blob: bf0b4302dbd5a60deeb7f5c667acf4d93dd5f9f0 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
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//
23//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.
35
36//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
John Kessenich140f3df2015-06-26 16:58:36 -060055#include <fstream>
Lei Zhang17535f72016-05-04 15:55:59 -040056#include <list>
57#include <map>
58#include <stack>
59#include <string>
60#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060061
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
qining4c912612016-04-01 10:35:16 -040069namespace {
70class SpecConstantOpModeGuard {
71public:
72 SpecConstantOpModeGuard(spv::Builder* builder)
73 : builder_(builder) {
74 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040075 }
76 ~SpecConstantOpModeGuard() {
77 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
78 : builder_->setToNormalCodeGenMode();
79 }
qining40887662016-04-03 22:20:42 -040080 void turnOnSpecConstantOpMode() {
81 builder_->setToSpecConstCodeGenMode();
82 }
qining4c912612016-04-01 10:35:16 -040083
84private:
85 spv::Builder* builder_;
86 bool previous_flag_;
87};
88}
89
John Kessenich140f3df2015-06-26 16:58:36 -060090//
91// The main holder of information for translating glslang to SPIR-V.
92//
93// Derives from the AST walking base class.
94//
95class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
96public:
Lei Zhang17535f72016-05-04 15:55:59 -040097 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenich140f3df2015-06-26 16:58:36 -060098 virtual ~TGlslangToSpvTraverser();
99
100 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
101 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
102 void visitConstantUnion(glslang::TIntermConstantUnion*);
103 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
104 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
105 void visitSymbol(glslang::TIntermSymbol* symbol);
106 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
107 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
108 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
109
John Kessenich7ba63412015-12-20 17:37:07 -0700110 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600111
112protected:
John Kessenich5e801132016-02-15 11:09:46 -0700113 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -0700114 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -0700115 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -0600116 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
117 spv::Id getSampledType(const glslang::TSampler&);
118 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700119 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -0700120 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700121 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800122 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700123 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700124 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
125 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
126 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
129 void makeFunctions(const glslang::TIntermSequence&);
130 void makeGlobalInitializers(const glslang::TIntermSequence&);
131 void visitFunctions(const glslang::TIntermSequence&);
132 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800133 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600134 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
135 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600136 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
137
138 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700139 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800140 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -0700141 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600142 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
143 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800144 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600145 spv::Id 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 -0600146 spv::Id createNoArgOperation(glslang::TOperator op);
147 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
148 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700149 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700151 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400152 spv::Id createSpvConstant(const glslang::TIntermTyped&);
153 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600154 bool isTrivialLeaf(const glslang::TIntermTyped* node);
155 bool isTrivial(const glslang::TIntermTyped* node);
156 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600157
158 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700159 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600160 int sequenceDepth;
161
Lei Zhang17535f72016-05-04 15:55:59 -0400162 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400163
John Kessenich140f3df2015-06-26 16:58:36 -0600164 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
165 spv::Builder builder;
166 bool inMain;
167 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700168 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 -0700169 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600170 const glslang::TIntermediate* glslangIntermediate;
171 spv::Id stdBuiltins;
172
John Kessenich2f273362015-07-18 22:34:27 -0600173 std::unordered_map<int, spv::Id> symbolValues;
174 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
175 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700176 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600177 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 -0600178 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600179};
180
181//
182// Helper functions for translating glslang representations to SPIR-V enumerants.
183//
184
185// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700186spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600187{
John Kessenich66e2faf2016-03-12 18:34:36 -0700188 switch (source) {
189 case glslang::EShSourceGlsl:
190 switch (profile) {
191 case ENoProfile:
192 case ECoreProfile:
193 case ECompatibilityProfile:
194 return spv::SourceLanguageGLSL;
195 case EEsProfile:
196 return spv::SourceLanguageESSL;
197 default:
198 return spv::SourceLanguageUnknown;
199 }
200 case glslang::EShSourceHlsl:
201 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 default:
203 return spv::SourceLanguageUnknown;
204 }
205}
206
207// Translate glslang language (stage) to SPIR-V execution model.
208spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
209{
210 switch (stage) {
211 case EShLangVertex: return spv::ExecutionModelVertex;
212 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
213 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
214 case EShLangGeometry: return spv::ExecutionModelGeometry;
215 case EShLangFragment: return spv::ExecutionModelFragment;
216 case EShLangCompute: return spv::ExecutionModelGLCompute;
217 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600219 return spv::ExecutionModelFragment;
220 }
221}
222
223// Translate glslang type to SPIR-V storage class.
224spv::StorageClass TranslateStorageClass(const glslang::TType& type)
225{
226 if (type.getQualifier().isPipeInput())
227 return spv::StorageClassInput;
228 else if (type.getQualifier().isPipeOutput())
229 return spv::StorageClassOutput;
230 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700231 if (type.getQualifier().layoutPushConstant)
232 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 if (type.getBasicType() == glslang::EbtBlock)
234 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800235 else if (type.getBasicType() == glslang::EbtAtomicUint)
236 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600237 else
238 return spv::StorageClassUniformConstant;
239 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
240 } else {
241 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700242 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
243 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600244 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
245 case glslang::EvqTemporary: return spv::StorageClassFunction;
246 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700247 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600248 return spv::StorageClassFunction;
249 }
250 }
251}
252
253// Translate glslang sampler type to SPIR-V dimensionality.
254spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
255{
256 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700257 case glslang::Esd1D: return spv::Dim1D;
258 case glslang::Esd2D: return spv::Dim2D;
259 case glslang::Esd3D: return spv::Dim3D;
260 case glslang::EsdCube: return spv::DimCube;
261 case glslang::EsdRect: return spv::DimRect;
262 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700263 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600264 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700265 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600266 return spv::Dim2D;
267 }
268}
269
270// Translate glslang type to SPIR-V precision decorations.
271spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
272{
273 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700274 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600275 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600276 default:
277 return spv::NoPrecision;
278 }
279}
280
281// Translate glslang type to SPIR-V block decorations.
282spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
283{
284 if (type.getBasicType() == glslang::EbtBlock) {
285 switch (type.getQualifier().storage) {
286 case glslang::EvqUniform: return spv::DecorationBlock;
287 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
288 case glslang::EvqVaryingIn: return spv::DecorationBlock;
289 case glslang::EvqVaryingOut: return spv::DecorationBlock;
290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 break;
293 }
294 }
295
296 return (spv::Decoration)spv::BadValue;
297}
298
Rex Xu1da878f2016-02-21 20:59:01 +0800299// Translate glslang type to SPIR-V memory decorations.
300void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
301{
302 if (qualifier.coherent)
303 memory.push_back(spv::DecorationCoherent);
304 if (qualifier.volatil)
305 memory.push_back(spv::DecorationVolatile);
306 if (qualifier.restrict)
307 memory.push_back(spv::DecorationRestrict);
308 if (qualifier.readonly)
309 memory.push_back(spv::DecorationNonWritable);
310 if (qualifier.writeonly)
311 memory.push_back(spv::DecorationNonReadable);
312}
313
John Kessenich140f3df2015-06-26 16:58:36 -0600314// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700315spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600316{
317 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700318 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600319 case glslang::ElmRowMajor:
320 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700321 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 default:
324 // opaque layouts don't need a majorness
325 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600326 }
327 } else {
328 switch (type.getBasicType()) {
329 default:
330 return (spv::Decoration)spv::BadValue;
331 break;
332 case glslang::EbtBlock:
333 switch (type.getQualifier().storage) {
334 case glslang::EvqUniform:
335 case glslang::EvqBuffer:
336 switch (type.getQualifier().layoutPacking) {
337 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600338 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
339 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600340 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 }
342 case glslang::EvqVaryingIn:
343 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700344 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return (spv::Decoration)spv::BadValue;
346 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600348 return (spv::Decoration)spv::BadValue;
349 }
350 }
351 }
352}
353
354// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700355// Returns spv::Decoration(spv::BadValue) when no decoration
356// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700357spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600358{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700359 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700360 // Smooth decoration doesn't exist in SPIR-V 1.0
361 return (spv::Decoration)spv::BadValue;
362 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700363 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700364 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700365 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600366 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700367 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700369 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600370 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700371 else if (qualifier.sample) {
372 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600373 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700374 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600375 return (spv::Decoration)spv::BadValue;
376}
377
John Kessenich92187592016-02-01 13:45:25 -0700378// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700379spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600380{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700381 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600382 return spv::DecorationInvariant;
383 else
384 return (spv::Decoration)spv::BadValue;
385}
386
387// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700388spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600389{
390 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700391 case glslang::EbvPointSize:
392 switch (glslangIntermediate->getStage()) {
393 case EShLangGeometry:
394 builder.addCapability(spv::CapabilityGeometryPointSize);
395 break;
396 case EShLangTessControl:
397 case EShLangTessEvaluation:
398 builder.addCapability(spv::CapabilityTessellationPointSize);
399 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100400 default:
401 break;
John Kessenich92187592016-02-01 13:45:25 -0700402 }
403 return spv::BuiltInPointSize;
404
405 case glslang::EbvClipDistance:
406 builder.addCapability(spv::CapabilityClipDistance);
407 return spv::BuiltInClipDistance;
408
409 case glslang::EbvCullDistance:
410 builder.addCapability(spv::CapabilityCullDistance);
411 return spv::BuiltInCullDistance;
412
413 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500414 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700415 return spv::BuiltInViewportIndex;
416
John Kessenich5e801132016-02-15 11:09:46 -0700417 case glslang::EbvSampleId:
418 builder.addCapability(spv::CapabilitySampleRateShading);
419 return spv::BuiltInSampleId;
420
421 case glslang::EbvSamplePosition:
422 builder.addCapability(spv::CapabilitySampleRateShading);
423 return spv::BuiltInSamplePosition;
424
425 case glslang::EbvSampleMask:
426 builder.addCapability(spv::CapabilitySampleRateShading);
427 return spv::BuiltInSampleMask;
428
John Kessenich140f3df2015-06-26 16:58:36 -0600429 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600430 case glslang::EbvVertexId: return spv::BuiltInVertexId;
431 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700432 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
433 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600434 case glslang::EbvBaseVertex:
435 case glslang::EbvBaseInstance:
436 case glslang::EbvDrawId:
437 // TODO: Add SPIR-V builtin ID.
Lei Zhang17535f72016-05-04 15:55:59 -0400438 logger->missingFunctionality("Draw parameters");
John Kessenichda581a22015-10-14 14:10:30 -0600439 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600440 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
441 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
442 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600443 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
444 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
445 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
446 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
447 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
448 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
449 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600450 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
451 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
452 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
453 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
454 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
455 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
456 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
457 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
458 default: return (spv::BuiltIn)spv::BadValue;
459 }
460}
461
Rex Xufc618912015-09-09 16:42:49 +0800462// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700463spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800464{
465 assert(type.getBasicType() == glslang::EbtSampler);
466
John Kessenich5d0fa972016-02-15 11:57:00 -0700467 // Check for capabilities
468 switch (type.getQualifier().layoutFormat) {
469 case glslang::ElfRg32f:
470 case glslang::ElfRg16f:
471 case glslang::ElfR11fG11fB10f:
472 case glslang::ElfR16f:
473 case glslang::ElfRgba16:
474 case glslang::ElfRgb10A2:
475 case glslang::ElfRg16:
476 case glslang::ElfRg8:
477 case glslang::ElfR16:
478 case glslang::ElfR8:
479 case glslang::ElfRgba16Snorm:
480 case glslang::ElfRg16Snorm:
481 case glslang::ElfRg8Snorm:
482 case glslang::ElfR16Snorm:
483 case glslang::ElfR8Snorm:
484
485 case glslang::ElfRg32i:
486 case glslang::ElfRg16i:
487 case glslang::ElfRg8i:
488 case glslang::ElfR16i:
489 case glslang::ElfR8i:
490
491 case glslang::ElfRgb10a2ui:
492 case glslang::ElfRg32ui:
493 case glslang::ElfRg16ui:
494 case glslang::ElfRg8ui:
495 case glslang::ElfR16ui:
496 case glslang::ElfR8ui:
497 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
498 break;
499
500 default:
501 break;
502 }
503
504 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800505 switch (type.getQualifier().layoutFormat) {
506 case glslang::ElfNone: return spv::ImageFormatUnknown;
507 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
508 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
509 case glslang::ElfR32f: return spv::ImageFormatR32f;
510 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
511 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
512 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
513 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
514 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
515 case glslang::ElfR16f: return spv::ImageFormatR16f;
516 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
517 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
518 case glslang::ElfRg16: return spv::ImageFormatRg16;
519 case glslang::ElfRg8: return spv::ImageFormatRg8;
520 case glslang::ElfR16: return spv::ImageFormatR16;
521 case glslang::ElfR8: return spv::ImageFormatR8;
522 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
523 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
524 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
525 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
526 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
527 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
528 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
529 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
530 case glslang::ElfR32i: return spv::ImageFormatR32i;
531 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
532 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
533 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
534 case glslang::ElfR16i: return spv::ImageFormatR16i;
535 case glslang::ElfR8i: return spv::ImageFormatR8i;
536 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
537 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
538 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
539 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
540 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
541 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
542 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
543 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
544 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
545 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
546 default: return (spv::ImageFormat)spv::BadValue;
547 }
548}
549
John Kessenich6c292d32016-02-15 20:58:50 -0700550// Return whether or not the given type is something that should be tied to a
551// descriptor set.
552bool IsDescriptorResource(const glslang::TType& type)
553{
John Kessenichf7497e22016-03-08 21:36:22 -0700554 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700555 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700556 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700557
558 // non block...
559 // basically samplerXXX/subpass/sampler/texture are all included
560 // if they are the global-scope-class, not the function parameter
561 // (or local, if they ever exist) class.
562 if (type.getBasicType() == glslang::EbtSampler)
563 return type.getQualifier().isUniformOrBuffer();
564
565 // None of the above.
566 return false;
567}
568
John Kesseniche0b6cad2015-12-24 10:30:13 -0700569void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
570{
571 if (child.layoutMatrix == glslang::ElmNone)
572 child.layoutMatrix = parent.layoutMatrix;
573
574 if (parent.invariant)
575 child.invariant = true;
576 if (parent.nopersp)
577 child.nopersp = true;
578 if (parent.flat)
579 child.flat = true;
580 if (parent.centroid)
581 child.centroid = true;
582 if (parent.patch)
583 child.patch = true;
584 if (parent.sample)
585 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800586 if (parent.coherent)
587 child.coherent = true;
588 if (parent.volatil)
589 child.volatil = true;
590 if (parent.restrict)
591 child.restrict = true;
592 if (parent.readonly)
593 child.readonly = true;
594 if (parent.writeonly)
595 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700596}
597
598bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
599{
John Kessenich7b9fa252016-01-21 18:56:57 -0700600 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700601 // - struct members can inherit from a struct declaration
602 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
603 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700604 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700605}
606
John Kessenich140f3df2015-06-26 16:58:36 -0600607//
608// Implement the TGlslangToSpvTraverser class.
609//
610
Lei Zhang17535f72016-05-04 15:55:59 -0400611TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
612 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0), logger(buildLogger),
613 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich140f3df2015-06-26 16:58:36 -0600614 inMain(false), mainTerminated(false), linkageOnly(false),
615 glslangIntermediate(glslangIntermediate)
616{
617 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
618
619 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700620 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600621 stdBuiltins = builder.import("GLSL.std.450");
622 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700623 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
624 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600625
626 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600627 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
628 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600629 builder.addSourceExtension(it->c_str());
630
631 // Add the top-level modes for this shader.
632
John Kessenich92187592016-02-01 13:45:25 -0700633 if (glslangIntermediate->getXfbMode()) {
634 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600635 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700636 }
John Kessenich140f3df2015-06-26 16:58:36 -0600637
638 unsigned int mode;
639 switch (glslangIntermediate->getStage()) {
640 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600641 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600642 break;
643
644 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600645 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600646 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
647 break;
648
649 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600650 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600651 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700652 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
653 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
654 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600655 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600656 }
657 if (mode != spv::BadValue)
658 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
659
John Kesseniche6903322015-10-13 16:29:02 -0600660 switch (glslangIntermediate->getVertexSpacing()) {
661 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
662 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
663 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
664 default: mode = spv::BadValue; break;
665 }
666 if (mode != spv::BadValue)
667 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
668
669 switch (glslangIntermediate->getVertexOrder()) {
670 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
671 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
672 default: mode = spv::BadValue; break;
673 }
674 if (mode != spv::BadValue)
675 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
676
677 if (glslangIntermediate->getPointMode())
678 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600679 break;
680
681 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600682 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600683 switch (glslangIntermediate->getInputPrimitive()) {
684 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
685 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
686 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700687 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600688 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
689 default: mode = spv::BadValue; break;
690 }
691 if (mode != spv::BadValue)
692 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600693
John Kessenich140f3df2015-06-26 16:58:36 -0600694 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
695
696 switch (glslangIntermediate->getOutputPrimitive()) {
697 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
698 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
699 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
700 default: mode = spv::BadValue; break;
701 }
702 if (mode != spv::BadValue)
703 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
704 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
705 break;
706
707 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600708 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600709 if (glslangIntermediate->getPixelCenterInteger())
710 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600711
John Kessenich140f3df2015-06-26 16:58:36 -0600712 if (glslangIntermediate->getOriginUpperLeft())
713 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600714 else
715 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600716
717 if (glslangIntermediate->getEarlyFragmentTests())
718 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
719
720 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600721 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
722 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
723 default: mode = spv::BadValue; break;
724 }
725 if (mode != spv::BadValue)
726 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
727
728 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
729 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600730 break;
731
732 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600733 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600734 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
735 glslangIntermediate->getLocalSize(1),
736 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600737 break;
738
739 default:
740 break;
741 }
742
743}
744
John Kessenich7ba63412015-12-20 17:37:07 -0700745// Finish everything and dump
746void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
747{
748 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100749 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
750 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700751
qiningda397332016-03-09 19:54:03 -0500752 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700753 builder.dump(out);
754}
755
John Kessenich140f3df2015-06-26 16:58:36 -0600756TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
757{
758 if (! mainTerminated) {
759 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
760 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600761 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600762 }
763}
764
765//
766// Implement the traversal functions.
767//
768// Return true from interior nodes to have the external traversal
769// continue on to children. Return false if children were
770// already processed.
771//
772
773//
774// Symbols can turn into
775// - uniform/input reads
776// - output writes
777// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
778// - something simple that degenerates into the last bullet
779//
780void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
781{
qining75d1d802016-04-06 14:42:01 -0400782 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
783 if (symbol->getType().getQualifier().isSpecConstant())
784 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
785
John Kessenich140f3df2015-06-26 16:58:36 -0600786 // getSymbolId() will set up all the IO decorations on the first call.
787 // Formal function parameters were mapped during makeFunctions().
788 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700789
790 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
791 if (builder.isPointer(id)) {
792 spv::StorageClass sc = builder.getStorageClass(id);
793 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
794 iOSet.insert(id);
795 }
796
797 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700798 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600799 // Prepare to generate code for the access
800
801 // L-value chains will be computed left to right. We're on the symbol now,
802 // which is the left-most part of the access chain, so now is "clear" time,
803 // followed by setting the base.
804 builder.clearAccessChain();
805
806 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700807 // except for
808 // A) "const in" arguments to a function, which are an intermediate object.
809 // See comments in handleUserFunctionCall().
810 // B) Specialization constants (normal constant don't even come in as a variable),
811 // These are also pure R-values.
812 glslang::TQualifier qualifier = symbol->getQualifier();
813 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
814 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600815 builder.setAccessChainRValue(id);
816 else
817 builder.setAccessChainLValue(id);
818 }
819}
820
821bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
822{
qining40887662016-04-03 22:20:42 -0400823 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
824 if (node->getType().getQualifier().isSpecConstant())
825 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
826
John Kessenich140f3df2015-06-26 16:58:36 -0600827 // First, handle special cases
828 switch (node->getOp()) {
829 case glslang::EOpAssign:
830 case glslang::EOpAddAssign:
831 case glslang::EOpSubAssign:
832 case glslang::EOpMulAssign:
833 case glslang::EOpVectorTimesMatrixAssign:
834 case glslang::EOpVectorTimesScalarAssign:
835 case glslang::EOpMatrixTimesScalarAssign:
836 case glslang::EOpMatrixTimesMatrixAssign:
837 case glslang::EOpDivAssign:
838 case glslang::EOpModAssign:
839 case glslang::EOpAndAssign:
840 case glslang::EOpInclusiveOrAssign:
841 case glslang::EOpExclusiveOrAssign:
842 case glslang::EOpLeftShiftAssign:
843 case glslang::EOpRightShiftAssign:
844 // A bin-op assign "a += b" means the same thing as "a = a + b"
845 // where a is evaluated before b. For a simple assignment, GLSL
846 // says to evaluate the left before the right. So, always, left
847 // node then right node.
848 {
849 // get the left l-value, save it away
850 builder.clearAccessChain();
851 node->getLeft()->traverse(this);
852 spv::Builder::AccessChain lValue = builder.getAccessChain();
853
854 // evaluate the right
855 builder.clearAccessChain();
856 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700857 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600858
859 if (node->getOp() != glslang::EOpAssign) {
860 // the left is also an r-value
861 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700862 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600863
864 // do the operation
865 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
866 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
867 node->getType().getBasicType());
868
869 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700870 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600871 }
872
873 // store the result
874 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800875 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600876
877 // assignments are expressions having an rValue after they are evaluated...
878 builder.clearAccessChain();
879 builder.setAccessChainRValue(rValue);
880 }
881 return false;
882 case glslang::EOpIndexDirect:
883 case glslang::EOpIndexDirectStruct:
884 {
885 // Get the left part of the access chain.
886 node->getLeft()->traverse(this);
887
888 // Add the next element in the chain
889
John Kessenich55e7d112015-11-15 21:33:39 -0700890 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600891 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
892 // This may be, e.g., an anonymous block-member selection, which generally need
893 // index remapping due to hidden members in anonymous blocks.
894 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700895 assert(remapper.size() > 0);
896 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600897 }
898
899 if (! node->getLeft()->getType().isArray() &&
900 node->getLeft()->getType().isVector() &&
901 node->getOp() == glslang::EOpIndexDirect) {
902 // This is essentially a hard-coded vector swizzle of size 1,
903 // so short circuit the access-chain stuff with a swizzle.
904 std::vector<unsigned> swizzle;
905 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600906 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600907 } else {
908 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600909 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600910 }
911 }
912 return false;
913 case glslang::EOpIndexIndirect:
914 {
915 // Structure or array or vector indirection.
916 // Will use native SPIR-V access-chain for struct and array indirection;
917 // matrices are arrays of vectors, so will also work for a matrix.
918 // Will use the access chain's 'component' for variable index into a vector.
919
920 // This adapter is building access chains left to right.
921 // Set up the access chain to the left.
922 node->getLeft()->traverse(this);
923
924 // save it so that computing the right side doesn't trash it
925 spv::Builder::AccessChain partial = builder.getAccessChain();
926
927 // compute the next index in the chain
928 builder.clearAccessChain();
929 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700930 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600931
932 // restore the saved access chain
933 builder.setAccessChain(partial);
934
935 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600936 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600937 else
John Kessenichfa668da2015-09-13 14:46:30 -0600938 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600939 }
940 return false;
941 case glslang::EOpVectorSwizzle:
942 {
943 node->getLeft()->traverse(this);
944 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
945 std::vector<unsigned> swizzle;
946 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
947 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600948 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600949 }
950 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600951 case glslang::EOpLogicalOr:
952 case glslang::EOpLogicalAnd:
953 {
954
955 // These may require short circuiting, but can sometimes be done as straight
956 // binary operations. The right operand must be short circuited if it has
957 // side effects, and should probably be if it is complex.
958 if (isTrivial(node->getRight()->getAsTyped()))
959 break; // handle below as a normal binary operation
960 // otherwise, we need to do dynamic short circuiting on the right operand
961 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
962 builder.clearAccessChain();
963 builder.setAccessChainRValue(result);
964 }
965 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600966 default:
967 break;
968 }
969
970 // Assume generic binary op...
971
John Kessenich32cfd492016-02-02 12:37:46 -0700972 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600973 builder.clearAccessChain();
974 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700975 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600976
John Kessenich32cfd492016-02-02 12:37:46 -0700977 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600978 builder.clearAccessChain();
979 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700980 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600981
John Kessenich32cfd492016-02-02 12:37:46 -0700982 // get result
983 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
984 convertGlslangToSpvType(node->getType()), left, right,
985 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600986
John Kessenich50e57562015-12-21 21:21:11 -0700987 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600988 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -0400989 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700990 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600991 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600992 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600993 return false;
994 }
John Kessenich140f3df2015-06-26 16:58:36 -0600995}
996
997bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
998{
qining40887662016-04-03 22:20:42 -0400999 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1000 if (node->getType().getQualifier().isSpecConstant())
1001 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1002
John Kessenichfc51d282015-08-19 13:34:18 -06001003 spv::Id result = spv::NoResult;
1004
1005 // try texturing first
1006 result = createImageTextureFunctionCall(node);
1007 if (result != spv::NoResult) {
1008 builder.clearAccessChain();
1009 builder.setAccessChainRValue(result);
1010
1011 return false; // done with this node
1012 }
1013
1014 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001015
1016 if (node->getOp() == glslang::EOpArrayLength) {
1017 // Quite special; won't want to evaluate the operand.
1018
1019 // Normal .length() would have been constant folded by the front-end.
1020 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001021 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001022 assert(node->getOperand()->getType().isRuntimeSizedArray());
1023 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1024 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001025 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1026 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001027
1028 builder.clearAccessChain();
1029 builder.setAccessChainRValue(length);
1030
1031 return false;
1032 }
1033
John Kessenichfc51d282015-08-19 13:34:18 -06001034 // Start by evaluating the operand
1035
John Kessenich140f3df2015-06-26 16:58:36 -06001036 builder.clearAccessChain();
1037 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001038
Rex Xufc618912015-09-09 16:42:49 +08001039 spv::Id operand = spv::NoResult;
1040
1041 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1042 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001043 node->getOp() == glslang::EOpAtomicCounter ||
1044 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001045 operand = builder.accessChainGetLValue(); // Special case l-value operands
1046 else
John Kessenich32cfd492016-02-02 12:37:46 -07001047 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001048
1049 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1050
1051 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001052 if (! result)
1053 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001054
1055 // if not, then possibly an operation
1056 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001057 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001058
1059 if (result) {
1060 builder.clearAccessChain();
1061 builder.setAccessChainRValue(result);
1062
1063 return false; // done with this node
1064 }
1065
1066 // it must be a special case, check...
1067 switch (node->getOp()) {
1068 case glslang::EOpPostIncrement:
1069 case glslang::EOpPostDecrement:
1070 case glslang::EOpPreIncrement:
1071 case glslang::EOpPreDecrement:
1072 {
1073 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001074 spv::Id one = 0;
1075 if (node->getBasicType() == glslang::EbtFloat)
1076 one = builder.makeFloatConstant(1.0F);
1077 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1078 one = builder.makeInt64Constant(1);
1079 else
1080 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001081 glslang::TOperator op;
1082 if (node->getOp() == glslang::EOpPreIncrement ||
1083 node->getOp() == glslang::EOpPostIncrement)
1084 op = glslang::EOpAdd;
1085 else
1086 op = glslang::EOpSub;
1087
1088 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001089 convertGlslangToSpvType(node->getType()), operand, one,
1090 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001091 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001092
1093 // The result of operation is always stored, but conditionally the
1094 // consumed result. The consumed result is always an r-value.
1095 builder.accessChainStore(result);
1096 builder.clearAccessChain();
1097 if (node->getOp() == glslang::EOpPreIncrement ||
1098 node->getOp() == glslang::EOpPreDecrement)
1099 builder.setAccessChainRValue(result);
1100 else
1101 builder.setAccessChainRValue(operand);
1102 }
1103
1104 return false;
1105
1106 case glslang::EOpEmitStreamVertex:
1107 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1108 return false;
1109 case glslang::EOpEndStreamPrimitive:
1110 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1111 return false;
1112
1113 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001114 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001115 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001116 }
John Kessenich140f3df2015-06-26 16:58:36 -06001117}
1118
1119bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1120{
qining27e04a02016-04-14 16:40:20 -04001121 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1122 if (node->getType().getQualifier().isSpecConstant())
1123 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1124
John Kessenichfc51d282015-08-19 13:34:18 -06001125 spv::Id result = spv::NoResult;
1126
1127 // try texturing
1128 result = createImageTextureFunctionCall(node);
1129 if (result != spv::NoResult) {
1130 builder.clearAccessChain();
1131 builder.setAccessChainRValue(result);
1132
1133 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001134 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001135 // "imageStore" is a special case, which has no result
1136 return false;
1137 }
John Kessenichfc51d282015-08-19 13:34:18 -06001138
John Kessenich140f3df2015-06-26 16:58:36 -06001139 glslang::TOperator binOp = glslang::EOpNull;
1140 bool reduceComparison = true;
1141 bool isMatrix = false;
1142 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001143 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 assert(node->getOp());
1146
1147 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1148
1149 switch (node->getOp()) {
1150 case glslang::EOpSequence:
1151 {
1152 if (preVisit)
1153 ++sequenceDepth;
1154 else
1155 --sequenceDepth;
1156
1157 if (sequenceDepth == 1) {
1158 // If this is the parent node of all the functions, we want to see them
1159 // early, so all call points have actual SPIR-V functions to reference.
1160 // In all cases, still let the traverser visit the children for us.
1161 makeFunctions(node->getAsAggregate()->getSequence());
1162
1163 // Also, we want all globals initializers to go into the entry of main(), before
1164 // anything else gets there, so visit out of order, doing them all now.
1165 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1166
1167 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1168 // so do them manually.
1169 visitFunctions(node->getAsAggregate()->getSequence());
1170
1171 return false;
1172 }
1173
1174 return true;
1175 }
1176 case glslang::EOpLinkerObjects:
1177 {
1178 if (visit == glslang::EvPreVisit)
1179 linkageOnly = true;
1180 else
1181 linkageOnly = false;
1182
1183 return true;
1184 }
1185 case glslang::EOpComma:
1186 {
1187 // processing from left to right naturally leaves the right-most
1188 // lying around in the access chain
1189 glslang::TIntermSequence& glslangOperands = node->getSequence();
1190 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1191 glslangOperands[i]->traverse(this);
1192
1193 return false;
1194 }
1195 case glslang::EOpFunction:
1196 if (visit == glslang::EvPreVisit) {
1197 if (isShaderEntrypoint(node)) {
1198 inMain = true;
1199 builder.setBuildPoint(shaderEntry->getLastBlock());
1200 } else {
1201 handleFunctionEntry(node);
1202 }
1203 } else {
1204 if (inMain)
1205 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001206 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001207 inMain = false;
1208 }
1209
1210 return true;
1211 case glslang::EOpParameters:
1212 // Parameters will have been consumed by EOpFunction processing, but not
1213 // the body, so we still visited the function node's children, making this
1214 // child redundant.
1215 return false;
1216 case glslang::EOpFunctionCall:
1217 {
1218 if (node->isUserDefined())
1219 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001220 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1221 if (result) {
1222 builder.clearAccessChain();
1223 builder.setAccessChainRValue(result);
1224 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001225 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001226
1227 return false;
1228 }
1229 case glslang::EOpConstructMat2x2:
1230 case glslang::EOpConstructMat2x3:
1231 case glslang::EOpConstructMat2x4:
1232 case glslang::EOpConstructMat3x2:
1233 case glslang::EOpConstructMat3x3:
1234 case glslang::EOpConstructMat3x4:
1235 case glslang::EOpConstructMat4x2:
1236 case glslang::EOpConstructMat4x3:
1237 case glslang::EOpConstructMat4x4:
1238 case glslang::EOpConstructDMat2x2:
1239 case glslang::EOpConstructDMat2x3:
1240 case glslang::EOpConstructDMat2x4:
1241 case glslang::EOpConstructDMat3x2:
1242 case glslang::EOpConstructDMat3x3:
1243 case glslang::EOpConstructDMat3x4:
1244 case glslang::EOpConstructDMat4x2:
1245 case glslang::EOpConstructDMat4x3:
1246 case glslang::EOpConstructDMat4x4:
1247 isMatrix = true;
1248 // fall through
1249 case glslang::EOpConstructFloat:
1250 case glslang::EOpConstructVec2:
1251 case glslang::EOpConstructVec3:
1252 case glslang::EOpConstructVec4:
1253 case glslang::EOpConstructDouble:
1254 case glslang::EOpConstructDVec2:
1255 case glslang::EOpConstructDVec3:
1256 case glslang::EOpConstructDVec4:
1257 case glslang::EOpConstructBool:
1258 case glslang::EOpConstructBVec2:
1259 case glslang::EOpConstructBVec3:
1260 case glslang::EOpConstructBVec4:
1261 case glslang::EOpConstructInt:
1262 case glslang::EOpConstructIVec2:
1263 case glslang::EOpConstructIVec3:
1264 case glslang::EOpConstructIVec4:
1265 case glslang::EOpConstructUint:
1266 case glslang::EOpConstructUVec2:
1267 case glslang::EOpConstructUVec3:
1268 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001269 case glslang::EOpConstructInt64:
1270 case glslang::EOpConstructI64Vec2:
1271 case glslang::EOpConstructI64Vec3:
1272 case glslang::EOpConstructI64Vec4:
1273 case glslang::EOpConstructUint64:
1274 case glslang::EOpConstructU64Vec2:
1275 case glslang::EOpConstructU64Vec3:
1276 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001277 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001278 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001279 {
1280 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001281 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001282 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1283 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001284 if (node->getOp() == glslang::EOpConstructTextureSampler)
1285 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1286 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001287 std::vector<spv::Id> constituents;
1288 for (int c = 0; c < (int)arguments.size(); ++c)
1289 constituents.push_back(arguments[c]);
1290 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001291 } else if (isMatrix)
1292 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1293 else
1294 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001295
1296 builder.clearAccessChain();
1297 builder.setAccessChainRValue(constructed);
1298
1299 return false;
1300 }
1301
1302 // These six are component-wise compares with component-wise results.
1303 // Forward on to createBinaryOperation(), requesting a vector result.
1304 case glslang::EOpLessThan:
1305 case glslang::EOpGreaterThan:
1306 case glslang::EOpLessThanEqual:
1307 case glslang::EOpGreaterThanEqual:
1308 case glslang::EOpVectorEqual:
1309 case glslang::EOpVectorNotEqual:
1310 {
1311 // Map the operation to a binary
1312 binOp = node->getOp();
1313 reduceComparison = false;
1314 switch (node->getOp()) {
1315 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1316 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1317 default: binOp = node->getOp(); break;
1318 }
1319
1320 break;
1321 }
1322 case glslang::EOpMul:
1323 // compontent-wise matrix multiply
1324 binOp = glslang::EOpMul;
1325 break;
1326 case glslang::EOpOuterProduct:
1327 // two vectors multiplied to make a matrix
1328 binOp = glslang::EOpOuterProduct;
1329 break;
1330 case glslang::EOpDot:
1331 {
1332 // for scalar dot product, use multiply
1333 glslang::TIntermSequence& glslangOperands = node->getSequence();
1334 if (! glslangOperands[0]->getAsTyped()->isVector())
1335 binOp = glslang::EOpMul;
1336 break;
1337 }
1338 case glslang::EOpMod:
1339 // when an aggregate, this is the floating-point mod built-in function,
1340 // which can be emitted by the one in createBinaryOperation()
1341 binOp = glslang::EOpMod;
1342 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001343 case glslang::EOpEmitVertex:
1344 case glslang::EOpEndPrimitive:
1345 case glslang::EOpBarrier:
1346 case glslang::EOpMemoryBarrier:
1347 case glslang::EOpMemoryBarrierAtomicCounter:
1348 case glslang::EOpMemoryBarrierBuffer:
1349 case glslang::EOpMemoryBarrierImage:
1350 case glslang::EOpMemoryBarrierShared:
1351 case glslang::EOpGroupMemoryBarrier:
1352 noReturnValue = true;
1353 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1354 break;
1355
John Kessenich426394d2015-07-23 10:22:48 -06001356 case glslang::EOpAtomicAdd:
1357 case glslang::EOpAtomicMin:
1358 case glslang::EOpAtomicMax:
1359 case glslang::EOpAtomicAnd:
1360 case glslang::EOpAtomicOr:
1361 case glslang::EOpAtomicXor:
1362 case glslang::EOpAtomicExchange:
1363 case glslang::EOpAtomicCompSwap:
1364 atomic = true;
1365 break;
1366
John Kessenich140f3df2015-06-26 16:58:36 -06001367 default:
1368 break;
1369 }
1370
1371 //
1372 // See if it maps to a regular operation.
1373 //
John Kessenich140f3df2015-06-26 16:58:36 -06001374 if (binOp != glslang::EOpNull) {
1375 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1376 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1377 assert(left && right);
1378
1379 builder.clearAccessChain();
1380 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001381 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001382
1383 builder.clearAccessChain();
1384 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001385 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001386
1387 result = createBinaryOperation(binOp, precision,
1388 convertGlslangToSpvType(node->getType()), leftId, rightId,
1389 left->getType().getBasicType(), reduceComparison);
1390
1391 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001392 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001393 builder.clearAccessChain();
1394 builder.setAccessChainRValue(result);
1395
1396 return false;
1397 }
1398
John Kessenich426394d2015-07-23 10:22:48 -06001399 //
1400 // Create the list of operands.
1401 //
John Kessenich140f3df2015-06-26 16:58:36 -06001402 glslang::TIntermSequence& glslangOperands = node->getSequence();
1403 std::vector<spv::Id> operands;
1404 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1405 builder.clearAccessChain();
1406 glslangOperands[arg]->traverse(this);
1407
1408 // special case l-value operands; there are just a few
1409 bool lvalue = false;
1410 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001411 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001412 case glslang::EOpModf:
1413 if (arg == 1)
1414 lvalue = true;
1415 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001416 case glslang::EOpInterpolateAtSample:
1417 case glslang::EOpInterpolateAtOffset:
1418 if (arg == 0)
1419 lvalue = true;
1420 break;
Rex Xud4782c12015-09-06 16:30:11 +08001421 case glslang::EOpAtomicAdd:
1422 case glslang::EOpAtomicMin:
1423 case glslang::EOpAtomicMax:
1424 case glslang::EOpAtomicAnd:
1425 case glslang::EOpAtomicOr:
1426 case glslang::EOpAtomicXor:
1427 case glslang::EOpAtomicExchange:
1428 case glslang::EOpAtomicCompSwap:
1429 if (arg == 0)
1430 lvalue = true;
1431 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001432 case glslang::EOpAddCarry:
1433 case glslang::EOpSubBorrow:
1434 if (arg == 2)
1435 lvalue = true;
1436 break;
1437 case glslang::EOpUMulExtended:
1438 case glslang::EOpIMulExtended:
1439 if (arg >= 2)
1440 lvalue = true;
1441 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001442 default:
1443 break;
1444 }
1445 if (lvalue)
1446 operands.push_back(builder.accessChainGetLValue());
1447 else
John Kessenich32cfd492016-02-02 12:37:46 -07001448 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001449 }
John Kessenich426394d2015-07-23 10:22:48 -06001450
1451 if (atomic) {
1452 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001453 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001454 } else {
1455 // Pass through to generic operations.
1456 switch (glslangOperands.size()) {
1457 case 0:
1458 result = createNoArgOperation(node->getOp());
1459 break;
1460 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001461 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001462 break;
1463 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001464 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001465 break;
1466 }
John Kessenich140f3df2015-06-26 16:58:36 -06001467 }
1468
1469 if (noReturnValue)
1470 return false;
1471
1472 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001473 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001474 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001475 } else {
1476 builder.clearAccessChain();
1477 builder.setAccessChainRValue(result);
1478 return false;
1479 }
1480}
1481
1482bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1483{
1484 // This path handles both if-then-else and ?:
1485 // The if-then-else has a node type of void, while
1486 // ?: has a non-void node type
1487 spv::Id result = 0;
1488 if (node->getBasicType() != glslang::EbtVoid) {
1489 // don't handle this as just on-the-fly temporaries, because there will be two names
1490 // and better to leave SSA to later passes
1491 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1492 }
1493
1494 // emit the condition before doing anything with selection
1495 node->getCondition()->traverse(this);
1496
1497 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001498 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001499
1500 if (node->getTrueBlock()) {
1501 // emit the "then" statement
1502 node->getTrueBlock()->traverse(this);
1503 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001504 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001505 }
1506
1507 if (node->getFalseBlock()) {
1508 ifBuilder.makeBeginElse();
1509 // emit the "else" statement
1510 node->getFalseBlock()->traverse(this);
1511 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001512 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001513 }
1514
1515 ifBuilder.makeEndIf();
1516
1517 if (result) {
1518 // GLSL only has r-values as the result of a :?, but
1519 // if we have an l-value, that can be more efficient if it will
1520 // become the base of a complex r-value expression, because the
1521 // next layer copies r-values into memory to use the access-chain mechanism
1522 builder.clearAccessChain();
1523 builder.setAccessChainLValue(result);
1524 }
1525
1526 return false;
1527}
1528
1529bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1530{
1531 // emit and get the condition before doing anything with switch
1532 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001533 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001534
1535 // browse the children to sort out code segments
1536 int defaultSegment = -1;
1537 std::vector<TIntermNode*> codeSegments;
1538 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1539 std::vector<int> caseValues;
1540 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1541 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1542 TIntermNode* child = *c;
1543 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001544 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001545 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001546 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001547 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1548 } else
1549 codeSegments.push_back(child);
1550 }
1551
1552 // handle the case where the last code segment is missing, due to no code
1553 // statements between the last case and the end of the switch statement
1554 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1555 (int)codeSegments.size() == defaultSegment)
1556 codeSegments.push_back(nullptr);
1557
1558 // make the switch statement
1559 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001560 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001561
1562 // emit all the code in the segments
1563 breakForLoop.push(false);
1564 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1565 builder.nextSwitchSegment(segmentBlocks, s);
1566 if (codeSegments[s])
1567 codeSegments[s]->traverse(this);
1568 else
1569 builder.addSwitchBreak();
1570 }
1571 breakForLoop.pop();
1572
1573 builder.endSwitch(segmentBlocks);
1574
1575 return false;
1576}
1577
1578void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1579{
1580 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001581 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001582
1583 builder.clearAccessChain();
1584 builder.setAccessChainRValue(constant);
1585}
1586
1587bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1588{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001589 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001590 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001591 // Spec requires back edges to target header blocks, and every header block
1592 // must dominate its merge block. Make a header block first to ensure these
1593 // conditions are met. By definition, it will contain OpLoopMerge, followed
1594 // by a block-ending branch. But we don't want to put any other body/test
1595 // instructions in it, since the body/test may have arbitrary instructions,
1596 // including merges of its own.
1597 builder.setBuildPoint(&blocks.head);
1598 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001599 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001600 spv::Block& test = builder.makeNewBlock();
1601 builder.createBranch(&test);
1602
1603 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001604 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001605 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001606 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001607 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1608
1609 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001610 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001611 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001612 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001613 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001614 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001615
1616 builder.setBuildPoint(&blocks.continue_target);
1617 if (node->getTerminal())
1618 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001619 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001620 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001621 builder.createBranch(&blocks.body);
1622
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001623 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001624 builder.setBuildPoint(&blocks.body);
1625 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001626 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001627 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001628 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001629
1630 builder.setBuildPoint(&blocks.continue_target);
1631 if (node->getTerminal())
1632 node->getTerminal()->traverse(this);
1633 if (node->getTest()) {
1634 node->getTest()->traverse(this);
1635 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001636 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001637 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001638 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001639 // TODO: unless there was a break/return/discard instruction
1640 // somewhere in the body, this is an infinite loop, so we should
1641 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001642 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001643 }
John Kessenich140f3df2015-06-26 16:58:36 -06001644 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001645 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001646 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001647 return false;
1648}
1649
1650bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1651{
1652 if (node->getExpression())
1653 node->getExpression()->traverse(this);
1654
1655 switch (node->getFlowOp()) {
1656 case glslang::EOpKill:
1657 builder.makeDiscard();
1658 break;
1659 case glslang::EOpBreak:
1660 if (breakForLoop.top())
1661 builder.createLoopExit();
1662 else
1663 builder.addSwitchBreak();
1664 break;
1665 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001666 builder.createLoopContinue();
1667 break;
1668 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001669 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001670 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001671 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001672 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001673
1674 builder.clearAccessChain();
1675 break;
1676
1677 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001678 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001679 break;
1680 }
1681
1682 return false;
1683}
1684
1685spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1686{
1687 // First, steer off constants, which are not SPIR-V variables, but
1688 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001689 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001690 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001691 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001692 }
1693
1694 // Now, handle actual variables
1695 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1696 spv::Id spvType = convertGlslangToSpvType(node->getType());
1697
1698 const char* name = node->getName().c_str();
1699 if (glslang::IsAnonymous(name))
1700 name = "";
1701
1702 return builder.createVariable(storageClass, spvType, name);
1703}
1704
1705// Return type Id of the sampled type.
1706spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1707{
1708 switch (sampler.type) {
1709 case glslang::EbtFloat: return builder.makeFloatType(32);
1710 case glslang::EbtInt: return builder.makeIntType(32);
1711 case glslang::EbtUint: return builder.makeUintType(32);
1712 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001713 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001714 return builder.makeFloatType(32);
1715 }
1716}
1717
John Kessenich3ac051e2015-12-20 11:29:16 -07001718// Convert from a glslang type to an SPV type, by calling into a
1719// recursive version of this function. This establishes the inherited
1720// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001721spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1722{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001723 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001724}
1725
1726// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001727// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001728spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001729{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001730 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001731
1732 switch (type.getBasicType()) {
1733 case glslang::EbtVoid:
1734 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001735 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001736 break;
1737 case glslang::EbtFloat:
1738 spvType = builder.makeFloatType(32);
1739 break;
1740 case glslang::EbtDouble:
1741 spvType = builder.makeFloatType(64);
1742 break;
1743 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001744 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1745 // a 32-bit int where non-0 means true.
1746 if (explicitLayout != glslang::ElpNone)
1747 spvType = builder.makeUintType(32);
1748 else
1749 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001750 break;
1751 case glslang::EbtInt:
1752 spvType = builder.makeIntType(32);
1753 break;
1754 case glslang::EbtUint:
1755 spvType = builder.makeUintType(32);
1756 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08001757 case glslang::EbtInt64:
1758 builder.addCapability(spv::CapabilityInt64);
1759 spvType = builder.makeIntType(64);
1760 break;
1761 case glslang::EbtUint64:
1762 builder.addCapability(spv::CapabilityInt64);
1763 spvType = builder.makeUintType(64);
1764 break;
John Kessenich426394d2015-07-23 10:22:48 -06001765 case glslang::EbtAtomicUint:
Lei Zhang17535f72016-05-04 15:55:59 -04001766 logger->tbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
John Kessenich426394d2015-07-23 10:22:48 -06001767 spvType = builder.makeUintType(32);
1768 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001769 case glslang::EbtSampler:
1770 {
1771 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001772 if (sampler.sampler) {
1773 // pure sampler
1774 spvType = builder.makeSamplerType();
1775 } else {
1776 // an image is present, make its type
1777 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1778 sampler.image ? 2 : 1, TranslateImageFormat(type));
1779 if (sampler.combined) {
1780 // already has both image and sampler, make the combined type
1781 spvType = builder.makeSampledImageType(spvType);
1782 }
John Kessenich55e7d112015-11-15 21:33:39 -07001783 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001784 }
John Kessenich140f3df2015-06-26 16:58:36 -06001785 break;
1786 case glslang::EbtStruct:
1787 case glslang::EbtBlock:
1788 {
1789 // If we've seen this struct type, return it
1790 const glslang::TTypeList* glslangStruct = type.getStruct();
1791 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001792
1793 // Try to share structs for different layouts, but not yet for other
1794 // kinds of qualification (primarily not yet including interpolant qualification).
1795 if (! HasNonLayoutQualifiers(qualifier))
1796 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1797 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001798 break;
1799
1800 // else, we haven't seen it...
1801
1802 // Create a vector of struct types for SPIR-V to consume
1803 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1804 if (type.getBasicType() == glslang::EbtBlock)
1805 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001806 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001807 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1808 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1809 if (glslangType.hiddenMember()) {
1810 ++memberDelta;
1811 if (type.getBasicType() == glslang::EbtBlock)
1812 memberRemapper[glslangStruct][i] = -1;
1813 } else {
1814 if (type.getBasicType() == glslang::EbtBlock)
1815 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001816 // modify just this child's view of the qualifier
1817 glslang::TQualifier subQualifier = glslangType.getQualifier();
1818 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001819
1820 // manually inherit location; it's more complex
1821 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1822 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1823 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001824 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001825
1826 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001827 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001828 }
1829 }
1830
1831 // Make the SPIR-V type
1832 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001833 if (! HasNonLayoutQualifiers(qualifier))
1834 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001835
1836 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001837 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001838 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001839 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1840 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1841 int member = i;
1842 if (type.getBasicType() == glslang::EbtBlock)
1843 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001844
John Kesseniche0b6cad2015-12-24 10:30:13 -07001845 // modify just this child's view of the qualifier
1846 glslang::TQualifier subQualifier = glslangType.getQualifier();
1847 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001848
John Kessenich140f3df2015-06-26 16:58:36 -06001849 // using -1 above to indicate a hidden member
1850 if (member >= 0) {
1851 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001852 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001853 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001854 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1855 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001856
Rex Xu1da878f2016-02-21 20:59:01 +08001857 if (qualifier.storage == glslang::EvqBuffer) {
1858 std::vector<spv::Decoration> memory;
1859 TranslateMemoryDecoration(subQualifier, memory);
1860 for (unsigned int i = 0; i < memory.size(); ++i)
1861 addMemberDecoration(spvType, member, memory[i]);
1862 }
1863
John Kessenich09677482016-02-19 12:21:50 -07001864 // compute location decoration; tricky based on whether inheritance is at play
1865 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1866 // probably move to the linker stage of the front end proper, and just have the
1867 // answer sitting already distributed throughout the individual member locations.
1868 int location = -1; // will only decorate if present or inherited
1869 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1870 location = subQualifier.layoutLocation;
1871 else if (qualifier.hasLocation()) // inheritance
1872 location = qualifier.layoutLocation + locationOffset;
1873 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001874 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001875 if (location >= 0)
1876 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1877
1878 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001879 if (glslangType.getQualifier().hasComponent())
1880 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1881 if (glslangType.getQualifier().hasXfbOffset())
1882 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001883 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001884 // figure out what to do with offset, which is accumulating
1885 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001886 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001887 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001888 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001889 offset = nextOffset;
1890 }
John Kessenich140f3df2015-06-26 16:58:36 -06001891
John Kessenichf85e8062015-12-19 13:57:10 -07001892 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001893 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001894
John Kessenich140f3df2015-06-26 16:58:36 -06001895 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001896 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1897 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001898 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001899 }
1900 }
1901
1902 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001903 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001904 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001905 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001906 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001907 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001908 }
John Kessenich140f3df2015-06-26 16:58:36 -06001909 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001910 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001911 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001912 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001913 if (type.getQualifier().hasXfbBuffer())
1914 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1915 }
1916 }
1917 break;
1918 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001919 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001920 break;
1921 }
1922
1923 if (type.isMatrix())
1924 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1925 else {
1926 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1927 if (type.getVectorSize() > 1)
1928 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1929 }
1930
1931 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001932 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1933
John Kessenichc9a80832015-09-12 12:17:44 -06001934 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001935 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001936 // We need to decorate array strides for types needing explicit layout, except blocks.
1937 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001938 // Use a dummy glslang type for querying internal strides of
1939 // arrays of arrays, but using just a one-dimensional array.
1940 glslang::TType simpleArrayType(type, 0); // deference type of the array
1941 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1942 simpleArrayType.getArraySizes().dereference();
1943
1944 // Will compute the higher-order strides here, rather than making a whole
1945 // pile of types and doing repetitive recursion on their contents.
1946 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1947 }
John Kessenichf8842e52016-01-04 19:22:56 -07001948
1949 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001950 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001951 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001952 if (stride > 0)
1953 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001954 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001955 }
1956 } else {
1957 // single-dimensional array, and don't yet have stride
1958
John Kessenichf8842e52016-01-04 19:22:56 -07001959 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001960 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1961 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001962 }
John Kessenich31ed4832015-09-09 17:51:38 -06001963
John Kessenichc9a80832015-09-12 12:17:44 -06001964 // Do the outer dimension, which might not be known for a runtime-sized array
1965 if (type.isRuntimeSizedArray()) {
1966 spvType = builder.makeRuntimeArray(spvType);
1967 } else {
1968 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001969 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001970 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001971 if (stride > 0)
1972 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001973 }
1974
1975 return spvType;
1976}
1977
John Kessenich6c292d32016-02-15 20:58:50 -07001978// Turn the expression forming the array size into an id.
1979// This is not quite trivial, because of specialization constants.
1980// Sometimes, a raw constant is turned into an Id, and sometimes
1981// a specialization constant expression is.
1982spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1983{
1984 // First, see if this is sized with a node, meaning a specialization constant:
1985 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1986 if (specNode != nullptr) {
1987 builder.clearAccessChain();
1988 specNode->traverse(this);
1989 return accessChainLoad(specNode->getAsTyped()->getType());
1990 }
1991
1992 // Otherwise, need a compile-time (front end) size, get it:
1993 int size = arraySizes.getDimSize(dim);
1994 assert(size > 0);
1995 return builder.makeUintConstant(size);
1996}
1997
John Kessenich103bef92016-02-08 21:38:15 -07001998// Wrap the builder's accessChainLoad to:
1999// - localize handling of RelaxedPrecision
2000// - use the SPIR-V inferred type instead of another conversion of the glslang type
2001// (avoids unnecessary work and possible type punning for structures)
2002// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002003spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2004{
John Kessenich103bef92016-02-08 21:38:15 -07002005 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2006 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2007
2008 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002009 if (type.getBasicType() == glslang::EbtBool) {
2010 if (builder.isScalarType(nominalTypeId)) {
2011 // Conversion for bool
2012 spv::Id boolType = builder.makeBoolType();
2013 if (nominalTypeId != boolType)
2014 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2015 } else if (builder.isVectorType(nominalTypeId)) {
2016 // Conversion for bvec
2017 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2018 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2019 if (nominalTypeId != bvecType)
2020 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2021 }
2022 }
John Kessenich103bef92016-02-08 21:38:15 -07002023
2024 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002025}
2026
Rex Xu27253232016-02-23 17:51:09 +08002027// Wrap the builder's accessChainStore to:
2028// - do conversion of concrete to abstract type
2029void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2030{
2031 // Need to convert to abstract types when necessary
2032 if (type.getBasicType() == glslang::EbtBool) {
2033 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2034
2035 if (builder.isScalarType(nominalTypeId)) {
2036 // Conversion for bool
2037 spv::Id boolType = builder.makeBoolType();
2038 if (nominalTypeId != boolType) {
2039 spv::Id zero = builder.makeUintConstant(0);
2040 spv::Id one = builder.makeUintConstant(1);
2041 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2042 }
2043 } else if (builder.isVectorType(nominalTypeId)) {
2044 // Conversion for bvec
2045 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2046 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2047 if (nominalTypeId != bvecType) {
2048 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2049 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2050 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2051 }
2052 }
2053 }
2054
2055 builder.accessChainStore(rvalue);
2056}
2057
John Kessenichf85e8062015-12-19 13:57:10 -07002058// Decide whether or not this type should be
2059// decorated with offsets and strides, and if so
2060// whether std140 or std430 rules should be applied.
2061glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002062{
John Kessenichf85e8062015-12-19 13:57:10 -07002063 // has to be a block
2064 if (type.getBasicType() != glslang::EbtBlock)
2065 return glslang::ElpNone;
2066
2067 // has to be a uniform or buffer block
2068 if (type.getQualifier().storage != glslang::EvqUniform &&
2069 type.getQualifier().storage != glslang::EvqBuffer)
2070 return glslang::ElpNone;
2071
2072 // return the layout to use
2073 switch (type.getQualifier().layoutPacking) {
2074 case glslang::ElpStd140:
2075 case glslang::ElpStd430:
2076 return type.getQualifier().layoutPacking;
2077 default:
2078 return glslang::ElpNone;
2079 }
John Kessenich31ed4832015-09-09 17:51:38 -06002080}
2081
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002082// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002083int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002084{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002085 int size;
John Kessenich49987892015-12-29 17:11:44 -07002086 int stride;
2087 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002088
2089 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002090}
2091
John Kessenich49987892015-12-29 17:11:44 -07002092// 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 -07002093// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002094int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002095{
John Kessenich49987892015-12-29 17:11:44 -07002096 glslang::TType elementType;
2097 elementType.shallowCopy(matrixType);
2098 elementType.clearArraySizes();
2099
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002100 int size;
John Kessenich49987892015-12-29 17:11:44 -07002101 int stride;
2102 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2103
2104 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002105}
2106
John Kessenich5e4b1242015-08-06 22:53:06 -06002107// Given a member type of a struct, realign the current offset for it, and compute
2108// the next (not yet aligned) offset for the next member, which will get aligned
2109// on the next call.
2110// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2111// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2112// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002113void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002114 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002115{
2116 // this will get a positive value when deemed necessary
2117 nextOffset = -1;
2118
John Kessenich5e4b1242015-08-06 22:53:06 -06002119 // override anything in currentOffset with user-set offset
2120 if (memberType.getQualifier().hasOffset())
2121 currentOffset = memberType.getQualifier().layoutOffset;
2122
2123 // It could be that current linker usage in glslang updated all the layoutOffset,
2124 // in which case the following code does not matter. But, that's not quite right
2125 // once cross-compilation unit GLSL validation is done, as the original user
2126 // settings are needed in layoutOffset, and then the following will come into play.
2127
John Kessenichf85e8062015-12-19 13:57:10 -07002128 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002129 if (! memberType.getQualifier().hasOffset())
2130 currentOffset = -1;
2131
2132 return;
2133 }
2134
John Kessenichf85e8062015-12-19 13:57:10 -07002135 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002136 if (currentOffset < 0)
2137 currentOffset = 0;
2138
2139 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2140 // but possibly not yet correctly aligned.
2141
2142 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002143 int dummyStride;
2144 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002145 glslang::RoundToPow2(currentOffset, memberAlignment);
2146 nextOffset = currentOffset + memberSize;
2147}
2148
John Kessenich140f3df2015-06-26 16:58:36 -06002149bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2150{
John Kessenich4d65ee32016-03-12 18:17:47 -07002151 // have to ignore mangling and just look at the base name
baldurk3cb57d32016-04-09 13:07:12 +02002152 size_t firstOpen = node->getName().find('(');
John Kessenich7e3e4862016-04-06 19:03:15 -06002153 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002154}
2155
2156// Make all the functions, skeletally, without actually visiting their bodies.
2157void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2158{
2159 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2160 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2161 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2162 continue;
2163
2164 // We're on a user function. Set up the basic interface for the function now,
2165 // so that it's available to call.
2166 // Translating the body will happen later.
2167 //
2168 // Typically (except for a "const in" parameter), an address will be passed to the
2169 // function. What it is an address of varies:
2170 //
2171 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2172 // so that write needs to be to a copy, hence the address of a copy works.
2173 //
2174 // - "const in" parameters can just be the r-value, as no writes need occur.
2175 //
2176 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2177 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2178
2179 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002180 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002181 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2182
2183 for (int p = 0; p < (int)parameters.size(); ++p) {
2184 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2185 spv::Id typeId = convertGlslangToSpvType(paramType);
2186 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2187 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2188 else
2189 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002190 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002191 paramTypes.push_back(typeId);
2192 }
2193
2194 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002195 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2196 convertGlslangToSpvType(glslFunction->getType()),
2197 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002198
2199 // Track function to emit/call later
2200 functionMap[glslFunction->getName().c_str()] = function;
2201
2202 // Set the parameter id's
2203 for (int p = 0; p < (int)parameters.size(); ++p) {
2204 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2205 // give a name too
2206 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2207 }
2208 }
2209}
2210
2211// Process all the initializers, while skipping the functions and link objects
2212void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2213{
2214 builder.setBuildPoint(shaderEntry->getLastBlock());
2215 for (int i = 0; i < (int)initializers.size(); ++i) {
2216 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2217 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2218
2219 // We're on a top-level node that's not a function. Treat as an initializer, whose
2220 // code goes into the beginning of main.
2221 initializer->traverse(this);
2222 }
2223 }
2224}
2225
2226// Process all the functions, while skipping initializers.
2227void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2228{
2229 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2230 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2231 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2232 node->traverse(this);
2233 }
2234}
2235
2236void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2237{
2238 // SPIR-V functions should already be in the functionMap from the prepass
2239 // that called makeFunctions().
2240 spv::Function* function = functionMap[node->getName().c_str()];
2241 spv::Block* functionBlock = function->getEntryBlock();
2242 builder.setBuildPoint(functionBlock);
2243}
2244
Rex Xu04db3f52015-09-16 11:44:02 +08002245void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002246{
Rex Xufc618912015-09-09 16:42:49 +08002247 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002248
2249 glslang::TSampler sampler = {};
2250 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002251 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002252 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2253 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2254 }
2255
John Kessenich140f3df2015-06-26 16:58:36 -06002256 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2257 builder.clearAccessChain();
2258 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002259
2260 // Special case l-value operands
2261 bool lvalue = false;
2262 switch (node.getOp()) {
2263 case glslang::EOpImageAtomicAdd:
2264 case glslang::EOpImageAtomicMin:
2265 case glslang::EOpImageAtomicMax:
2266 case glslang::EOpImageAtomicAnd:
2267 case glslang::EOpImageAtomicOr:
2268 case glslang::EOpImageAtomicXor:
2269 case glslang::EOpImageAtomicExchange:
2270 case glslang::EOpImageAtomicCompSwap:
2271 if (i == 0)
2272 lvalue = true;
2273 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002274 case glslang::EOpSparseImageLoad:
2275 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2276 lvalue = true;
2277 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002278 case glslang::EOpSparseTexture:
2279 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2280 lvalue = true;
2281 break;
2282 case glslang::EOpSparseTextureClamp:
2283 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2284 lvalue = true;
2285 break;
2286 case glslang::EOpSparseTextureLod:
2287 case glslang::EOpSparseTextureOffset:
2288 if (i == 3)
2289 lvalue = true;
2290 break;
2291 case glslang::EOpSparseTextureFetch:
2292 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2293 lvalue = true;
2294 break;
2295 case glslang::EOpSparseTextureFetchOffset:
2296 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2297 lvalue = true;
2298 break;
2299 case glslang::EOpSparseTextureLodOffset:
2300 case glslang::EOpSparseTextureGrad:
2301 case glslang::EOpSparseTextureOffsetClamp:
2302 if (i == 4)
2303 lvalue = true;
2304 break;
2305 case glslang::EOpSparseTextureGradOffset:
2306 case glslang::EOpSparseTextureGradClamp:
2307 if (i == 5)
2308 lvalue = true;
2309 break;
2310 case glslang::EOpSparseTextureGradOffsetClamp:
2311 if (i == 6)
2312 lvalue = true;
2313 break;
2314 case glslang::EOpSparseTextureGather:
2315 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2316 lvalue = true;
2317 break;
2318 case glslang::EOpSparseTextureGatherOffset:
2319 case glslang::EOpSparseTextureGatherOffsets:
2320 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2321 lvalue = true;
2322 break;
Rex Xufc618912015-09-09 16:42:49 +08002323 default:
2324 break;
2325 }
2326
Rex Xu6b86d492015-09-16 17:48:22 +08002327 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002328 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002329 else
John Kessenich32cfd492016-02-02 12:37:46 -07002330 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002331 }
2332}
2333
John Kessenichfc51d282015-08-19 13:34:18 -06002334void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002335{
John Kessenichfc51d282015-08-19 13:34:18 -06002336 builder.clearAccessChain();
2337 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002338 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002339}
John Kessenich140f3df2015-06-26 16:58:36 -06002340
John Kessenichfc51d282015-08-19 13:34:18 -06002341spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2342{
Rex Xufc618912015-09-09 16:42:49 +08002343 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002344 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002345 }
2346
John Kessenichfc51d282015-08-19 13:34:18 -06002347 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002348 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2349 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2350 std::vector<spv::Id> arguments;
2351 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002352 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002353 else
2354 translateArguments(*node->getAsUnaryNode(), arguments);
2355 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2356
2357 spv::Builder::TextureParameters params = { };
2358 params.sampler = arguments[0];
2359
Rex Xu04db3f52015-09-16 11:44:02 +08002360 glslang::TCrackedTextureOp cracked;
2361 node->crackTexture(sampler, cracked);
2362
John Kessenichfc51d282015-08-19 13:34:18 -06002363 // Check for queries
2364 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002365 // a sampled image needs to have the image extracted first
2366 if (builder.isSampledImage(params.sampler))
2367 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002368 switch (node->getOp()) {
2369 case glslang::EOpImageQuerySize:
2370 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002371 if (arguments.size() > 1) {
2372 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002373 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002374 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002375 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002376 case glslang::EOpImageQuerySamples:
2377 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002378 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002379 case glslang::EOpTextureQueryLod:
2380 params.coords = arguments[1];
2381 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2382 case glslang::EOpTextureQueryLevels:
2383 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002384 case glslang::EOpSparseTexelsResident:
2385 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002386 default:
2387 assert(0);
2388 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002389 }
John Kessenich140f3df2015-06-26 16:58:36 -06002390 }
2391
Rex Xufc618912015-09-09 16:42:49 +08002392 // Check for image functions other than queries
2393 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002394 std::vector<spv::Id> operands;
2395 auto opIt = arguments.begin();
2396 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002397
2398 // Handle subpass operations
2399 // TODO: GLSL should change to have the "MS" only on the type rather than the
2400 // built-in function.
2401 if (cracked.subpass) {
2402 // add on the (0,0) coordinate
2403 spv::Id zero = builder.makeIntConstant(0);
2404 std::vector<spv::Id> comps;
2405 comps.push_back(zero);
2406 comps.push_back(zero);
2407 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2408 if (sampler.ms) {
2409 operands.push_back(spv::ImageOperandsSampleMask);
2410 operands.push_back(*(opIt++));
2411 }
2412 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2413 }
2414
John Kessenich56bab042015-09-16 10:54:31 -06002415 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002416 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002417 if (sampler.ms) {
2418 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002419 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002420 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002421 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2422 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002423 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002424 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002425 if (sampler.ms) {
2426 operands.push_back(*(opIt + 1));
2427 operands.push_back(spv::ImageOperandsSampleMask);
2428 operands.push_back(*opIt);
2429 } else
2430 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002431 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002432 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2433 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002434 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002435 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2436 builder.addCapability(spv::CapabilitySparseResidency);
2437 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2438 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2439
2440 if (sampler.ms) {
2441 operands.push_back(spv::ImageOperandsSampleMask);
2442 operands.push_back(*opIt++);
2443 }
2444
2445 // Create the return type that was a special structure
2446 spv::Id texelOut = *opIt;
2447 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2448 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2449 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2450
2451 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2452
2453 // Decode the return type
2454 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2455 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002456 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002457 // Process image atomic operations
2458
2459 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2460 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002461 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002462
Rex Xufc618912015-09-09 16:42:49 +08002463 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002464 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002465
2466 std::vector<spv::Id> operands;
2467 operands.push_back(pointer);
2468 for (; opIt != arguments.end(); ++opIt)
2469 operands.push_back(*opIt);
2470
Rex Xu04db3f52015-09-16 11:44:02 +08002471 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002472 }
2473 }
2474
2475 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002476 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002477 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2478
John Kessenichfc51d282015-08-19 13:34:18 -06002479 // check for bias argument
2480 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002481 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002482 int nonBiasArgCount = 2;
2483 if (cracked.offset)
2484 ++nonBiasArgCount;
2485 if (cracked.grad)
2486 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002487 if (cracked.lodClamp)
2488 ++nonBiasArgCount;
2489 if (sparse)
2490 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002491
2492 if ((int)arguments.size() > nonBiasArgCount)
2493 bias = true;
2494 }
2495
John Kessenichfc51d282015-08-19 13:34:18 -06002496 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002497
John Kessenichfc51d282015-08-19 13:34:18 -06002498 params.coords = arguments[1];
2499 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002500 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002501
2502 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002503 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002504 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002505 ++extraArgs;
2506 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002507 params.Dref = arguments[2];
2508 ++extraArgs;
2509 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002510 std::vector<spv::Id> indexes;
2511 int comp;
2512 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002513 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002514 else
2515 comp = builder.getNumComponents(params.coords) - 1;
2516 indexes.push_back(comp);
2517 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2518 }
2519 if (cracked.lod) {
2520 params.lod = arguments[2];
2521 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002522 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2523 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2524 noImplicitLod = true;
2525 }
2526 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002527 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002528 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002529 }
2530 if (cracked.grad) {
2531 params.gradX = arguments[2 + extraArgs];
2532 params.gradY = arguments[3 + extraArgs];
2533 extraArgs += 2;
2534 }
John Kessenich55e7d112015-11-15 21:33:39 -07002535 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002536 params.offset = arguments[2 + extraArgs];
2537 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002538 } else if (cracked.offsets) {
2539 params.offsets = arguments[2 + extraArgs];
2540 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002541 }
Rex Xu48edadf2015-12-31 16:11:41 +08002542 if (cracked.lodClamp) {
2543 params.lodClamp = arguments[2 + extraArgs];
2544 ++extraArgs;
2545 }
2546 if (sparse) {
2547 params.texelOut = arguments[2 + extraArgs];
2548 ++extraArgs;
2549 }
John Kessenichfc51d282015-08-19 13:34:18 -06002550 if (bias) {
2551 params.bias = arguments[2 + extraArgs];
2552 ++extraArgs;
2553 }
John Kessenich55e7d112015-11-15 21:33:39 -07002554 if (cracked.gather && ! sampler.shadow) {
2555 // default component is 0, if missing, otherwise an argument
2556 if (2 + extraArgs < (int)arguments.size()) {
2557 params.comp = arguments[2 + extraArgs];
2558 ++extraArgs;
2559 } else {
2560 params.comp = builder.makeIntConstant(0);
2561 }
2562 }
John Kessenichfc51d282015-08-19 13:34:18 -06002563
John Kessenich019f08f2016-02-15 15:40:42 -07002564 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002565}
2566
2567spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2568{
2569 // Grab the function's pointer from the previously created function
2570 spv::Function* function = functionMap[node->getName().c_str()];
2571 if (! function)
2572 return 0;
2573
2574 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2575 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2576
2577 // See comments in makeFunctions() for details about the semantics for parameter passing.
2578 //
2579 // These imply we need a four step process:
2580 // 1. Evaluate the arguments
2581 // 2. Allocate and make copies of in, out, and inout arguments
2582 // 3. Make the call
2583 // 4. Copy back the results
2584
2585 // 1. Evaluate the arguments
2586 std::vector<spv::Builder::AccessChain> lValues;
2587 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002588 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002589 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2590 // build l-value
2591 builder.clearAccessChain();
2592 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002593 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002594 // keep outputs as l-values, evaluate input-only as r-values
2595 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2596 // save l-value
2597 lValues.push_back(builder.getAccessChain());
2598 } else {
2599 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002600 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002601 }
2602 }
2603
2604 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2605 // copy the original into that space.
2606 //
2607 // Also, build up the list of actual arguments to pass in for the call
2608 int lValueCount = 0;
2609 int rValueCount = 0;
2610 std::vector<spv::Id> spvArgs;
2611 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2612 spv::Id arg;
2613 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2614 // need space to hold the copy
2615 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2616 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2617 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2618 // need to copy the input into output space
2619 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002620 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002621 builder.createStore(copy, arg);
2622 }
2623 ++lValueCount;
2624 } else {
2625 arg = rValues[rValueCount];
2626 ++rValueCount;
2627 }
2628 spvArgs.push_back(arg);
2629 }
2630
2631 // 3. Make the call.
2632 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002633 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002634
2635 // 4. Copy back out an "out" arguments.
2636 lValueCount = 0;
2637 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2638 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2639 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2640 spv::Id copy = builder.createLoad(spvArgs[a]);
2641 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002642 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002643 }
2644 ++lValueCount;
2645 }
2646 }
2647
2648 return result;
2649}
2650
2651// Translate AST operation to SPV operation, already having SPV-based operands/types.
2652spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2653 spv::Id typeId, spv::Id left, spv::Id right,
2654 glslang::TBasicType typeProxy, bool reduceComparison)
2655{
Rex Xu8ff43de2016-04-22 16:51:45 +08002656 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06002657 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc7d36562016-04-27 08:15:37 +08002658 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06002659
2660 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002661 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002662 bool comparison = false;
2663
2664 switch (op) {
2665 case glslang::EOpAdd:
2666 case glslang::EOpAddAssign:
2667 if (isFloat)
2668 binOp = spv::OpFAdd;
2669 else
2670 binOp = spv::OpIAdd;
2671 break;
2672 case glslang::EOpSub:
2673 case glslang::EOpSubAssign:
2674 if (isFloat)
2675 binOp = spv::OpFSub;
2676 else
2677 binOp = spv::OpISub;
2678 break;
2679 case glslang::EOpMul:
2680 case glslang::EOpMulAssign:
2681 if (isFloat)
2682 binOp = spv::OpFMul;
2683 else
2684 binOp = spv::OpIMul;
2685 break;
2686 case glslang::EOpVectorTimesScalar:
2687 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002688 if (isFloat) {
2689 if (builder.isVector(right))
2690 std::swap(left, right);
2691 assert(builder.isScalar(right));
2692 needMatchingVectors = false;
2693 binOp = spv::OpVectorTimesScalar;
2694 } else
2695 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002696 break;
2697 case glslang::EOpVectorTimesMatrix:
2698 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002699 binOp = spv::OpVectorTimesMatrix;
2700 break;
2701 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002702 binOp = spv::OpMatrixTimesVector;
2703 break;
2704 case glslang::EOpMatrixTimesScalar:
2705 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002706 binOp = spv::OpMatrixTimesScalar;
2707 break;
2708 case glslang::EOpMatrixTimesMatrix:
2709 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002710 binOp = spv::OpMatrixTimesMatrix;
2711 break;
2712 case glslang::EOpOuterProduct:
2713 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002714 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002715 break;
2716
2717 case glslang::EOpDiv:
2718 case glslang::EOpDivAssign:
2719 if (isFloat)
2720 binOp = spv::OpFDiv;
2721 else if (isUnsigned)
2722 binOp = spv::OpUDiv;
2723 else
2724 binOp = spv::OpSDiv;
2725 break;
2726 case glslang::EOpMod:
2727 case glslang::EOpModAssign:
2728 if (isFloat)
2729 binOp = spv::OpFMod;
2730 else if (isUnsigned)
2731 binOp = spv::OpUMod;
2732 else
2733 binOp = spv::OpSMod;
2734 break;
2735 case glslang::EOpRightShift:
2736 case glslang::EOpRightShiftAssign:
2737 if (isUnsigned)
2738 binOp = spv::OpShiftRightLogical;
2739 else
2740 binOp = spv::OpShiftRightArithmetic;
2741 break;
2742 case glslang::EOpLeftShift:
2743 case glslang::EOpLeftShiftAssign:
2744 binOp = spv::OpShiftLeftLogical;
2745 break;
2746 case glslang::EOpAnd:
2747 case glslang::EOpAndAssign:
2748 binOp = spv::OpBitwiseAnd;
2749 break;
2750 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002751 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002752 binOp = spv::OpLogicalAnd;
2753 break;
2754 case glslang::EOpInclusiveOr:
2755 case glslang::EOpInclusiveOrAssign:
2756 binOp = spv::OpBitwiseOr;
2757 break;
2758 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002759 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002760 binOp = spv::OpLogicalOr;
2761 break;
2762 case glslang::EOpExclusiveOr:
2763 case glslang::EOpExclusiveOrAssign:
2764 binOp = spv::OpBitwiseXor;
2765 break;
2766 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002767 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002768 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002769 break;
2770
2771 case glslang::EOpLessThan:
2772 case glslang::EOpGreaterThan:
2773 case glslang::EOpLessThanEqual:
2774 case glslang::EOpGreaterThanEqual:
2775 case glslang::EOpEqual:
2776 case glslang::EOpNotEqual:
2777 case glslang::EOpVectorEqual:
2778 case glslang::EOpVectorNotEqual:
2779 comparison = true;
2780 break;
2781 default:
2782 break;
2783 }
2784
John Kessenich7c1aa102015-10-15 13:29:11 -06002785 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002786 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002787 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002788 if (builder.isMatrix(left) || builder.isMatrix(right))
2789 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002790
2791 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002792 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002793 builder.promoteScalar(precision, left, right);
2794
John Kessenich32cfd492016-02-02 12:37:46 -07002795 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002796 }
2797
2798 if (! comparison)
2799 return 0;
2800
John Kessenich7c1aa102015-10-15 13:29:11 -06002801 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002802
2803 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2804 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2805
John Kessenich22118352015-12-21 20:54:09 -07002806 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002807 }
2808
2809 switch (op) {
2810 case glslang::EOpLessThan:
2811 if (isFloat)
2812 binOp = spv::OpFOrdLessThan;
2813 else if (isUnsigned)
2814 binOp = spv::OpULessThan;
2815 else
2816 binOp = spv::OpSLessThan;
2817 break;
2818 case glslang::EOpGreaterThan:
2819 if (isFloat)
2820 binOp = spv::OpFOrdGreaterThan;
2821 else if (isUnsigned)
2822 binOp = spv::OpUGreaterThan;
2823 else
2824 binOp = spv::OpSGreaterThan;
2825 break;
2826 case glslang::EOpLessThanEqual:
2827 if (isFloat)
2828 binOp = spv::OpFOrdLessThanEqual;
2829 else if (isUnsigned)
2830 binOp = spv::OpULessThanEqual;
2831 else
2832 binOp = spv::OpSLessThanEqual;
2833 break;
2834 case glslang::EOpGreaterThanEqual:
2835 if (isFloat)
2836 binOp = spv::OpFOrdGreaterThanEqual;
2837 else if (isUnsigned)
2838 binOp = spv::OpUGreaterThanEqual;
2839 else
2840 binOp = spv::OpSGreaterThanEqual;
2841 break;
2842 case glslang::EOpEqual:
2843 case glslang::EOpVectorEqual:
2844 if (isFloat)
2845 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002846 else if (isBool)
2847 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002848 else
2849 binOp = spv::OpIEqual;
2850 break;
2851 case glslang::EOpNotEqual:
2852 case glslang::EOpVectorNotEqual:
2853 if (isFloat)
2854 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08002855 else if (isBool)
2856 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002857 else
2858 binOp = spv::OpINotEqual;
2859 break;
2860 default:
2861 break;
2862 }
2863
John Kessenich32cfd492016-02-02 12:37:46 -07002864 if (binOp != spv::OpNop)
2865 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002866
2867 return 0;
2868}
2869
John Kessenich04bb8a02015-12-12 12:28:14 -07002870//
2871// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2872// These can be any of:
2873//
2874// matrix * scalar
2875// scalar * matrix
2876// matrix * matrix linear algebraic
2877// matrix * vector
2878// vector * matrix
2879// matrix * matrix componentwise
2880// matrix op matrix op in {+, -, /}
2881// matrix op scalar op in {+, -, /}
2882// scalar op matrix op in {+, -, /}
2883//
2884spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2885{
2886 bool firstClass = true;
2887
2888 // First, handle first-class matrix operations (* and matrix/scalar)
2889 switch (op) {
2890 case spv::OpFDiv:
2891 if (builder.isMatrix(left) && builder.isScalar(right)) {
2892 // turn matrix / scalar into a multiply...
2893 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2894 op = spv::OpMatrixTimesScalar;
2895 } else
2896 firstClass = false;
2897 break;
2898 case spv::OpMatrixTimesScalar:
2899 if (builder.isMatrix(right))
2900 std::swap(left, right);
2901 assert(builder.isScalar(right));
2902 break;
2903 case spv::OpVectorTimesMatrix:
2904 assert(builder.isVector(left));
2905 assert(builder.isMatrix(right));
2906 break;
2907 case spv::OpMatrixTimesVector:
2908 assert(builder.isMatrix(left));
2909 assert(builder.isVector(right));
2910 break;
2911 case spv::OpMatrixTimesMatrix:
2912 assert(builder.isMatrix(left));
2913 assert(builder.isMatrix(right));
2914 break;
2915 default:
2916 firstClass = false;
2917 break;
2918 }
2919
John Kessenich32cfd492016-02-02 12:37:46 -07002920 if (firstClass)
2921 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002922
2923 // Handle component-wise +, -, *, and / for all combinations of type.
2924 // The result type of all of them is the same type as the (a) matrix operand.
2925 // The algorithm is to:
2926 // - break the matrix(es) into vectors
2927 // - smear any scalar to a vector
2928 // - do vector operations
2929 // - make a matrix out the vector results
2930 switch (op) {
2931 case spv::OpFAdd:
2932 case spv::OpFSub:
2933 case spv::OpFDiv:
2934 case spv::OpFMul:
2935 {
2936 // one time set up...
2937 bool leftMat = builder.isMatrix(left);
2938 bool rightMat = builder.isMatrix(right);
2939 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2940 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2941 spv::Id scalarType = builder.getScalarTypeId(typeId);
2942 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2943 std::vector<spv::Id> results;
2944 spv::Id smearVec = spv::NoResult;
2945 if (builder.isScalar(left))
2946 smearVec = builder.smearScalar(precision, left, vecType);
2947 else if (builder.isScalar(right))
2948 smearVec = builder.smearScalar(precision, right, vecType);
2949
2950 // do each vector op
2951 for (unsigned int c = 0; c < numCols; ++c) {
2952 std::vector<unsigned int> indexes;
2953 indexes.push_back(c);
2954 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2955 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2956 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2957 builder.setPrecision(results.back(), precision);
2958 }
2959
2960 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002961 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002962 }
2963 default:
2964 assert(0);
2965 return spv::NoResult;
2966 }
2967}
2968
Rex Xu04db3f52015-09-16 11:44:02 +08002969spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06002970{
2971 spv::Op unaryOp = spv::OpNop;
2972 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08002973 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08002974 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002975
2976 switch (op) {
2977 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002978 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002979 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002980 if (builder.isMatrixType(typeId))
2981 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2982 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002983 unaryOp = spv::OpSNegate;
2984 break;
2985
2986 case glslang::EOpLogicalNot:
2987 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002988 unaryOp = spv::OpLogicalNot;
2989 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002990 case glslang::EOpBitwiseNot:
2991 unaryOp = spv::OpNot;
2992 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002993
John Kessenich140f3df2015-06-26 16:58:36 -06002994 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002995 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002996 break;
2997 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002998 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002999 break;
3000 case glslang::EOpTranspose:
3001 unaryOp = spv::OpTranspose;
3002 break;
3003
3004 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003005 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003006 break;
3007 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003008 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003009 break;
3010 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003011 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003012 break;
3013 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003014 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003015 break;
3016 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003017 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003018 break;
3019 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003020 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003021 break;
3022 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003023 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003024 break;
3025 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003026 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003027 break;
3028
3029 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003030 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003031 break;
3032 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003033 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003034 break;
3035 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003036 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003037 break;
3038 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003039 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003040 break;
3041 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003042 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003043 break;
3044 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003045 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003046 break;
3047
3048 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003049 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003050 break;
3051 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003052 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003053 break;
3054
3055 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003056 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003057 break;
3058 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003059 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003060 break;
3061 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003062 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003063 break;
3064 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003065 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003066 break;
3067 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003068 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003069 break;
3070 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003071 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003072 break;
3073
3074 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003075 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003076 break;
3077 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003078 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003079 break;
3080 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003081 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003082 break;
3083 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003084 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003085 break;
3086 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003087 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003088 break;
3089 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003090 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003091 break;
3092
3093 case glslang::EOpIsNan:
3094 unaryOp = spv::OpIsNan;
3095 break;
3096 case glslang::EOpIsInf:
3097 unaryOp = spv::OpIsInf;
3098 break;
3099
Rex Xucbc426e2015-12-15 16:03:10 +08003100 case glslang::EOpFloatBitsToInt:
3101 case glslang::EOpFloatBitsToUint:
3102 case glslang::EOpIntBitsToFloat:
3103 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003104 case glslang::EOpDoubleBitsToInt64:
3105 case glslang::EOpDoubleBitsToUint64:
3106 case glslang::EOpInt64BitsToDouble:
3107 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003108 unaryOp = spv::OpBitcast;
3109 break;
3110
John Kessenich140f3df2015-06-26 16:58:36 -06003111 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003112 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003113 break;
3114 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003115 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003116 break;
3117 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003118 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003119 break;
3120 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003121 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003122 break;
3123 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003124 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003125 break;
3126 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003127 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003128 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003129 case glslang::EOpPackSnorm4x8:
3130 libCall = spv::GLSLstd450PackSnorm4x8;
3131 break;
3132 case glslang::EOpUnpackSnorm4x8:
3133 libCall = spv::GLSLstd450UnpackSnorm4x8;
3134 break;
3135 case glslang::EOpPackUnorm4x8:
3136 libCall = spv::GLSLstd450PackUnorm4x8;
3137 break;
3138 case glslang::EOpUnpackUnorm4x8:
3139 libCall = spv::GLSLstd450UnpackUnorm4x8;
3140 break;
3141 case glslang::EOpPackDouble2x32:
3142 libCall = spv::GLSLstd450PackDouble2x32;
3143 break;
3144 case glslang::EOpUnpackDouble2x32:
3145 libCall = spv::GLSLstd450UnpackDouble2x32;
3146 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003147
Rex Xu8ff43de2016-04-22 16:51:45 +08003148 case glslang::EOpPackInt2x32:
3149 case glslang::EOpUnpackInt2x32:
3150 case glslang::EOpPackUint2x32:
3151 case glslang::EOpUnpackUint2x32:
Lei Zhang17535f72016-05-04 15:55:59 -04003152 logger->missingFunctionality("shader int64");
Rex Xu8ff43de2016-04-22 16:51:45 +08003153 libCall = spv::GLSLstd450Bad; // TODO: This is a placeholder.
3154 break;
3155
John Kessenich140f3df2015-06-26 16:58:36 -06003156 case glslang::EOpDPdx:
3157 unaryOp = spv::OpDPdx;
3158 break;
3159 case glslang::EOpDPdy:
3160 unaryOp = spv::OpDPdy;
3161 break;
3162 case glslang::EOpFwidth:
3163 unaryOp = spv::OpFwidth;
3164 break;
3165 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003166 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003167 unaryOp = spv::OpDPdxFine;
3168 break;
3169 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003170 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003171 unaryOp = spv::OpDPdyFine;
3172 break;
3173 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003174 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003175 unaryOp = spv::OpFwidthFine;
3176 break;
3177 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003178 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003179 unaryOp = spv::OpDPdxCoarse;
3180 break;
3181 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003182 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003183 unaryOp = spv::OpDPdyCoarse;
3184 break;
3185 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003186 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003187 unaryOp = spv::OpFwidthCoarse;
3188 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003189 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003190 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003191 libCall = spv::GLSLstd450InterpolateAtCentroid;
3192 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003193 case glslang::EOpAny:
3194 unaryOp = spv::OpAny;
3195 break;
3196 case glslang::EOpAll:
3197 unaryOp = spv::OpAll;
3198 break;
3199
3200 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003201 if (isFloat)
3202 libCall = spv::GLSLstd450FAbs;
3203 else
3204 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003205 break;
3206 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003207 if (isFloat)
3208 libCall = spv::GLSLstd450FSign;
3209 else
3210 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003211 break;
3212
John Kessenichfc51d282015-08-19 13:34:18 -06003213 case glslang::EOpAtomicCounterIncrement:
3214 case glslang::EOpAtomicCounterDecrement:
3215 case glslang::EOpAtomicCounter:
3216 {
3217 // Handle all of the atomics in one place, in createAtomicOperation()
3218 std::vector<spv::Id> operands;
3219 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003220 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003221 }
3222
John Kessenichfc51d282015-08-19 13:34:18 -06003223 case glslang::EOpBitFieldReverse:
3224 unaryOp = spv::OpBitReverse;
3225 break;
3226 case glslang::EOpBitCount:
3227 unaryOp = spv::OpBitCount;
3228 break;
3229 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003230 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003231 break;
3232 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003233 if (isUnsigned)
3234 libCall = spv::GLSLstd450FindUMsb;
3235 else
3236 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003237 break;
3238
John Kessenich140f3df2015-06-26 16:58:36 -06003239 default:
3240 return 0;
3241 }
3242
3243 spv::Id id;
3244 if (libCall >= 0) {
3245 std::vector<spv::Id> args;
3246 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003247 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003248 } else
3249 id = builder.createUnaryOp(unaryOp, typeId, operand);
3250
John Kessenich32cfd492016-02-02 12:37:46 -07003251 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003252}
3253
John Kessenich7a53f762016-01-20 11:19:27 -07003254// Create a unary operation on a matrix
3255spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3256{
3257 // Handle unary operations vector by vector.
3258 // The result type is the same type as the original type.
3259 // The algorithm is to:
3260 // - break the matrix into vectors
3261 // - apply the operation to each vector
3262 // - make a matrix out the vector results
3263
3264 // get the types sorted out
3265 int numCols = builder.getNumColumns(operand);
3266 int numRows = builder.getNumRows(operand);
3267 spv::Id scalarType = builder.getScalarTypeId(typeId);
3268 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3269 std::vector<spv::Id> results;
3270
3271 // do each vector op
3272 for (int c = 0; c < numCols; ++c) {
3273 std::vector<unsigned int> indexes;
3274 indexes.push_back(c);
3275 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3276 results.push_back(builder.createUnaryOp(op, vecType, vec));
3277 builder.setPrecision(results.back(), precision);
3278 }
3279
3280 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003281 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003282}
3283
John Kessenich140f3df2015-06-26 16:58:36 -06003284spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3285{
3286 spv::Op convOp = spv::OpNop;
3287 spv::Id zero = 0;
3288 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08003289 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003290
3291 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3292
3293 switch (op) {
3294 case glslang::EOpConvIntToBool:
3295 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08003296 case glslang::EOpConvInt64ToBool:
3297 case glslang::EOpConvUint64ToBool:
3298 zero = (op == glslang::EOpConvInt64ToBool ||
3299 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003300 zero = makeSmearedConstant(zero, vectorSize);
3301 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3302
3303 case glslang::EOpConvFloatToBool:
3304 zero = builder.makeFloatConstant(0.0F);
3305 zero = makeSmearedConstant(zero, vectorSize);
3306 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3307
3308 case glslang::EOpConvDoubleToBool:
3309 zero = builder.makeDoubleConstant(0.0);
3310 zero = makeSmearedConstant(zero, vectorSize);
3311 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3312
3313 case glslang::EOpConvBoolToFloat:
3314 convOp = spv::OpSelect;
3315 zero = builder.makeFloatConstant(0.0);
3316 one = builder.makeFloatConstant(1.0);
3317 break;
3318 case glslang::EOpConvBoolToDouble:
3319 convOp = spv::OpSelect;
3320 zero = builder.makeDoubleConstant(0.0);
3321 one = builder.makeDoubleConstant(1.0);
3322 break;
3323 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003324 case glslang::EOpConvBoolToInt64:
3325 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
3326 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003327 convOp = spv::OpSelect;
3328 break;
3329 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003330 case glslang::EOpConvBoolToUint64:
3331 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3332 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06003333 convOp = spv::OpSelect;
3334 break;
3335
3336 case glslang::EOpConvIntToFloat:
3337 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003338 case glslang::EOpConvInt64ToFloat:
3339 case glslang::EOpConvInt64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003340 convOp = spv::OpConvertSToF;
3341 break;
3342
3343 case glslang::EOpConvUintToFloat:
3344 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08003345 case glslang::EOpConvUint64ToFloat:
3346 case glslang::EOpConvUint64ToDouble:
John Kessenich140f3df2015-06-26 16:58:36 -06003347 convOp = spv::OpConvertUToF;
3348 break;
3349
3350 case glslang::EOpConvDoubleToFloat:
3351 case glslang::EOpConvFloatToDouble:
3352 convOp = spv::OpFConvert;
3353 break;
3354
3355 case glslang::EOpConvFloatToInt:
3356 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08003357 case glslang::EOpConvFloatToInt64:
3358 case glslang::EOpConvDoubleToInt64:
John Kessenich140f3df2015-06-26 16:58:36 -06003359 convOp = spv::OpConvertFToS;
3360 break;
3361
3362 case glslang::EOpConvUintToInt:
3363 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003364 case glslang::EOpConvUint64ToInt64:
3365 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04003366 if (builder.isInSpecConstCodeGenMode()) {
3367 // Build zero scalar or vector for OpIAdd.
Rex Xu8ff43de2016-04-22 16:51:45 +08003368 zero = (op == glslang::EOpConvUintToInt64 ||
3369 op == glslang::EOpConvIntToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04003370 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04003371 // Use OpIAdd, instead of OpBitcast to do the conversion when
3372 // generating for OpSpecConstantOp instruction.
3373 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3374 }
3375 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06003376 convOp = spv::OpBitcast;
3377 break;
3378
3379 case glslang::EOpConvFloatToUint:
3380 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08003381 case glslang::EOpConvFloatToUint64:
3382 case glslang::EOpConvDoubleToUint64:
John Kessenich140f3df2015-06-26 16:58:36 -06003383 convOp = spv::OpConvertFToU;
3384 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003385
3386 case glslang::EOpConvIntToInt64:
3387 case glslang::EOpConvInt64ToInt:
3388 convOp = spv::OpSConvert;
3389 break;
3390
3391 case glslang::EOpConvUintToUint64:
3392 case glslang::EOpConvUint64ToUint:
3393 convOp = spv::OpUConvert;
3394 break;
3395
3396 case glslang::EOpConvIntToUint64:
3397 case glslang::EOpConvInt64ToUint:
3398 case glslang::EOpConvUint64ToInt:
3399 case glslang::EOpConvUintToInt64:
3400 // OpSConvert/OpUConvert + OpBitCast
3401 switch (op) {
3402 case glslang::EOpConvIntToUint64:
3403 convOp = spv::OpSConvert;
3404 type = builder.makeIntType(64);
3405 break;
3406 case glslang::EOpConvInt64ToUint:
3407 convOp = spv::OpSConvert;
3408 type = builder.makeIntType(32);
3409 break;
3410 case glslang::EOpConvUint64ToInt:
3411 convOp = spv::OpUConvert;
3412 type = builder.makeUintType(32);
3413 break;
3414 case glslang::EOpConvUintToInt64:
3415 convOp = spv::OpUConvert;
3416 type = builder.makeUintType(64);
3417 break;
3418 default:
3419 assert(0);
3420 break;
3421 }
3422
3423 if (vectorSize > 0)
3424 type = builder.makeVectorType(type, vectorSize);
3425
3426 operand = builder.createUnaryOp(convOp, type, operand);
3427
3428 if (builder.isInSpecConstCodeGenMode()) {
3429 // Build zero scalar or vector for OpIAdd.
3430 zero = (op == glslang::EOpConvIntToUint64 ||
3431 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
3432 zero = makeSmearedConstant(zero, vectorSize);
3433 // Use OpIAdd, instead of OpBitcast to do the conversion when
3434 // generating for OpSpecConstantOp instruction.
3435 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
3436 }
3437 // For normal run-time conversion instruction, use OpBitcast.
3438 convOp = spv::OpBitcast;
3439 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003440 default:
3441 break;
3442 }
3443
3444 spv::Id result = 0;
3445 if (convOp == spv::OpNop)
3446 return result;
3447
3448 if (convOp == spv::OpSelect) {
3449 zero = makeSmearedConstant(zero, vectorSize);
3450 one = makeSmearedConstant(one, vectorSize);
3451 result = builder.createTriOp(convOp, destType, operand, one, zero);
3452 } else
3453 result = builder.createUnaryOp(convOp, destType, operand);
3454
John Kessenich32cfd492016-02-02 12:37:46 -07003455 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003456}
3457
3458spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3459{
3460 if (vectorSize == 0)
3461 return constant;
3462
3463 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3464 std::vector<spv::Id> components;
3465 for (int c = 0; c < vectorSize; ++c)
3466 components.push_back(constant);
3467 return builder.makeCompositeConstant(vectorTypeId, components);
3468}
3469
John Kessenich426394d2015-07-23 10:22:48 -06003470// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003471spv::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 -06003472{
3473 spv::Op opCode = spv::OpNop;
3474
3475 switch (op) {
3476 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003477 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003478 opCode = spv::OpAtomicIAdd;
3479 break;
3480 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003481 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003482 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003483 break;
3484 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003485 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003486 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003487 break;
3488 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003489 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003490 opCode = spv::OpAtomicAnd;
3491 break;
3492 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003493 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003494 opCode = spv::OpAtomicOr;
3495 break;
3496 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003497 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003498 opCode = spv::OpAtomicXor;
3499 break;
3500 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003501 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003502 opCode = spv::OpAtomicExchange;
3503 break;
3504 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003505 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003506 opCode = spv::OpAtomicCompareExchange;
3507 break;
3508 case glslang::EOpAtomicCounterIncrement:
3509 opCode = spv::OpAtomicIIncrement;
3510 break;
3511 case glslang::EOpAtomicCounterDecrement:
3512 opCode = spv::OpAtomicIDecrement;
3513 break;
3514 case glslang::EOpAtomicCounter:
3515 opCode = spv::OpAtomicLoad;
3516 break;
3517 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003518 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003519 break;
3520 }
3521
3522 // Sort out the operands
3523 // - mapping from glslang -> SPV
3524 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003525 // - compare-exchange swaps the value and comparator
3526 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003527 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3528 auto opIt = operands.begin(); // walk the glslang operands
3529 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003530 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3531 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3532 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003533 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3534 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003535 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003536 spvAtomicOperands.push_back(*(opIt + 1));
3537 spvAtomicOperands.push_back(*opIt);
3538 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003539 }
John Kessenich426394d2015-07-23 10:22:48 -06003540
John Kessenich3e60a6f2015-09-14 22:45:16 -06003541 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003542 for (; opIt != operands.end(); ++opIt)
3543 spvAtomicOperands.push_back(*opIt);
3544
3545 return builder.createOp(opCode, typeId, spvAtomicOperands);
3546}
3547
John Kessenich5e4b1242015-08-06 22:53:06 -06003548spv::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 -06003549{
Rex Xu8ff43de2016-04-22 16:51:45 +08003550 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06003551 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3552
John Kessenich140f3df2015-06-26 16:58:36 -06003553 spv::Op opCode = spv::OpNop;
3554 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003555 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003556 spv::Id typeId0 = 0;
3557 if (consumedOperands > 0)
3558 typeId0 = builder.getTypeId(operands[0]);
3559 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003560
3561 switch (op) {
3562 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003563 if (isFloat)
3564 libCall = spv::GLSLstd450FMin;
3565 else if (isUnsigned)
3566 libCall = spv::GLSLstd450UMin;
3567 else
3568 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003569 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003570 break;
3571 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003572 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003573 break;
3574 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003575 if (isFloat)
3576 libCall = spv::GLSLstd450FMax;
3577 else if (isUnsigned)
3578 libCall = spv::GLSLstd450UMax;
3579 else
3580 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003581 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003582 break;
3583 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003584 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003585 break;
3586 case glslang::EOpDot:
3587 opCode = spv::OpDot;
3588 break;
3589 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003590 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003591 break;
3592
3593 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003594 if (isFloat)
3595 libCall = spv::GLSLstd450FClamp;
3596 else if (isUnsigned)
3597 libCall = spv::GLSLstd450UClamp;
3598 else
3599 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003600 builder.promoteScalar(precision, operands.front(), operands[1]);
3601 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003602 break;
3603 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003604 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3605 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003606 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003607 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003608 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003609 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003610 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003611 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003612 break;
3613 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003614 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003615 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003616 break;
3617 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003618 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003619 builder.promoteScalar(precision, operands[0], operands[2]);
3620 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003621 break;
3622
3623 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003624 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003625 break;
3626 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003627 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003628 break;
3629 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003630 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003631 break;
3632 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003633 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003634 break;
3635 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003636 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003637 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003638 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003639 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003640 libCall = spv::GLSLstd450InterpolateAtSample;
3641 break;
3642 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003643 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003644 libCall = spv::GLSLstd450InterpolateAtOffset;
3645 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003646 case glslang::EOpAddCarry:
3647 opCode = spv::OpIAddCarry;
3648 typeId = builder.makeStructResultType(typeId0, typeId0);
3649 consumedOperands = 2;
3650 break;
3651 case glslang::EOpSubBorrow:
3652 opCode = spv::OpISubBorrow;
3653 typeId = builder.makeStructResultType(typeId0, typeId0);
3654 consumedOperands = 2;
3655 break;
3656 case glslang::EOpUMulExtended:
3657 opCode = spv::OpUMulExtended;
3658 typeId = builder.makeStructResultType(typeId0, typeId0);
3659 consumedOperands = 2;
3660 break;
3661 case glslang::EOpIMulExtended:
3662 opCode = spv::OpSMulExtended;
3663 typeId = builder.makeStructResultType(typeId0, typeId0);
3664 consumedOperands = 2;
3665 break;
3666 case glslang::EOpBitfieldExtract:
3667 if (isUnsigned)
3668 opCode = spv::OpBitFieldUExtract;
3669 else
3670 opCode = spv::OpBitFieldSExtract;
3671 break;
3672 case glslang::EOpBitfieldInsert:
3673 opCode = spv::OpBitFieldInsert;
3674 break;
3675
3676 case glslang::EOpFma:
3677 libCall = spv::GLSLstd450Fma;
3678 break;
3679 case glslang::EOpFrexp:
3680 libCall = spv::GLSLstd450FrexpStruct;
3681 if (builder.getNumComponents(operands[0]) == 1)
3682 frexpIntType = builder.makeIntegerType(32, true);
3683 else
3684 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3685 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3686 consumedOperands = 1;
3687 break;
3688 case glslang::EOpLdexp:
3689 libCall = spv::GLSLstd450Ldexp;
3690 break;
3691
John Kessenich140f3df2015-06-26 16:58:36 -06003692 default:
3693 return 0;
3694 }
3695
3696 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003697 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003698 // Use an extended instruction from the standard library.
3699 // Construct the call arguments, without modifying the original operands vector.
3700 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3701 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003702 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003703 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003704 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003705 case 0:
3706 // should all be handled by visitAggregate and createNoArgOperation
3707 assert(0);
3708 return 0;
3709 case 1:
3710 // should all be handled by createUnaryOperation
3711 assert(0);
3712 return 0;
3713 case 2:
3714 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3715 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003716 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003717 // anything 3 or over doesn't have l-value operands, so all should be consumed
3718 assert(consumedOperands == operands.size());
3719 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003720 break;
3721 }
3722 }
3723
John Kessenich55e7d112015-11-15 21:33:39 -07003724 // Decode the return types that were structures
3725 switch (op) {
3726 case glslang::EOpAddCarry:
3727 case glslang::EOpSubBorrow:
3728 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3729 id = builder.createCompositeExtract(id, typeId0, 0);
3730 break;
3731 case glslang::EOpUMulExtended:
3732 case glslang::EOpIMulExtended:
3733 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3734 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3735 break;
3736 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003737 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003738 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3739 id = builder.createCompositeExtract(id, typeId0, 0);
3740 break;
3741 default:
3742 break;
3743 }
3744
John Kessenich32cfd492016-02-02 12:37:46 -07003745 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003746}
3747
3748// Intrinsics with no arguments, no return value, and no precision.
3749spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3750{
3751 // TODO: get the barrier operands correct
3752
3753 switch (op) {
3754 case glslang::EOpEmitVertex:
3755 builder.createNoResultOp(spv::OpEmitVertex);
3756 return 0;
3757 case glslang::EOpEndPrimitive:
3758 builder.createNoResultOp(spv::OpEndPrimitive);
3759 return 0;
3760 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3762 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003763 return 0;
3764 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003765 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003766 return 0;
3767 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003768 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003769 return 0;
3770 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003772 return 0;
3773 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003774 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003775 return 0;
3776 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003777 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003778 return 0;
3779 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003780 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003781 return 0;
3782 default:
Lei Zhang17535f72016-05-04 15:55:59 -04003783 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003784 return 0;
3785 }
3786}
3787
3788spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3789{
John Kessenich2f273362015-07-18 22:34:27 -06003790 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003791 spv::Id id;
3792 if (symbolValues.end() != iter) {
3793 id = iter->second;
3794 return id;
3795 }
3796
3797 // it was not found, create it
3798 id = createSpvVariable(symbol);
3799 symbolValues[symbol->getId()] = id;
3800
3801 if (! symbol->getType().isStruct()) {
3802 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003803 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003804 if (symbol->getType().getQualifier().hasSpecConstantId())
3805 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003806 if (symbol->getQualifier().hasLocation())
3807 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3808 if (symbol->getQualifier().hasIndex())
3809 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3810 if (symbol->getQualifier().hasComponent())
3811 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3812 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003813 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003814 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003815 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003816 if (symbol->getQualifier().hasXfbBuffer())
3817 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3818 if (symbol->getQualifier().hasXfbOffset())
3819 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3820 }
3821 }
3822
John Kesseniche0b6cad2015-12-24 10:30:13 -07003823 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003824 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003825 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003826 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003827 }
John Kessenich140f3df2015-06-26 16:58:36 -06003828 if (symbol->getQualifier().hasSet())
3829 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003830 else if (IsDescriptorResource(symbol->getType())) {
3831 // default to 0
3832 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3833 }
John Kessenich140f3df2015-06-26 16:58:36 -06003834 if (symbol->getQualifier().hasBinding())
3835 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003836 if (symbol->getQualifier().hasAttachment())
3837 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003838 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003839 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003840 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003841 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003842 if (symbol->getQualifier().hasXfbBuffer())
3843 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3844 }
3845
Rex Xu1da878f2016-02-21 20:59:01 +08003846 if (symbol->getType().isImage()) {
3847 std::vector<spv::Decoration> memory;
3848 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3849 for (unsigned int i = 0; i < memory.size(); ++i)
3850 addDecoration(id, memory[i]);
3851 }
3852
John Kessenich140f3df2015-06-26 16:58:36 -06003853 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003854 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003855 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003856 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003857
John Kessenich140f3df2015-06-26 16:58:36 -06003858 return id;
3859}
3860
John Kessenich55e7d112015-11-15 21:33:39 -07003861// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003862void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3863{
3864 if (dec != spv::BadValue)
3865 builder.addDecoration(id, dec);
3866}
3867
John Kessenich55e7d112015-11-15 21:33:39 -07003868// If 'dec' is valid, add a one-operand decoration to an object
3869void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3870{
3871 if (dec != spv::BadValue)
3872 builder.addDecoration(id, dec, value);
3873}
3874
3875// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003876void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3877{
3878 if (dec != spv::BadValue)
3879 builder.addMemberDecoration(id, (unsigned)member, dec);
3880}
3881
John Kessenich92187592016-02-01 13:45:25 -07003882// If 'dec' is valid, add a one-operand decoration to a struct member
3883void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3884{
3885 if (dec != spv::BadValue)
3886 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3887}
3888
John Kessenich55e7d112015-11-15 21:33:39 -07003889// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003890// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003891//
3892// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3893//
3894// Recursively walk the nodes. The nodes form a tree whose leaves are
3895// regular constants, which themselves are trees that createSpvConstant()
3896// recursively walks. So, this function walks the "top" of the tree:
3897// - emit specialization constant-building instructions for specConstant
3898// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003899spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003900{
John Kessenich7cc0e282016-03-20 00:46:02 -06003901 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003902
qining4f4bb812016-04-03 23:55:17 -04003903 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003904 if (! node.getQualifier().specConstant) {
3905 // hand off to the non-spec-constant path
3906 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3907 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003908 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003909 nextConst, false);
3910 }
3911
3912 // We now know we have a specialization constant to build
3913
qining4f4bb812016-04-03 23:55:17 -04003914 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3915 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3916 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3917 std::vector<spv::Id> dimConstId;
3918 for (int dim = 0; dim < 3; ++dim) {
3919 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3920 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3921 if (specConst)
3922 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3923 }
3924 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3925 }
3926
3927 // An AST node labelled as specialization constant should be a symbol node.
3928 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3929 if (auto* sn = node.getAsSymbolNode()) {
3930 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04003931 // Traverse the constant constructor sub tree like generating normal run-time instructions.
3932 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
3933 // will set the builder into spec constant op instruction generating mode.
3934 sub_tree->traverse(this);
3935 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04003936 } else if (auto* const_union_array = &sn->getConstArray()){
3937 int nextConst = 0;
3938 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003939 }
3940 }
qining4f4bb812016-04-03 23:55:17 -04003941
3942 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3943 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04003944 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04003945 exit(1);
3946 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07003947}
3948
John Kessenich140f3df2015-06-26 16:58:36 -06003949// Use 'consts' as the flattened glslang source of scalar constants to recursively
3950// build the aggregate SPIR-V constant.
3951//
3952// If there are not enough elements present in 'consts', 0 will be substituted;
3953// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3954//
qining08408382016-03-21 09:51:37 -04003955spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003956{
3957 // vector of constants for SPIR-V
3958 std::vector<spv::Id> spvConsts;
3959
3960 // Type is used for struct and array constants
3961 spv::Id typeId = convertGlslangToSpvType(glslangType);
3962
3963 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003964 glslang::TType elementType(glslangType, 0);
3965 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04003966 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003967 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003968 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003969 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04003970 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003971 } else if (glslangType.getStruct()) {
3972 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3973 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04003974 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003975 } else if (glslangType.isVector()) {
3976 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3977 bool zero = nextConst >= consts.size();
3978 switch (glslangType.getBasicType()) {
3979 case glslang::EbtInt:
3980 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3981 break;
3982 case glslang::EbtUint:
3983 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3984 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08003985 case glslang::EbtInt64:
3986 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
3987 break;
3988 case glslang::EbtUint64:
3989 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
3990 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003991 case glslang::EbtFloat:
3992 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3993 break;
3994 case glslang::EbtDouble:
3995 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3996 break;
3997 case glslang::EbtBool:
3998 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3999 break;
4000 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004001 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004002 break;
4003 }
4004 ++nextConst;
4005 }
4006 } else {
4007 // we have a non-aggregate (scalar) constant
4008 bool zero = nextConst >= consts.size();
4009 spv::Id scalar = 0;
4010 switch (glslangType.getBasicType()) {
4011 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07004012 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004013 break;
4014 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07004015 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004016 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004017 case glslang::EbtInt64:
4018 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
4019 break;
4020 case glslang::EbtUint64:
4021 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
4022 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004023 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07004024 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004025 break;
4026 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07004027 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004028 break;
4029 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07004030 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06004031 break;
4032 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004033 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004034 break;
4035 }
4036 ++nextConst;
4037 return scalar;
4038 }
4039
4040 return builder.makeCompositeConstant(typeId, spvConsts);
4041}
4042
John Kessenich7c1aa102015-10-15 13:29:11 -06004043// Return true if the node is a constant or symbol whose reading has no
4044// non-trivial observable cost or effect.
4045bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
4046{
4047 // don't know what this is
4048 if (node == nullptr)
4049 return false;
4050
4051 // a constant is safe
4052 if (node->getAsConstantUnion() != nullptr)
4053 return true;
4054
4055 // not a symbol means non-trivial
4056 if (node->getAsSymbolNode() == nullptr)
4057 return false;
4058
4059 // a symbol, depends on what's being read
4060 switch (node->getType().getQualifier().storage) {
4061 case glslang::EvqTemporary:
4062 case glslang::EvqGlobal:
4063 case glslang::EvqIn:
4064 case glslang::EvqInOut:
4065 case glslang::EvqConst:
4066 case glslang::EvqConstReadOnly:
4067 case glslang::EvqUniform:
4068 return true;
4069 default:
4070 return false;
4071 }
4072}
4073
4074// A node is trivial if it is a single operation with no side effects.
4075// Error on the side of saying non-trivial.
4076// Return true if trivial.
4077bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
4078{
4079 if (node == nullptr)
4080 return false;
4081
4082 // symbols and constants are trivial
4083 if (isTrivialLeaf(node))
4084 return true;
4085
4086 // otherwise, it needs to be a simple operation or one or two leaf nodes
4087
4088 // not a simple operation
4089 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4090 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4091 if (binaryNode == nullptr && unaryNode == nullptr)
4092 return false;
4093
4094 // not on leaf nodes
4095 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4096 return false;
4097
4098 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4099 return false;
4100 }
4101
4102 switch (node->getAsOperator()->getOp()) {
4103 case glslang::EOpLogicalNot:
4104 case glslang::EOpConvIntToBool:
4105 case glslang::EOpConvUintToBool:
4106 case glslang::EOpConvFloatToBool:
4107 case glslang::EOpConvDoubleToBool:
4108 case glslang::EOpEqual:
4109 case glslang::EOpNotEqual:
4110 case glslang::EOpLessThan:
4111 case glslang::EOpGreaterThan:
4112 case glslang::EOpLessThanEqual:
4113 case glslang::EOpGreaterThanEqual:
4114 case glslang::EOpIndexDirect:
4115 case glslang::EOpIndexDirectStruct:
4116 case glslang::EOpLogicalXor:
4117 case glslang::EOpAny:
4118 case glslang::EOpAll:
4119 return true;
4120 default:
4121 return false;
4122 }
4123}
4124
4125// Emit short-circuiting code, where 'right' is never evaluated unless
4126// the left side is true (for &&) or false (for ||).
4127spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4128{
4129 spv::Id boolTypeId = builder.makeBoolType();
4130
4131 // emit left operand
4132 builder.clearAccessChain();
4133 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004134 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004135
4136 // Operands to accumulate OpPhi operands
4137 std::vector<spv::Id> phiOperands;
4138 // accumulate left operand's phi information
4139 phiOperands.push_back(leftId);
4140 phiOperands.push_back(builder.getBuildPoint()->getId());
4141
4142 // Make the two kinds of operation symmetric with a "!"
4143 // || => emit "if (! left) result = right"
4144 // && => emit "if ( left) result = right"
4145 //
4146 // TODO: this runtime "not" for || could be avoided by adding functionality
4147 // to 'builder' to have an "else" without an "then"
4148 if (op == glslang::EOpLogicalOr)
4149 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4150
4151 // make an "if" based on the left value
4152 spv::Builder::If ifBuilder(leftId, builder);
4153
4154 // emit right operand as the "then" part of the "if"
4155 builder.clearAccessChain();
4156 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004157 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004158
4159 // accumulate left operand's phi information
4160 phiOperands.push_back(rightId);
4161 phiOperands.push_back(builder.getBuildPoint()->getId());
4162
4163 // finish the "if"
4164 ifBuilder.makeEndIf();
4165
4166 // phi together the two results
4167 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4168}
4169
John Kessenich140f3df2015-06-26 16:58:36 -06004170}; // end anonymous namespace
4171
4172namespace glslang {
4173
John Kessenich68d78fd2015-07-12 19:28:10 -06004174void GetSpirvVersion(std::string& version)
4175{
John Kessenich9e55f632015-07-15 10:03:39 -06004176 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004177 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004178 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004179 version = buf;
4180}
4181
John Kessenich140f3df2015-06-26 16:58:36 -06004182// Write SPIR-V out to a binary file
4183void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4184{
4185 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004186 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004187 for (int i = 0; i < (int)spirv.size(); ++i) {
4188 unsigned int word = spirv[i];
4189 out.write((const char*)&word, 4);
4190 }
4191 out.close();
4192}
4193
4194//
4195// Set up the glslang traversal
4196//
4197void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4198{
Lei Zhang17535f72016-05-04 15:55:59 -04004199 spv::SpvBuildLogger logger;
4200 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04004201}
4202
Lei Zhang17535f72016-05-04 15:55:59 -04004203void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04004204{
John Kessenich140f3df2015-06-26 16:58:36 -06004205 TIntermNode* root = intermediate.getTreeRoot();
4206
4207 if (root == 0)
4208 return;
4209
4210 glslang::GetThreadPoolAllocator().push();
4211
Lei Zhang17535f72016-05-04 15:55:59 -04004212 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06004213
4214 root->traverse(&it);
4215
4216 it.dumpSpv(spirv);
4217
4218 glslang::GetThreadPoolAllocator().pop();
4219}
4220
4221}; // end namespace glslang