blob: 9d42e3cffab2ff45d3b09f0492956b12998fb339 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
2//Copyright (C) 2014 LunarG, Inc.
3//
4//All rights reserved.
5//
6//Redistribution and use in source and binary forms, with or without
7//modification, are permitted provided that the following conditions
8//are met:
9//
10// Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//
13// Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following
15// disclaimer in the documentation and/or other materials provided
16// with the distribution.
17//
18// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19// contributors may be used to endorse or promote products derived
20// from this software without specific prior written permission.
21//
22//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33//POSSIBILITY OF SUCH DAMAGE.
34
35//
36// Author: John Kessenich, LunarG
37//
38// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
46 #include "GLSL.std.450.h"
47}
John Kessenich140f3df2015-06-26 16:58:36 -060048
49// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020050#include "../glslang/MachineIndependent/localintermediate.h"
51#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060053
54#include <string>
55#include <map>
56#include <list>
57#include <vector>
58#include <stack>
59#include <fstream>
60
61namespace {
62
John Kessenich55e7d112015-11-15 21:33:39 -070063// For low-order part of the generator's magic number. Bump up
64// when there is a change in the style (e.g., if SSA form changes,
65// or a different instruction sequence to do something gets used).
66const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060067
68//
69// The main holder of information for translating glslang to SPIR-V.
70//
71// Derives from the AST walking base class.
72//
73class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
74public:
75 TGlslangToSpvTraverser(const glslang::TIntermediate*);
76 virtual ~TGlslangToSpvTraverser();
77
78 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
79 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
80 void visitConstantUnion(glslang::TIntermConstantUnion*);
81 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
82 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
83 void visitSymbol(glslang::TIntermSymbol* symbol);
84 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
85 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
86 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
87
John Kessenich7ba63412015-12-20 17:37:07 -070088 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060089
90protected:
91 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
92 spv::Id getSampledType(const glslang::TSampler&);
93 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070094 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenichf85e8062015-12-19 13:57:10 -070095 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -070096 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
97 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
98 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 -060099
100 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
101 void makeFunctions(const glslang::TIntermSequence&);
102 void makeGlobalInitializers(const glslang::TIntermSequence&);
103 void visitFunctions(const glslang::TIntermSequence&);
104 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800105 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600106 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
107 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600108 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
109
110 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 -0700111 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800112 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600113 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
114 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800115 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 -0600116 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 -0600117 spv::Id createNoArgOperation(glslang::TOperator op);
118 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
119 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700120 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600121 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700122 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
123 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600124 bool isTrivialLeaf(const glslang::TIntermTyped* node);
125 bool isTrivial(const glslang::TIntermTyped* node);
126 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700129 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600130 int sequenceDepth;
131
132 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
133 spv::Builder builder;
134 bool inMain;
135 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700136 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 -0700137 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600138 const glslang::TIntermediate* glslangIntermediate;
139 spv::Id stdBuiltins;
140
John Kessenich2f273362015-07-18 22:34:27 -0600141 std::unordered_map<int, spv::Id> symbolValues;
142 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
143 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700144 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600145 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 -0600146 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600147};
148
149//
150// Helper functions for translating glslang representations to SPIR-V enumerants.
151//
152
153// Translate glslang profile to SPIR-V source language.
154spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
155{
156 switch (profile) {
157 case ENoProfile:
158 case ECoreProfile:
159 case ECompatibilityProfile:
160 return spv::SourceLanguageGLSL;
161 case EEsProfile:
162 return spv::SourceLanguageESSL;
163 default:
164 return spv::SourceLanguageUnknown;
165 }
166}
167
168// Translate glslang language (stage) to SPIR-V execution model.
169spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
170{
171 switch (stage) {
172 case EShLangVertex: return spv::ExecutionModelVertex;
173 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
174 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
175 case EShLangGeometry: return spv::ExecutionModelGeometry;
176 case EShLangFragment: return spv::ExecutionModelFragment;
177 case EShLangCompute: return spv::ExecutionModelGLCompute;
178 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700179 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600180 return spv::ExecutionModelFragment;
181 }
182}
183
184// Translate glslang type to SPIR-V storage class.
185spv::StorageClass TranslateStorageClass(const glslang::TType& type)
186{
187 if (type.getQualifier().isPipeInput())
188 return spv::StorageClassInput;
189 else if (type.getQualifier().isPipeOutput())
190 return spv::StorageClassOutput;
191 else if (type.getQualifier().isUniformOrBuffer()) {
192 if (type.getBasicType() == glslang::EbtBlock)
193 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800194 else if (type.getBasicType() == glslang::EbtAtomicUint)
195 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600196 else
197 return spv::StorageClassUniformConstant;
198 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
199 } else {
200 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700201 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
202 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600203 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
204 case glslang::EvqTemporary: return spv::StorageClassFunction;
205 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700206 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600207 return spv::StorageClassFunction;
208 }
209 }
210}
211
212// Translate glslang sampler type to SPIR-V dimensionality.
213spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
214{
215 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700216 case glslang::Esd1D: return spv::Dim1D;
217 case glslang::Esd2D: return spv::Dim2D;
218 case glslang::Esd3D: return spv::Dim3D;
219 case glslang::EsdCube: return spv::DimCube;
220 case glslang::EsdRect: return spv::DimRect;
221 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600222 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700223 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600224 return spv::Dim2D;
225 }
226}
227
228// Translate glslang type to SPIR-V precision decorations.
229spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
230{
231 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700232 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600233 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
234 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 default:
236 return spv::NoPrecision;
237 }
238}
239
240// Translate glslang type to SPIR-V block decorations.
241spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
242{
243 if (type.getBasicType() == glslang::EbtBlock) {
244 switch (type.getQualifier().storage) {
245 case glslang::EvqUniform: return spv::DecorationBlock;
246 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
247 case glslang::EvqVaryingIn: return spv::DecorationBlock;
248 case glslang::EvqVaryingOut: return spv::DecorationBlock;
249 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700250 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600251 break;
252 }
253 }
254
255 return (spv::Decoration)spv::BadValue;
256}
257
258// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700259spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600260{
261 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700262 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600263 case glslang::ElmRowMajor:
264 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700265 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600266 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700267 default:
268 // opaque layouts don't need a majorness
269 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 }
271 } else {
272 switch (type.getBasicType()) {
273 default:
274 return (spv::Decoration)spv::BadValue;
275 break;
276 case glslang::EbtBlock:
277 switch (type.getQualifier().storage) {
278 case glslang::EvqUniform:
279 case glslang::EvqBuffer:
280 switch (type.getQualifier().layoutPacking) {
281 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600282 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
283 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600284 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600285 }
286 case glslang::EvqVaryingIn:
287 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700288 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600289 return (spv::Decoration)spv::BadValue;
290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return (spv::Decoration)spv::BadValue;
293 }
294 }
295 }
296}
297
298// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700299// Returns spv::Decoration(spv::BadValue) when no decoration
300// should be applied.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700301spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600302{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700303 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700304 // Smooth decoration doesn't exist in SPIR-V 1.0
305 return (spv::Decoration)spv::BadValue;
306 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700307 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700308 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700309 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600310 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700311 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600312 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700313 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600314 return spv::DecorationCentroid;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700315 else if (qualifier.sample)
John Kessenich140f3df2015-06-26 16:58:36 -0600316 return spv::DecorationSample;
317 else
318 return (spv::Decoration)spv::BadValue;
319}
320
321// If glslang type is invaraiant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700322spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600323{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700324 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600325 return spv::DecorationInvariant;
326 else
327 return (spv::Decoration)spv::BadValue;
328}
329
330// Translate glslang built-in variable to SPIR-V built in decoration.
331spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
332{
333 switch (builtIn) {
334 case glslang::EbvPosition: return spv::BuiltInPosition;
335 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600336 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
337 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
338 case glslang::EbvVertexId: return spv::BuiltInVertexId;
339 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600340 case glslang::EbvBaseVertex:
341 case glslang::EbvBaseInstance:
342 case glslang::EbvDrawId:
343 // TODO: Add SPIR-V builtin ID.
344 spv::MissingFunctionality("Draw parameters");
345 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600346 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
347 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
348 case glslang::EbvLayer: return spv::BuiltInLayer;
349 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
350 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
351 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
352 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
353 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
354 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
355 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
356 case glslang::EbvFace: return spv::BuiltInFrontFacing;
357 case glslang::EbvSampleId: return spv::BuiltInSampleId;
358 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
359 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
361 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
362 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
363 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
364 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
365 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
366 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
367 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
368 default: return (spv::BuiltIn)spv::BadValue;
369 }
370}
371
Rex Xufc618912015-09-09 16:42:49 +0800372// Translate glslang image layout format to SPIR-V image format.
373spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
374{
375 assert(type.getBasicType() == glslang::EbtSampler);
376
377 switch (type.getQualifier().layoutFormat) {
378 case glslang::ElfNone: return spv::ImageFormatUnknown;
379 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
380 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
381 case glslang::ElfR32f: return spv::ImageFormatR32f;
382 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
383 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
384 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
385 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
386 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
387 case glslang::ElfR16f: return spv::ImageFormatR16f;
388 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
389 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
390 case glslang::ElfRg16: return spv::ImageFormatRg16;
391 case glslang::ElfRg8: return spv::ImageFormatRg8;
392 case glslang::ElfR16: return spv::ImageFormatR16;
393 case glslang::ElfR8: return spv::ImageFormatR8;
394 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
395 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
396 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
397 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
398 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
399 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
400 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
401 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
402 case glslang::ElfR32i: return spv::ImageFormatR32i;
403 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
404 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
405 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
406 case glslang::ElfR16i: return spv::ImageFormatR16i;
407 case glslang::ElfR8i: return spv::ImageFormatR8i;
408 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
409 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
410 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
411 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
412 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
413 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
414 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
415 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
416 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
417 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
418 default: return (spv::ImageFormat)spv::BadValue;
419 }
420}
421
John Kesseniche0b6cad2015-12-24 10:30:13 -0700422void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
423{
424 if (child.layoutMatrix == glslang::ElmNone)
425 child.layoutMatrix = parent.layoutMatrix;
426
427 if (parent.invariant)
428 child.invariant = true;
429 if (parent.nopersp)
430 child.nopersp = true;
431 if (parent.flat)
432 child.flat = true;
433 if (parent.centroid)
434 child.centroid = true;
435 if (parent.patch)
436 child.patch = true;
437 if (parent.sample)
438 child.sample = true;
439}
440
441bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
442{
443 // This should list qualifiers that simultaneous satisify:
444 // - struct members can inherit from a struct declaration
445 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
446 // - are not part of the offset/st430/etc or row/column-major layout
447 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample;
448}
449
John Kessenich140f3df2015-06-26 16:58:36 -0600450//
451// Implement the TGlslangToSpvTraverser class.
452//
453
454TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
455 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700456 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600457 inMain(false), mainTerminated(false), linkageOnly(false),
458 glslangIntermediate(glslangIntermediate)
459{
460 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
461
462 builder.clearAccessChain();
463 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
464 stdBuiltins = builder.import("GLSL.std.450");
465 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
466 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700467 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600468
469 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600470 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
471 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600472 builder.addSourceExtension(it->c_str());
473
474 // Add the top-level modes for this shader.
475
476 if (glslangIntermediate->getXfbMode())
477 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
478
479 unsigned int mode;
480 switch (glslangIntermediate->getStage()) {
481 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600482 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600483 break;
484
485 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600486 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600487 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
488 break;
489
490 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600491 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600492 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700493 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
494 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
495 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600496 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 }
498 if (mode != spv::BadValue)
499 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
500
John Kesseniche6903322015-10-13 16:29:02 -0600501 switch (glslangIntermediate->getVertexSpacing()) {
502 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
503 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
504 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
505 default: mode = spv::BadValue; break;
506 }
507 if (mode != spv::BadValue)
508 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
509
510 switch (glslangIntermediate->getVertexOrder()) {
511 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
512 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
513 default: mode = spv::BadValue; break;
514 }
515 if (mode != spv::BadValue)
516 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
517
518 if (glslangIntermediate->getPointMode())
519 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600520 break;
521
522 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600523 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600524 switch (glslangIntermediate->getInputPrimitive()) {
525 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
526 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
527 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700528 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600529 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
530 default: mode = spv::BadValue; break;
531 }
532 if (mode != spv::BadValue)
533 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600534
John Kessenich140f3df2015-06-26 16:58:36 -0600535 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
536
537 switch (glslangIntermediate->getOutputPrimitive()) {
538 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
539 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
540 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
541 default: mode = spv::BadValue; break;
542 }
543 if (mode != spv::BadValue)
544 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
545 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
546 break;
547
548 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600549 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600550 if (glslangIntermediate->getPixelCenterInteger())
551 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600552
John Kessenich140f3df2015-06-26 16:58:36 -0600553 if (glslangIntermediate->getOriginUpperLeft())
554 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600555 else
556 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600557
558 if (glslangIntermediate->getEarlyFragmentTests())
559 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
560
561 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600562 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
563 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
564 default: mode = spv::BadValue; break;
565 }
566 if (mode != spv::BadValue)
567 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
568
569 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
570 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600571 break;
572
573 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600574 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600575 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
576 glslangIntermediate->getLocalSize(1),
577 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600578 break;
579
580 default:
581 break;
582 }
583
584}
585
John Kessenich7ba63412015-12-20 17:37:07 -0700586// Finish everything and dump
587void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
588{
589 // finish off the entry-point SPV instruction by adding the Input/Output <id>
590 for (auto it : iOSet)
591 entryPoint->addIdOperand(it);
592
593 builder.dump(out);
594}
595
John Kessenich140f3df2015-06-26 16:58:36 -0600596TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
597{
598 if (! mainTerminated) {
599 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
600 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600601 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600602 }
603}
604
605//
606// Implement the traversal functions.
607//
608// Return true from interior nodes to have the external traversal
609// continue on to children. Return false if children were
610// already processed.
611//
612
613//
614// Symbols can turn into
615// - uniform/input reads
616// - output writes
617// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
618// - something simple that degenerates into the last bullet
619//
620void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
621{
622 // getSymbolId() will set up all the IO decorations on the first call.
623 // Formal function parameters were mapped during makeFunctions().
624 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700625
626 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
627 if (builder.isPointer(id)) {
628 spv::StorageClass sc = builder.getStorageClass(id);
629 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
630 iOSet.insert(id);
631 }
632
633 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600634 if (! linkageOnly) {
635 // Prepare to generate code for the access
636
637 // L-value chains will be computed left to right. We're on the symbol now,
638 // which is the left-most part of the access chain, so now is "clear" time,
639 // followed by setting the base.
640 builder.clearAccessChain();
641
642 // For now, we consider all user variables as being in memory, so they are pointers,
643 // except for "const in" arguments to a function, which are an intermediate object.
644 // See comments in handleUserFunctionCall().
645 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
646 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
647 builder.setAccessChainRValue(id);
648 else
649 builder.setAccessChainLValue(id);
650 }
651}
652
653bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
654{
655 // First, handle special cases
656 switch (node->getOp()) {
657 case glslang::EOpAssign:
658 case glslang::EOpAddAssign:
659 case glslang::EOpSubAssign:
660 case glslang::EOpMulAssign:
661 case glslang::EOpVectorTimesMatrixAssign:
662 case glslang::EOpVectorTimesScalarAssign:
663 case glslang::EOpMatrixTimesScalarAssign:
664 case glslang::EOpMatrixTimesMatrixAssign:
665 case glslang::EOpDivAssign:
666 case glslang::EOpModAssign:
667 case glslang::EOpAndAssign:
668 case glslang::EOpInclusiveOrAssign:
669 case glslang::EOpExclusiveOrAssign:
670 case glslang::EOpLeftShiftAssign:
671 case glslang::EOpRightShiftAssign:
672 // A bin-op assign "a += b" means the same thing as "a = a + b"
673 // where a is evaluated before b. For a simple assignment, GLSL
674 // says to evaluate the left before the right. So, always, left
675 // node then right node.
676 {
677 // get the left l-value, save it away
678 builder.clearAccessChain();
679 node->getLeft()->traverse(this);
680 spv::Builder::AccessChain lValue = builder.getAccessChain();
681
682 // evaluate the right
683 builder.clearAccessChain();
684 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600685 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600686
687 if (node->getOp() != glslang::EOpAssign) {
688 // the left is also an r-value
689 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600690 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600691
692 // do the operation
693 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
694 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
695 node->getType().getBasicType());
696
697 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700698 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600699 }
700
701 // store the result
702 builder.setAccessChain(lValue);
703 builder.accessChainStore(rValue);
704
705 // assignments are expressions having an rValue after they are evaluated...
706 builder.clearAccessChain();
707 builder.setAccessChainRValue(rValue);
708 }
709 return false;
710 case glslang::EOpIndexDirect:
711 case glslang::EOpIndexDirectStruct:
712 {
713 // Get the left part of the access chain.
714 node->getLeft()->traverse(this);
715
716 // Add the next element in the chain
717
John Kessenich55e7d112015-11-15 21:33:39 -0700718 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600719 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
720 // This may be, e.g., an anonymous block-member selection, which generally need
721 // index remapping due to hidden members in anonymous blocks.
722 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700723 assert(remapper.size() > 0);
724 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600725 }
726
727 if (! node->getLeft()->getType().isArray() &&
728 node->getLeft()->getType().isVector() &&
729 node->getOp() == glslang::EOpIndexDirect) {
730 // This is essentially a hard-coded vector swizzle of size 1,
731 // so short circuit the access-chain stuff with a swizzle.
732 std::vector<unsigned> swizzle;
733 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600734 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600735 } else {
736 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600737 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600738 }
739 }
740 return false;
741 case glslang::EOpIndexIndirect:
742 {
743 // Structure or array or vector indirection.
744 // Will use native SPIR-V access-chain for struct and array indirection;
745 // matrices are arrays of vectors, so will also work for a matrix.
746 // Will use the access chain's 'component' for variable index into a vector.
747
748 // This adapter is building access chains left to right.
749 // Set up the access chain to the left.
750 node->getLeft()->traverse(this);
751
752 // save it so that computing the right side doesn't trash it
753 spv::Builder::AccessChain partial = builder.getAccessChain();
754
755 // compute the next index in the chain
756 builder.clearAccessChain();
757 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600758 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600759
760 // restore the saved access chain
761 builder.setAccessChain(partial);
762
763 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600764 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600765 else
John Kessenichfa668da2015-09-13 14:46:30 -0600766 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600767 }
768 return false;
769 case glslang::EOpVectorSwizzle:
770 {
771 node->getLeft()->traverse(this);
772 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
773 std::vector<unsigned> swizzle;
774 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
775 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600776 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600777 }
778 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600779 case glslang::EOpLogicalOr:
780 case glslang::EOpLogicalAnd:
781 {
782
783 // These may require short circuiting, but can sometimes be done as straight
784 // binary operations. The right operand must be short circuited if it has
785 // side effects, and should probably be if it is complex.
786 if (isTrivial(node->getRight()->getAsTyped()))
787 break; // handle below as a normal binary operation
788 // otherwise, we need to do dynamic short circuiting on the right operand
789 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
790 builder.clearAccessChain();
791 builder.setAccessChainRValue(result);
792 }
793 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600794 default:
795 break;
796 }
797
798 // Assume generic binary op...
799
800 // Get the operands
801 builder.clearAccessChain();
802 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600803 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600804
805 builder.clearAccessChain();
806 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600807 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600808
809 spv::Id result;
810 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
811
812 result = createBinaryOperation(node->getOp(), precision,
813 convertGlslangToSpvType(node->getType()), left, right,
814 node->getLeft()->getType().getBasicType());
815
John Kessenich50e57562015-12-21 21:21:11 -0700816 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600817 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700818 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700819 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600820 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600821 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600822 return false;
823 }
John Kessenich140f3df2015-06-26 16:58:36 -0600824}
825
826bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
827{
John Kessenichfc51d282015-08-19 13:34:18 -0600828 spv::Id result = spv::NoResult;
829
830 // try texturing first
831 result = createImageTextureFunctionCall(node);
832 if (result != spv::NoResult) {
833 builder.clearAccessChain();
834 builder.setAccessChainRValue(result);
835
836 return false; // done with this node
837 }
838
839 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600840
841 if (node->getOp() == glslang::EOpArrayLength) {
842 // Quite special; won't want to evaluate the operand.
843
844 // Normal .length() would have been constant folded by the front-end.
845 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600846 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600847 assert(node->getOperand()->getType().isRuntimeSizedArray());
848 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
849 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600850 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
851 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600852
853 builder.clearAccessChain();
854 builder.setAccessChainRValue(length);
855
856 return false;
857 }
858
John Kessenichfc51d282015-08-19 13:34:18 -0600859 // Start by evaluating the operand
860
John Kessenich140f3df2015-06-26 16:58:36 -0600861 builder.clearAccessChain();
862 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800863
Rex Xufc618912015-09-09 16:42:49 +0800864 spv::Id operand = spv::NoResult;
865
866 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
867 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800868 node->getOp() == glslang::EOpAtomicCounter ||
869 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800870 operand = builder.accessChainGetLValue(); // Special case l-value operands
871 else
Rex Xu30f92582015-09-14 10:38:56 +0800872 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600873
874 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
875
876 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600877 if (! result)
878 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600879
880 // if not, then possibly an operation
881 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700882 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600883
884 if (result) {
885 builder.clearAccessChain();
886 builder.setAccessChainRValue(result);
887
888 return false; // done with this node
889 }
890
891 // it must be a special case, check...
892 switch (node->getOp()) {
893 case glslang::EOpPostIncrement:
894 case glslang::EOpPostDecrement:
895 case glslang::EOpPreIncrement:
896 case glslang::EOpPreDecrement:
897 {
898 // we need the integer value "1" or the floating point "1.0" to add/subtract
899 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
900 builder.makeFloatConstant(1.0F) :
901 builder.makeIntConstant(1);
902 glslang::TOperator op;
903 if (node->getOp() == glslang::EOpPreIncrement ||
904 node->getOp() == glslang::EOpPostIncrement)
905 op = glslang::EOpAdd;
906 else
907 op = glslang::EOpSub;
908
909 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
910 convertGlslangToSpvType(node->getType()), operand, one,
911 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700912 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600913
914 // The result of operation is always stored, but conditionally the
915 // consumed result. The consumed result is always an r-value.
916 builder.accessChainStore(result);
917 builder.clearAccessChain();
918 if (node->getOp() == glslang::EOpPreIncrement ||
919 node->getOp() == glslang::EOpPreDecrement)
920 builder.setAccessChainRValue(result);
921 else
922 builder.setAccessChainRValue(operand);
923 }
924
925 return false;
926
927 case glslang::EOpEmitStreamVertex:
928 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
929 return false;
930 case glslang::EOpEndStreamPrimitive:
931 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
932 return false;
933
934 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700935 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -0700936 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -0600937 }
John Kessenich140f3df2015-06-26 16:58:36 -0600938}
939
940bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
941{
John Kessenichfc51d282015-08-19 13:34:18 -0600942 spv::Id result = spv::NoResult;
943
944 // try texturing
945 result = createImageTextureFunctionCall(node);
946 if (result != spv::NoResult) {
947 builder.clearAccessChain();
948 builder.setAccessChainRValue(result);
949
950 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600951 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800952 // "imageStore" is a special case, which has no result
953 return false;
954 }
John Kessenichfc51d282015-08-19 13:34:18 -0600955
John Kessenich140f3df2015-06-26 16:58:36 -0600956 glslang::TOperator binOp = glslang::EOpNull;
957 bool reduceComparison = true;
958 bool isMatrix = false;
959 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600960 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600961
962 assert(node->getOp());
963
964 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
965
966 switch (node->getOp()) {
967 case glslang::EOpSequence:
968 {
969 if (preVisit)
970 ++sequenceDepth;
971 else
972 --sequenceDepth;
973
974 if (sequenceDepth == 1) {
975 // If this is the parent node of all the functions, we want to see them
976 // early, so all call points have actual SPIR-V functions to reference.
977 // In all cases, still let the traverser visit the children for us.
978 makeFunctions(node->getAsAggregate()->getSequence());
979
980 // Also, we want all globals initializers to go into the entry of main(), before
981 // anything else gets there, so visit out of order, doing them all now.
982 makeGlobalInitializers(node->getAsAggregate()->getSequence());
983
984 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
985 // so do them manually.
986 visitFunctions(node->getAsAggregate()->getSequence());
987
988 return false;
989 }
990
991 return true;
992 }
993 case glslang::EOpLinkerObjects:
994 {
995 if (visit == glslang::EvPreVisit)
996 linkageOnly = true;
997 else
998 linkageOnly = false;
999
1000 return true;
1001 }
1002 case glslang::EOpComma:
1003 {
1004 // processing from left to right naturally leaves the right-most
1005 // lying around in the access chain
1006 glslang::TIntermSequence& glslangOperands = node->getSequence();
1007 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1008 glslangOperands[i]->traverse(this);
1009
1010 return false;
1011 }
1012 case glslang::EOpFunction:
1013 if (visit == glslang::EvPreVisit) {
1014 if (isShaderEntrypoint(node)) {
1015 inMain = true;
1016 builder.setBuildPoint(shaderEntry->getLastBlock());
1017 } else {
1018 handleFunctionEntry(node);
1019 }
1020 } else {
1021 if (inMain)
1022 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001023 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001024 inMain = false;
1025 }
1026
1027 return true;
1028 case glslang::EOpParameters:
1029 // Parameters will have been consumed by EOpFunction processing, but not
1030 // the body, so we still visited the function node's children, making this
1031 // child redundant.
1032 return false;
1033 case glslang::EOpFunctionCall:
1034 {
1035 if (node->isUserDefined())
1036 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001037 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001038 builder.clearAccessChain();
1039 builder.setAccessChainRValue(result);
1040
1041 return false;
1042 }
1043 case glslang::EOpConstructMat2x2:
1044 case glslang::EOpConstructMat2x3:
1045 case glslang::EOpConstructMat2x4:
1046 case glslang::EOpConstructMat3x2:
1047 case glslang::EOpConstructMat3x3:
1048 case glslang::EOpConstructMat3x4:
1049 case glslang::EOpConstructMat4x2:
1050 case glslang::EOpConstructMat4x3:
1051 case glslang::EOpConstructMat4x4:
1052 case glslang::EOpConstructDMat2x2:
1053 case glslang::EOpConstructDMat2x3:
1054 case glslang::EOpConstructDMat2x4:
1055 case glslang::EOpConstructDMat3x2:
1056 case glslang::EOpConstructDMat3x3:
1057 case glslang::EOpConstructDMat3x4:
1058 case glslang::EOpConstructDMat4x2:
1059 case glslang::EOpConstructDMat4x3:
1060 case glslang::EOpConstructDMat4x4:
1061 isMatrix = true;
1062 // fall through
1063 case glslang::EOpConstructFloat:
1064 case glslang::EOpConstructVec2:
1065 case glslang::EOpConstructVec3:
1066 case glslang::EOpConstructVec4:
1067 case glslang::EOpConstructDouble:
1068 case glslang::EOpConstructDVec2:
1069 case glslang::EOpConstructDVec3:
1070 case glslang::EOpConstructDVec4:
1071 case glslang::EOpConstructBool:
1072 case glslang::EOpConstructBVec2:
1073 case glslang::EOpConstructBVec3:
1074 case glslang::EOpConstructBVec4:
1075 case glslang::EOpConstructInt:
1076 case glslang::EOpConstructIVec2:
1077 case glslang::EOpConstructIVec3:
1078 case glslang::EOpConstructIVec4:
1079 case glslang::EOpConstructUint:
1080 case glslang::EOpConstructUVec2:
1081 case glslang::EOpConstructUVec3:
1082 case glslang::EOpConstructUVec4:
1083 case glslang::EOpConstructStruct:
1084 {
1085 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001086 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001087 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1088 spv::Id constructed;
1089 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1090 std::vector<spv::Id> constituents;
1091 for (int c = 0; c < (int)arguments.size(); ++c)
1092 constituents.push_back(arguments[c]);
1093 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001094 } else if (isMatrix)
1095 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1096 else
1097 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001098
1099 builder.clearAccessChain();
1100 builder.setAccessChainRValue(constructed);
1101
1102 return false;
1103 }
1104
1105 // These six are component-wise compares with component-wise results.
1106 // Forward on to createBinaryOperation(), requesting a vector result.
1107 case glslang::EOpLessThan:
1108 case glslang::EOpGreaterThan:
1109 case glslang::EOpLessThanEqual:
1110 case glslang::EOpGreaterThanEqual:
1111 case glslang::EOpVectorEqual:
1112 case glslang::EOpVectorNotEqual:
1113 {
1114 // Map the operation to a binary
1115 binOp = node->getOp();
1116 reduceComparison = false;
1117 switch (node->getOp()) {
1118 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1119 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1120 default: binOp = node->getOp(); break;
1121 }
1122
1123 break;
1124 }
1125 case glslang::EOpMul:
1126 // compontent-wise matrix multiply
1127 binOp = glslang::EOpMul;
1128 break;
1129 case glslang::EOpOuterProduct:
1130 // two vectors multiplied to make a matrix
1131 binOp = glslang::EOpOuterProduct;
1132 break;
1133 case glslang::EOpDot:
1134 {
1135 // for scalar dot product, use multiply
1136 glslang::TIntermSequence& glslangOperands = node->getSequence();
1137 if (! glslangOperands[0]->getAsTyped()->isVector())
1138 binOp = glslang::EOpMul;
1139 break;
1140 }
1141 case glslang::EOpMod:
1142 // when an aggregate, this is the floating-point mod built-in function,
1143 // which can be emitted by the one in createBinaryOperation()
1144 binOp = glslang::EOpMod;
1145 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001146 case glslang::EOpEmitVertex:
1147 case glslang::EOpEndPrimitive:
1148 case glslang::EOpBarrier:
1149 case glslang::EOpMemoryBarrier:
1150 case glslang::EOpMemoryBarrierAtomicCounter:
1151 case glslang::EOpMemoryBarrierBuffer:
1152 case glslang::EOpMemoryBarrierImage:
1153 case glslang::EOpMemoryBarrierShared:
1154 case glslang::EOpGroupMemoryBarrier:
1155 noReturnValue = true;
1156 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1157 break;
1158
John Kessenich426394d2015-07-23 10:22:48 -06001159 case glslang::EOpAtomicAdd:
1160 case glslang::EOpAtomicMin:
1161 case glslang::EOpAtomicMax:
1162 case glslang::EOpAtomicAnd:
1163 case glslang::EOpAtomicOr:
1164 case glslang::EOpAtomicXor:
1165 case glslang::EOpAtomicExchange:
1166 case glslang::EOpAtomicCompSwap:
1167 atomic = true;
1168 break;
1169
John Kessenich140f3df2015-06-26 16:58:36 -06001170 default:
1171 break;
1172 }
1173
1174 //
1175 // See if it maps to a regular operation.
1176 //
John Kessenich140f3df2015-06-26 16:58:36 -06001177 if (binOp != glslang::EOpNull) {
1178 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1179 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1180 assert(left && right);
1181
1182 builder.clearAccessChain();
1183 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001184 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001185
1186 builder.clearAccessChain();
1187 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001188 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001189
1190 result = createBinaryOperation(binOp, precision,
1191 convertGlslangToSpvType(node->getType()), leftId, rightId,
1192 left->getType().getBasicType(), reduceComparison);
1193
1194 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001195 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001196 builder.clearAccessChain();
1197 builder.setAccessChainRValue(result);
1198
1199 return false;
1200 }
1201
John Kessenich426394d2015-07-23 10:22:48 -06001202 //
1203 // Create the list of operands.
1204 //
John Kessenich140f3df2015-06-26 16:58:36 -06001205 glslang::TIntermSequence& glslangOperands = node->getSequence();
1206 std::vector<spv::Id> operands;
1207 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1208 builder.clearAccessChain();
1209 glslangOperands[arg]->traverse(this);
1210
1211 // special case l-value operands; there are just a few
1212 bool lvalue = false;
1213 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001214 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001215 case glslang::EOpModf:
1216 if (arg == 1)
1217 lvalue = true;
1218 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001219 case glslang::EOpInterpolateAtSample:
1220 case glslang::EOpInterpolateAtOffset:
1221 if (arg == 0)
1222 lvalue = true;
1223 break;
Rex Xud4782c12015-09-06 16:30:11 +08001224 case glslang::EOpAtomicAdd:
1225 case glslang::EOpAtomicMin:
1226 case glslang::EOpAtomicMax:
1227 case glslang::EOpAtomicAnd:
1228 case glslang::EOpAtomicOr:
1229 case glslang::EOpAtomicXor:
1230 case glslang::EOpAtomicExchange:
1231 case glslang::EOpAtomicCompSwap:
1232 if (arg == 0)
1233 lvalue = true;
1234 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001235 case glslang::EOpAddCarry:
1236 case glslang::EOpSubBorrow:
1237 if (arg == 2)
1238 lvalue = true;
1239 break;
1240 case glslang::EOpUMulExtended:
1241 case glslang::EOpIMulExtended:
1242 if (arg >= 2)
1243 lvalue = true;
1244 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001245 default:
1246 break;
1247 }
1248 if (lvalue)
1249 operands.push_back(builder.accessChainGetLValue());
1250 else
John Kessenichfa668da2015-09-13 14:46:30 -06001251 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001252 }
John Kessenich426394d2015-07-23 10:22:48 -06001253
1254 if (atomic) {
1255 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001256 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001257 } else {
1258 // Pass through to generic operations.
1259 switch (glslangOperands.size()) {
1260 case 0:
1261 result = createNoArgOperation(node->getOp());
1262 break;
1263 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001264 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001265 break;
1266 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001267 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001268 break;
1269 }
John Kessenich140f3df2015-06-26 16:58:36 -06001270 }
1271
1272 if (noReturnValue)
1273 return false;
1274
1275 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001276 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001277 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001278 } else {
1279 builder.clearAccessChain();
1280 builder.setAccessChainRValue(result);
1281 return false;
1282 }
1283}
1284
1285bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1286{
1287 // This path handles both if-then-else and ?:
1288 // The if-then-else has a node type of void, while
1289 // ?: has a non-void node type
1290 spv::Id result = 0;
1291 if (node->getBasicType() != glslang::EbtVoid) {
1292 // don't handle this as just on-the-fly temporaries, because there will be two names
1293 // and better to leave SSA to later passes
1294 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1295 }
1296
1297 // emit the condition before doing anything with selection
1298 node->getCondition()->traverse(this);
1299
1300 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001301 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 if (node->getTrueBlock()) {
1304 // emit the "then" statement
1305 node->getTrueBlock()->traverse(this);
1306 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001307 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001308 }
1309
1310 if (node->getFalseBlock()) {
1311 ifBuilder.makeBeginElse();
1312 // emit the "else" statement
1313 node->getFalseBlock()->traverse(this);
1314 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001315 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001316 }
1317
1318 ifBuilder.makeEndIf();
1319
1320 if (result) {
1321 // GLSL only has r-values as the result of a :?, but
1322 // if we have an l-value, that can be more efficient if it will
1323 // become the base of a complex r-value expression, because the
1324 // next layer copies r-values into memory to use the access-chain mechanism
1325 builder.clearAccessChain();
1326 builder.setAccessChainLValue(result);
1327 }
1328
1329 return false;
1330}
1331
1332bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1333{
1334 // emit and get the condition before doing anything with switch
1335 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001336 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001337
1338 // browse the children to sort out code segments
1339 int defaultSegment = -1;
1340 std::vector<TIntermNode*> codeSegments;
1341 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1342 std::vector<int> caseValues;
1343 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1344 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1345 TIntermNode* child = *c;
1346 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001347 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001348 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001349 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001350 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1351 } else
1352 codeSegments.push_back(child);
1353 }
1354
1355 // handle the case where the last code segment is missing, due to no code
1356 // statements between the last case and the end of the switch statement
1357 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1358 (int)codeSegments.size() == defaultSegment)
1359 codeSegments.push_back(nullptr);
1360
1361 // make the switch statement
1362 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001363 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001364
1365 // emit all the code in the segments
1366 breakForLoop.push(false);
1367 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1368 builder.nextSwitchSegment(segmentBlocks, s);
1369 if (codeSegments[s])
1370 codeSegments[s]->traverse(this);
1371 else
1372 builder.addSwitchBreak();
1373 }
1374 breakForLoop.pop();
1375
1376 builder.endSwitch(segmentBlocks);
1377
1378 return false;
1379}
1380
1381void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1382{
1383 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001384 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001385
1386 builder.clearAccessChain();
1387 builder.setAccessChainRValue(constant);
1388}
1389
1390bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1391{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001392 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001393 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001394 // Spec requires back edges to target header blocks, and every header block
1395 // must dominate its merge block. Make a header block first to ensure these
1396 // conditions are met. By definition, it will contain OpLoopMerge, followed
1397 // by a block-ending branch. But we don't want to put any other body/test
1398 // instructions in it, since the body/test may have arbitrary instructions,
1399 // including merges of its own.
1400 builder.setBuildPoint(&blocks.head);
1401 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001402 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001403 spv::Block& test = builder.makeNewBlock();
1404 builder.createBranch(&test);
1405
1406 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001407 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001408 spv::Id condition =
1409 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001410 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1411
1412 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001413 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001414 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001415 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001416 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001417 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001418
1419 builder.setBuildPoint(&blocks.continue_target);
1420 if (node->getTerminal())
1421 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001422 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001423 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001424 builder.createBranch(&blocks.body);
1425
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001426 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001427 builder.setBuildPoint(&blocks.body);
1428 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001429 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001430 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001431 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001432
1433 builder.setBuildPoint(&blocks.continue_target);
1434 if (node->getTerminal())
1435 node->getTerminal()->traverse(this);
1436 if (node->getTest()) {
1437 node->getTest()->traverse(this);
1438 spv::Id condition =
1439 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001440 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001441 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001442 // TODO: unless there was a break/return/discard instruction
1443 // somewhere in the body, this is an infinite loop, so we should
1444 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001445 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001446 }
John Kessenich140f3df2015-06-26 16:58:36 -06001447 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001448 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001449 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001450 return false;
1451}
1452
1453bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1454{
1455 if (node->getExpression())
1456 node->getExpression()->traverse(this);
1457
1458 switch (node->getFlowOp()) {
1459 case glslang::EOpKill:
1460 builder.makeDiscard();
1461 break;
1462 case glslang::EOpBreak:
1463 if (breakForLoop.top())
1464 builder.createLoopExit();
1465 else
1466 builder.addSwitchBreak();
1467 break;
1468 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001469 builder.createLoopContinue();
1470 break;
1471 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001472 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001473 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001474 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001475 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001476
1477 builder.clearAccessChain();
1478 break;
1479
1480 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001481 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001482 break;
1483 }
1484
1485 return false;
1486}
1487
1488spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1489{
1490 // First, steer off constants, which are not SPIR-V variables, but
1491 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001492 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001493 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001494 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001495 }
1496
1497 // Now, handle actual variables
1498 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1499 spv::Id spvType = convertGlslangToSpvType(node->getType());
1500
1501 const char* name = node->getName().c_str();
1502 if (glslang::IsAnonymous(name))
1503 name = "";
1504
1505 return builder.createVariable(storageClass, spvType, name);
1506}
1507
1508// Return type Id of the sampled type.
1509spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1510{
1511 switch (sampler.type) {
1512 case glslang::EbtFloat: return builder.makeFloatType(32);
1513 case glslang::EbtInt: return builder.makeIntType(32);
1514 case glslang::EbtUint: return builder.makeUintType(32);
1515 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001516 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001517 return builder.makeFloatType(32);
1518 }
1519}
1520
John Kessenich3ac051e2015-12-20 11:29:16 -07001521// Convert from a glslang type to an SPV type, by calling into a
1522// recursive version of this function. This establishes the inherited
1523// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001524spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1525{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001526 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001527}
1528
1529// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1530// explicitLayout can be kept the same throughout the heirarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001531spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001532{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001533 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001534
1535 switch (type.getBasicType()) {
1536 case glslang::EbtVoid:
1537 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001538 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001539 break;
1540 case glslang::EbtFloat:
1541 spvType = builder.makeFloatType(32);
1542 break;
1543 case glslang::EbtDouble:
1544 spvType = builder.makeFloatType(64);
1545 break;
1546 case glslang::EbtBool:
1547 spvType = builder.makeBoolType();
1548 break;
1549 case glslang::EbtInt:
1550 spvType = builder.makeIntType(32);
1551 break;
1552 case glslang::EbtUint:
1553 spvType = builder.makeUintType(32);
1554 break;
John Kessenich426394d2015-07-23 10:22:48 -06001555 case glslang::EbtAtomicUint:
1556 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1557 spvType = builder.makeUintType(32);
1558 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001559 case glslang::EbtSampler:
1560 {
1561 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001562 // an image is present, make its type
1563 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1564 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001565 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001566 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001567 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001568 }
John Kessenich140f3df2015-06-26 16:58:36 -06001569 break;
1570 case glslang::EbtStruct:
1571 case glslang::EbtBlock:
1572 {
1573 // If we've seen this struct type, return it
1574 const glslang::TTypeList* glslangStruct = type.getStruct();
1575 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001576
1577 // Try to share structs for different layouts, but not yet for other
1578 // kinds of qualification (primarily not yet including interpolant qualification).
1579 if (! HasNonLayoutQualifiers(qualifier))
1580 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1581 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001582 break;
1583
1584 // else, we haven't seen it...
1585
1586 // Create a vector of struct types for SPIR-V to consume
1587 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1588 if (type.getBasicType() == glslang::EbtBlock)
1589 memberRemapper[glslangStruct].resize(glslangStruct->size());
1590 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1591 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1592 if (glslangType.hiddenMember()) {
1593 ++memberDelta;
1594 if (type.getBasicType() == glslang::EbtBlock)
1595 memberRemapper[glslangStruct][i] = -1;
1596 } else {
1597 if (type.getBasicType() == glslang::EbtBlock)
1598 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001599 // modify just this child's view of the qualifier
1600 glslang::TQualifier subQualifier = glslangType.getQualifier();
1601 InheritQualifiers(subQualifier, qualifier);
1602 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001603 }
1604 }
1605
1606 // Make the SPIR-V type
1607 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001608 if (! HasNonLayoutQualifiers(qualifier))
1609 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001610
1611 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001612 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001613 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1614 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1615 int member = i;
1616 if (type.getBasicType() == glslang::EbtBlock)
1617 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001618
John Kesseniche0b6cad2015-12-24 10:30:13 -07001619 // modify just this child's view of the qualifier
1620 glslang::TQualifier subQualifier = glslangType.getQualifier();
1621 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001622
John Kessenich140f3df2015-06-26 16:58:36 -06001623 // using -1 above to indicate a hidden member
1624 if (member >= 0) {
1625 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001626 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001627 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001628 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1629 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001630 if (glslangType.getQualifier().hasLocation())
1631 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1632 if (glslangType.getQualifier().hasComponent())
1633 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1634 if (glslangType.getQualifier().hasXfbOffset())
1635 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001636 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001637 // figure out what to do with offset, which is accumulating
1638 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001639 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001640 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001641 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001642 offset = nextOffset;
1643 }
John Kessenich140f3df2015-06-26 16:58:36 -06001644
John Kessenichf85e8062015-12-19 13:57:10 -07001645 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001646 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001647
John Kessenich140f3df2015-06-26 16:58:36 -06001648 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001649 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1650 if (builtIn != spv::BadValue)
1651 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001652 }
1653 }
1654
1655 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001656 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001657 addDecoration(spvType, TranslateBlockDecoration(type));
1658 if (type.getQualifier().hasStream())
1659 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1660 if (glslangIntermediate->getXfbMode()) {
1661 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001662 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001663 if (type.getQualifier().hasXfbBuffer())
1664 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1665 }
1666 }
1667 break;
1668 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001669 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001670 break;
1671 }
1672
1673 if (type.isMatrix())
1674 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1675 else {
1676 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1677 if (type.getVectorSize() > 1)
1678 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1679 }
1680
1681 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001682 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1683
John Kessenichc9a80832015-09-12 12:17:44 -06001684 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001685 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001686 // We need to decorate array strides for types needing explicit layout, except blocks.
1687 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001688 // Use a dummy glslang type for querying internal strides of
1689 // arrays of arrays, but using just a one-dimensional array.
1690 glslang::TType simpleArrayType(type, 0); // deference type of the array
1691 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1692 simpleArrayType.getArraySizes().dereference();
1693
1694 // Will compute the higher-order strides here, rather than making a whole
1695 // pile of types and doing repetitive recursion on their contents.
1696 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1697 }
John Kessenichf8842e52016-01-04 19:22:56 -07001698
1699 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001700 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1701 int size = type.getArraySizes()->getDimSize(dim);
1702 assert(size > 0);
1703 spvType = builder.makeArrayType(spvType, size, stride);
1704 if (stride > 0)
1705 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1706 stride *= size;
1707 }
1708 } else {
1709 // single-dimensional array, and don't yet have stride
1710
John Kessenichf8842e52016-01-04 19:22:56 -07001711 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001712 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1713 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001714 }
John Kessenich31ed4832015-09-09 17:51:38 -06001715
John Kessenichc9a80832015-09-12 12:17:44 -06001716 // Do the outer dimension, which might not be known for a runtime-sized array
1717 if (type.isRuntimeSizedArray()) {
1718 spvType = builder.makeRuntimeArray(spvType);
1719 } else {
1720 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001721 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001722 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001723 if (stride > 0)
1724 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001725 }
1726
1727 return spvType;
1728}
1729
John Kessenichf85e8062015-12-19 13:57:10 -07001730// Decide whether or not this type should be
1731// decorated with offsets and strides, and if so
1732// whether std140 or std430 rules should be applied.
1733glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001734{
John Kessenichf85e8062015-12-19 13:57:10 -07001735 // has to be a block
1736 if (type.getBasicType() != glslang::EbtBlock)
1737 return glslang::ElpNone;
1738
1739 // has to be a uniform or buffer block
1740 if (type.getQualifier().storage != glslang::EvqUniform &&
1741 type.getQualifier().storage != glslang::EvqBuffer)
1742 return glslang::ElpNone;
1743
1744 // return the layout to use
1745 switch (type.getQualifier().layoutPacking) {
1746 case glslang::ElpStd140:
1747 case glslang::ElpStd430:
1748 return type.getQualifier().layoutPacking;
1749 default:
1750 return glslang::ElpNone;
1751 }
John Kessenich31ed4832015-09-09 17:51:38 -06001752}
1753
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001754// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001755int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001756{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001757 int size;
John Kessenich49987892015-12-29 17:11:44 -07001758 int stride;
1759 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001760
1761 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001762}
1763
John Kessenich49987892015-12-29 17:11:44 -07001764// 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 -07001765// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001766int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001767{
John Kessenich49987892015-12-29 17:11:44 -07001768 glslang::TType elementType;
1769 elementType.shallowCopy(matrixType);
1770 elementType.clearArraySizes();
1771
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001772 int size;
John Kessenich49987892015-12-29 17:11:44 -07001773 int stride;
1774 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1775
1776 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001777}
1778
John Kessenich5e4b1242015-08-06 22:53:06 -06001779// Given a member type of a struct, realign the current offset for it, and compute
1780// the next (not yet aligned) offset for the next member, which will get aligned
1781// on the next call.
1782// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1783// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1784// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001785void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001786 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001787{
1788 // this will get a positive value when deemed necessary
1789 nextOffset = -1;
1790
John Kessenich5e4b1242015-08-06 22:53:06 -06001791 // override anything in currentOffset with user-set offset
1792 if (memberType.getQualifier().hasOffset())
1793 currentOffset = memberType.getQualifier().layoutOffset;
1794
1795 // It could be that current linker usage in glslang updated all the layoutOffset,
1796 // in which case the following code does not matter. But, that's not quite right
1797 // once cross-compilation unit GLSL validation is done, as the original user
1798 // settings are needed in layoutOffset, and then the following will come into play.
1799
John Kessenichf85e8062015-12-19 13:57:10 -07001800 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001801 if (! memberType.getQualifier().hasOffset())
1802 currentOffset = -1;
1803
1804 return;
1805 }
1806
John Kessenichf85e8062015-12-19 13:57:10 -07001807 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001808 if (currentOffset < 0)
1809 currentOffset = 0;
1810
1811 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1812 // but possibly not yet correctly aligned.
1813
1814 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001815 int dummyStride;
1816 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001817 glslang::RoundToPow2(currentOffset, memberAlignment);
1818 nextOffset = currentOffset + memberSize;
1819}
1820
John Kessenich140f3df2015-06-26 16:58:36 -06001821bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1822{
1823 return node->getName() == "main(";
1824}
1825
1826// Make all the functions, skeletally, without actually visiting their bodies.
1827void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1828{
1829 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1830 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1831 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1832 continue;
1833
1834 // We're on a user function. Set up the basic interface for the function now,
1835 // so that it's available to call.
1836 // Translating the body will happen later.
1837 //
1838 // Typically (except for a "const in" parameter), an address will be passed to the
1839 // function. What it is an address of varies:
1840 //
1841 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1842 // so that write needs to be to a copy, hence the address of a copy works.
1843 //
1844 // - "const in" parameters can just be the r-value, as no writes need occur.
1845 //
1846 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1847 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1848
1849 std::vector<spv::Id> paramTypes;
1850 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1851
1852 for (int p = 0; p < (int)parameters.size(); ++p) {
1853 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1854 spv::Id typeId = convertGlslangToSpvType(paramType);
1855 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1856 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1857 else
1858 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1859 paramTypes.push_back(typeId);
1860 }
1861
1862 spv::Block* functionBlock;
1863 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1864 paramTypes, &functionBlock);
1865
1866 // Track function to emit/call later
1867 functionMap[glslFunction->getName().c_str()] = function;
1868
1869 // Set the parameter id's
1870 for (int p = 0; p < (int)parameters.size(); ++p) {
1871 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1872 // give a name too
1873 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1874 }
1875 }
1876}
1877
1878// Process all the initializers, while skipping the functions and link objects
1879void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1880{
1881 builder.setBuildPoint(shaderEntry->getLastBlock());
1882 for (int i = 0; i < (int)initializers.size(); ++i) {
1883 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1884 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1885
1886 // We're on a top-level node that's not a function. Treat as an initializer, whose
1887 // code goes into the beginning of main.
1888 initializer->traverse(this);
1889 }
1890 }
1891}
1892
1893// Process all the functions, while skipping initializers.
1894void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1895{
1896 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1897 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1898 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1899 node->traverse(this);
1900 }
1901}
1902
1903void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1904{
1905 // SPIR-V functions should already be in the functionMap from the prepass
1906 // that called makeFunctions().
1907 spv::Function* function = functionMap[node->getName().c_str()];
1908 spv::Block* functionBlock = function->getEntryBlock();
1909 builder.setBuildPoint(functionBlock);
1910}
1911
Rex Xu04db3f52015-09-16 11:44:02 +08001912void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001913{
Rex Xufc618912015-09-09 16:42:49 +08001914 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08001915
1916 glslang::TSampler sampler = {};
1917 bool cubeCompare = false;
1918 if (node.isTexture()) {
1919 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
1920 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1921 }
1922
John Kessenich140f3df2015-06-26 16:58:36 -06001923 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1924 builder.clearAccessChain();
1925 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001926
1927 // Special case l-value operands
1928 bool lvalue = false;
1929 switch (node.getOp()) {
1930 case glslang::EOpImageAtomicAdd:
1931 case glslang::EOpImageAtomicMin:
1932 case glslang::EOpImageAtomicMax:
1933 case glslang::EOpImageAtomicAnd:
1934 case glslang::EOpImageAtomicOr:
1935 case glslang::EOpImageAtomicXor:
1936 case glslang::EOpImageAtomicExchange:
1937 case glslang::EOpImageAtomicCompSwap:
1938 if (i == 0)
1939 lvalue = true;
1940 break;
Rex Xu48edadf2015-12-31 16:11:41 +08001941 case glslang::EOpSparseTexture:
1942 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
1943 lvalue = true;
1944 break;
1945 case glslang::EOpSparseTextureClamp:
1946 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
1947 lvalue = true;
1948 break;
1949 case glslang::EOpSparseTextureLod:
1950 case glslang::EOpSparseTextureOffset:
1951 if (i == 3)
1952 lvalue = true;
1953 break;
1954 case glslang::EOpSparseTextureFetch:
1955 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
1956 lvalue = true;
1957 break;
1958 case glslang::EOpSparseTextureFetchOffset:
1959 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
1960 lvalue = true;
1961 break;
1962 case glslang::EOpSparseTextureLodOffset:
1963 case glslang::EOpSparseTextureGrad:
1964 case glslang::EOpSparseTextureOffsetClamp:
1965 if (i == 4)
1966 lvalue = true;
1967 break;
1968 case glslang::EOpSparseTextureGradOffset:
1969 case glslang::EOpSparseTextureGradClamp:
1970 if (i == 5)
1971 lvalue = true;
1972 break;
1973 case glslang::EOpSparseTextureGradOffsetClamp:
1974 if (i == 6)
1975 lvalue = true;
1976 break;
1977 case glslang::EOpSparseTextureGather:
1978 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
1979 lvalue = true;
1980 break;
1981 case glslang::EOpSparseTextureGatherOffset:
1982 case glslang::EOpSparseTextureGatherOffsets:
1983 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
1984 lvalue = true;
1985 break;
Rex Xufc618912015-09-09 16:42:49 +08001986 default:
1987 break;
1988 }
1989
Rex Xu6b86d492015-09-16 17:48:22 +08001990 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001991 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001992 else
Rex Xu30f92582015-09-14 10:38:56 +08001993 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001994 }
1995}
1996
John Kessenichfc51d282015-08-19 13:34:18 -06001997void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001998{
John Kessenichfc51d282015-08-19 13:34:18 -06001999 builder.clearAccessChain();
2000 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002001 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06002002}
John Kessenich140f3df2015-06-26 16:58:36 -06002003
John Kessenichfc51d282015-08-19 13:34:18 -06002004spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2005{
Rex Xufc618912015-09-09 16:42:49 +08002006 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002007 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002008 }
2009
John Kessenichfc51d282015-08-19 13:34:18 -06002010 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002011 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2012 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2013 std::vector<spv::Id> arguments;
2014 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002015 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002016 else
2017 translateArguments(*node->getAsUnaryNode(), arguments);
2018 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2019
2020 spv::Builder::TextureParameters params = { };
2021 params.sampler = arguments[0];
2022
Rex Xu04db3f52015-09-16 11:44:02 +08002023 glslang::TCrackedTextureOp cracked;
2024 node->crackTexture(sampler, cracked);
2025
John Kessenichfc51d282015-08-19 13:34:18 -06002026 // Check for queries
2027 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002028 // a sampled image needs to have the image extracted first
2029 if (builder.isSampledImage(params.sampler))
2030 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002031 switch (node->getOp()) {
2032 case glslang::EOpImageQuerySize:
2033 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002034 if (arguments.size() > 1) {
2035 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002036 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002037 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002038 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002039 case glslang::EOpImageQuerySamples:
2040 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002041 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002042 case glslang::EOpTextureQueryLod:
2043 params.coords = arguments[1];
2044 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2045 case glslang::EOpTextureQueryLevels:
2046 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002047 case glslang::EOpSparseTexelsResident:
2048 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002049 default:
2050 assert(0);
2051 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002052 }
John Kessenich140f3df2015-06-26 16:58:36 -06002053 }
2054
Rex Xufc618912015-09-09 16:42:49 +08002055 // Check for image functions other than queries
2056 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002057 std::vector<spv::Id> operands;
2058 auto opIt = arguments.begin();
2059 operands.push_back(*(opIt++));
2060 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002061 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002062 if (sampler.ms) {
2063 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002064 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002065 }
John Kessenich56bab042015-09-16 10:54:31 -06002066 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2067 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002068 if (sampler.ms) {
2069 operands.push_back(*(opIt + 1));
2070 operands.push_back(spv::ImageOperandsSampleMask);
2071 operands.push_back(*opIt);
2072 } else
2073 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002074 builder.createNoResultOp(spv::OpImageWrite, operands);
2075 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002076 } else if (node->isSparseImage()) {
2077 spv::MissingFunctionality("sparse image functions");
2078 return spv::NoResult;
2079 }
2080 else {
Rex Xu6b86d492015-09-16 17:48:22 +08002081 // Process image atomic operations
2082
2083 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2084 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06002085 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002086
Rex Xufc618912015-09-09 16:42:49 +08002087 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002088 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002089
2090 std::vector<spv::Id> operands;
2091 operands.push_back(pointer);
2092 for (; opIt != arguments.end(); ++opIt)
2093 operands.push_back(*opIt);
2094
Rex Xu04db3f52015-09-16 11:44:02 +08002095 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002096 }
2097 }
2098
2099 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002100 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002101 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2102
John Kessenichfc51d282015-08-19 13:34:18 -06002103 // check for bias argument
2104 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002105 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002106 int nonBiasArgCount = 2;
2107 if (cracked.offset)
2108 ++nonBiasArgCount;
2109 if (cracked.grad)
2110 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002111 if (cracked.lodClamp)
2112 ++nonBiasArgCount;
2113 if (sparse)
2114 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002115
2116 if ((int)arguments.size() > nonBiasArgCount)
2117 bias = true;
2118 }
2119
John Kessenichfc51d282015-08-19 13:34:18 -06002120 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002121
John Kessenichfc51d282015-08-19 13:34:18 -06002122 params.coords = arguments[1];
2123 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002124
2125 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002126 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002127 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002128 ++extraArgs;
2129 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002130 params.Dref = arguments[2];
2131 ++extraArgs;
2132 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002133 std::vector<spv::Id> indexes;
2134 int comp;
2135 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002136 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002137 else
2138 comp = builder.getNumComponents(params.coords) - 1;
2139 indexes.push_back(comp);
2140 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2141 }
2142 if (cracked.lod) {
2143 params.lod = arguments[2];
2144 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002145 } else if (sampler.ms) {
2146 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002147 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002148 }
2149 if (cracked.grad) {
2150 params.gradX = arguments[2 + extraArgs];
2151 params.gradY = arguments[3 + extraArgs];
2152 extraArgs += 2;
2153 }
John Kessenich55e7d112015-11-15 21:33:39 -07002154 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002155 params.offset = arguments[2 + extraArgs];
2156 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002157 } else if (cracked.offsets) {
2158 params.offsets = arguments[2 + extraArgs];
2159 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002160 }
Rex Xu48edadf2015-12-31 16:11:41 +08002161 if (cracked.lodClamp) {
2162 params.lodClamp = arguments[2 + extraArgs];
2163 ++extraArgs;
2164 }
2165 if (sparse) {
2166 params.texelOut = arguments[2 + extraArgs];
2167 ++extraArgs;
2168 }
John Kessenichfc51d282015-08-19 13:34:18 -06002169 if (bias) {
2170 params.bias = arguments[2 + extraArgs];
2171 ++extraArgs;
2172 }
John Kessenich55e7d112015-11-15 21:33:39 -07002173 if (cracked.gather && ! sampler.shadow) {
2174 // default component is 0, if missing, otherwise an argument
2175 if (2 + extraArgs < (int)arguments.size()) {
2176 params.comp = arguments[2 + extraArgs];
2177 ++extraArgs;
2178 } else {
2179 params.comp = builder.makeIntConstant(0);
2180 }
2181 }
John Kessenichfc51d282015-08-19 13:34:18 -06002182
Rex Xu48edadf2015-12-31 16:11:41 +08002183 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002184}
2185
2186spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2187{
2188 // Grab the function's pointer from the previously created function
2189 spv::Function* function = functionMap[node->getName().c_str()];
2190 if (! function)
2191 return 0;
2192
2193 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2194 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2195
2196 // See comments in makeFunctions() for details about the semantics for parameter passing.
2197 //
2198 // These imply we need a four step process:
2199 // 1. Evaluate the arguments
2200 // 2. Allocate and make copies of in, out, and inout arguments
2201 // 3. Make the call
2202 // 4. Copy back the results
2203
2204 // 1. Evaluate the arguments
2205 std::vector<spv::Builder::AccessChain> lValues;
2206 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002207 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002208 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2209 // build l-value
2210 builder.clearAccessChain();
2211 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002212 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002213 // keep outputs as l-values, evaluate input-only as r-values
2214 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2215 // save l-value
2216 lValues.push_back(builder.getAccessChain());
2217 } else {
2218 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002219 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002220 }
2221 }
2222
2223 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2224 // copy the original into that space.
2225 //
2226 // Also, build up the list of actual arguments to pass in for the call
2227 int lValueCount = 0;
2228 int rValueCount = 0;
2229 std::vector<spv::Id> spvArgs;
2230 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2231 spv::Id arg;
2232 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2233 // need space to hold the copy
2234 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2235 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2236 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2237 // need to copy the input into output space
2238 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002239 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002240 builder.createStore(copy, arg);
2241 }
2242 ++lValueCount;
2243 } else {
2244 arg = rValues[rValueCount];
2245 ++rValueCount;
2246 }
2247 spvArgs.push_back(arg);
2248 }
2249
2250 // 3. Make the call.
2251 spv::Id result = builder.createFunctionCall(function, spvArgs);
2252
2253 // 4. Copy back out an "out" arguments.
2254 lValueCount = 0;
2255 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2256 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2257 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2258 spv::Id copy = builder.createLoad(spvArgs[a]);
2259 builder.setAccessChain(lValues[lValueCount]);
2260 builder.accessChainStore(copy);
2261 }
2262 ++lValueCount;
2263 }
2264 }
2265
2266 return result;
2267}
2268
2269// Translate AST operation to SPV operation, already having SPV-based operands/types.
2270spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2271 spv::Id typeId, spv::Id left, spv::Id right,
2272 glslang::TBasicType typeProxy, bool reduceComparison)
2273{
2274 bool isUnsigned = typeProxy == glslang::EbtUint;
2275 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2276
2277 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002278 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002279 bool comparison = false;
2280
2281 switch (op) {
2282 case glslang::EOpAdd:
2283 case glslang::EOpAddAssign:
2284 if (isFloat)
2285 binOp = spv::OpFAdd;
2286 else
2287 binOp = spv::OpIAdd;
2288 break;
2289 case glslang::EOpSub:
2290 case glslang::EOpSubAssign:
2291 if (isFloat)
2292 binOp = spv::OpFSub;
2293 else
2294 binOp = spv::OpISub;
2295 break;
2296 case glslang::EOpMul:
2297 case glslang::EOpMulAssign:
2298 if (isFloat)
2299 binOp = spv::OpFMul;
2300 else
2301 binOp = spv::OpIMul;
2302 break;
2303 case glslang::EOpVectorTimesScalar:
2304 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002305 if (isFloat) {
2306 if (builder.isVector(right))
2307 std::swap(left, right);
2308 assert(builder.isScalar(right));
2309 needMatchingVectors = false;
2310 binOp = spv::OpVectorTimesScalar;
2311 } else
2312 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002313 break;
2314 case glslang::EOpVectorTimesMatrix:
2315 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002316 binOp = spv::OpVectorTimesMatrix;
2317 break;
2318 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002319 binOp = spv::OpMatrixTimesVector;
2320 break;
2321 case glslang::EOpMatrixTimesScalar:
2322 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002323 binOp = spv::OpMatrixTimesScalar;
2324 break;
2325 case glslang::EOpMatrixTimesMatrix:
2326 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002327 binOp = spv::OpMatrixTimesMatrix;
2328 break;
2329 case glslang::EOpOuterProduct:
2330 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002331 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002332 break;
2333
2334 case glslang::EOpDiv:
2335 case glslang::EOpDivAssign:
2336 if (isFloat)
2337 binOp = spv::OpFDiv;
2338 else if (isUnsigned)
2339 binOp = spv::OpUDiv;
2340 else
2341 binOp = spv::OpSDiv;
2342 break;
2343 case glslang::EOpMod:
2344 case glslang::EOpModAssign:
2345 if (isFloat)
2346 binOp = spv::OpFMod;
2347 else if (isUnsigned)
2348 binOp = spv::OpUMod;
2349 else
2350 binOp = spv::OpSMod;
2351 break;
2352 case glslang::EOpRightShift:
2353 case glslang::EOpRightShiftAssign:
2354 if (isUnsigned)
2355 binOp = spv::OpShiftRightLogical;
2356 else
2357 binOp = spv::OpShiftRightArithmetic;
2358 break;
2359 case glslang::EOpLeftShift:
2360 case glslang::EOpLeftShiftAssign:
2361 binOp = spv::OpShiftLeftLogical;
2362 break;
2363 case glslang::EOpAnd:
2364 case glslang::EOpAndAssign:
2365 binOp = spv::OpBitwiseAnd;
2366 break;
2367 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002368 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002369 binOp = spv::OpLogicalAnd;
2370 break;
2371 case glslang::EOpInclusiveOr:
2372 case glslang::EOpInclusiveOrAssign:
2373 binOp = spv::OpBitwiseOr;
2374 break;
2375 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002376 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002377 binOp = spv::OpLogicalOr;
2378 break;
2379 case glslang::EOpExclusiveOr:
2380 case glslang::EOpExclusiveOrAssign:
2381 binOp = spv::OpBitwiseXor;
2382 break;
2383 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002384 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002385 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002386 break;
2387
2388 case glslang::EOpLessThan:
2389 case glslang::EOpGreaterThan:
2390 case glslang::EOpLessThanEqual:
2391 case glslang::EOpGreaterThanEqual:
2392 case glslang::EOpEqual:
2393 case glslang::EOpNotEqual:
2394 case glslang::EOpVectorEqual:
2395 case glslang::EOpVectorNotEqual:
2396 comparison = true;
2397 break;
2398 default:
2399 break;
2400 }
2401
John Kessenich7c1aa102015-10-15 13:29:11 -06002402 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002403 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002404 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002405 if (builder.isMatrix(left) || builder.isMatrix(right))
2406 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002407
2408 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002409 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002410 builder.promoteScalar(precision, left, right);
2411
2412 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2413 builder.setPrecision(id, precision);
2414
2415 return id;
2416 }
2417
2418 if (! comparison)
2419 return 0;
2420
John Kessenich7c1aa102015-10-15 13:29:11 -06002421 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002422
2423 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2424 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2425
John Kessenich22118352015-12-21 20:54:09 -07002426 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002427 }
2428
2429 switch (op) {
2430 case glslang::EOpLessThan:
2431 if (isFloat)
2432 binOp = spv::OpFOrdLessThan;
2433 else if (isUnsigned)
2434 binOp = spv::OpULessThan;
2435 else
2436 binOp = spv::OpSLessThan;
2437 break;
2438 case glslang::EOpGreaterThan:
2439 if (isFloat)
2440 binOp = spv::OpFOrdGreaterThan;
2441 else if (isUnsigned)
2442 binOp = spv::OpUGreaterThan;
2443 else
2444 binOp = spv::OpSGreaterThan;
2445 break;
2446 case glslang::EOpLessThanEqual:
2447 if (isFloat)
2448 binOp = spv::OpFOrdLessThanEqual;
2449 else if (isUnsigned)
2450 binOp = spv::OpULessThanEqual;
2451 else
2452 binOp = spv::OpSLessThanEqual;
2453 break;
2454 case glslang::EOpGreaterThanEqual:
2455 if (isFloat)
2456 binOp = spv::OpFOrdGreaterThanEqual;
2457 else if (isUnsigned)
2458 binOp = spv::OpUGreaterThanEqual;
2459 else
2460 binOp = spv::OpSGreaterThanEqual;
2461 break;
2462 case glslang::EOpEqual:
2463 case glslang::EOpVectorEqual:
2464 if (isFloat)
2465 binOp = spv::OpFOrdEqual;
2466 else
2467 binOp = spv::OpIEqual;
2468 break;
2469 case glslang::EOpNotEqual:
2470 case glslang::EOpVectorNotEqual:
2471 if (isFloat)
2472 binOp = spv::OpFOrdNotEqual;
2473 else
2474 binOp = spv::OpINotEqual;
2475 break;
2476 default:
2477 break;
2478 }
2479
2480 if (binOp != spv::OpNop) {
2481 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2482 builder.setPrecision(id, precision);
2483
2484 return id;
2485 }
2486
2487 return 0;
2488}
2489
John Kessenich04bb8a02015-12-12 12:28:14 -07002490//
2491// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2492// These can be any of:
2493//
2494// matrix * scalar
2495// scalar * matrix
2496// matrix * matrix linear algebraic
2497// matrix * vector
2498// vector * matrix
2499// matrix * matrix componentwise
2500// matrix op matrix op in {+, -, /}
2501// matrix op scalar op in {+, -, /}
2502// scalar op matrix op in {+, -, /}
2503//
2504spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2505{
2506 bool firstClass = true;
2507
2508 // First, handle first-class matrix operations (* and matrix/scalar)
2509 switch (op) {
2510 case spv::OpFDiv:
2511 if (builder.isMatrix(left) && builder.isScalar(right)) {
2512 // turn matrix / scalar into a multiply...
2513 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2514 op = spv::OpMatrixTimesScalar;
2515 } else
2516 firstClass = false;
2517 break;
2518 case spv::OpMatrixTimesScalar:
2519 if (builder.isMatrix(right))
2520 std::swap(left, right);
2521 assert(builder.isScalar(right));
2522 break;
2523 case spv::OpVectorTimesMatrix:
2524 assert(builder.isVector(left));
2525 assert(builder.isMatrix(right));
2526 break;
2527 case spv::OpMatrixTimesVector:
2528 assert(builder.isMatrix(left));
2529 assert(builder.isVector(right));
2530 break;
2531 case spv::OpMatrixTimesMatrix:
2532 assert(builder.isMatrix(left));
2533 assert(builder.isMatrix(right));
2534 break;
2535 default:
2536 firstClass = false;
2537 break;
2538 }
2539
2540 if (firstClass) {
2541 spv::Id id = builder.createBinOp(op, typeId, left, right);
2542 builder.setPrecision(id, precision);
2543
2544 return id;
2545 }
2546
2547 // Handle component-wise +, -, *, and / for all combinations of type.
2548 // The result type of all of them is the same type as the (a) matrix operand.
2549 // The algorithm is to:
2550 // - break the matrix(es) into vectors
2551 // - smear any scalar to a vector
2552 // - do vector operations
2553 // - make a matrix out the vector results
2554 switch (op) {
2555 case spv::OpFAdd:
2556 case spv::OpFSub:
2557 case spv::OpFDiv:
2558 case spv::OpFMul:
2559 {
2560 // one time set up...
2561 bool leftMat = builder.isMatrix(left);
2562 bool rightMat = builder.isMatrix(right);
2563 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2564 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2565 spv::Id scalarType = builder.getScalarTypeId(typeId);
2566 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2567 std::vector<spv::Id> results;
2568 spv::Id smearVec = spv::NoResult;
2569 if (builder.isScalar(left))
2570 smearVec = builder.smearScalar(precision, left, vecType);
2571 else if (builder.isScalar(right))
2572 smearVec = builder.smearScalar(precision, right, vecType);
2573
2574 // do each vector op
2575 for (unsigned int c = 0; c < numCols; ++c) {
2576 std::vector<unsigned int> indexes;
2577 indexes.push_back(c);
2578 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2579 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2580 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2581 builder.setPrecision(results.back(), precision);
2582 }
2583
2584 // put the pieces together
2585 spv::Id id = builder.createCompositeConstruct(typeId, results);
2586 builder.setPrecision(id, precision);
2587 return id;
2588 }
2589 default:
2590 assert(0);
2591 return spv::NoResult;
2592 }
2593}
2594
Rex Xu04db3f52015-09-16 11:44:02 +08002595spv::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 -06002596{
2597 spv::Op unaryOp = spv::OpNop;
2598 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002599 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002600 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002601
2602 switch (op) {
2603 case glslang::EOpNegative:
2604 if (isFloat)
2605 unaryOp = spv::OpFNegate;
2606 else
2607 unaryOp = spv::OpSNegate;
2608 break;
2609
2610 case glslang::EOpLogicalNot:
2611 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002612 unaryOp = spv::OpLogicalNot;
2613 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002614 case glslang::EOpBitwiseNot:
2615 unaryOp = spv::OpNot;
2616 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002617
John Kessenich140f3df2015-06-26 16:58:36 -06002618 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002619 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002620 break;
2621 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002622 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002623 break;
2624 case glslang::EOpTranspose:
2625 unaryOp = spv::OpTranspose;
2626 break;
2627
2628 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002629 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002630 break;
2631 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002632 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002633 break;
2634 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002635 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002636 break;
2637 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002638 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002639 break;
2640 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002641 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002642 break;
2643 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002644 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002645 break;
2646 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002647 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002648 break;
2649 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002650 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002651 break;
2652
2653 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002654 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002655 break;
2656 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002657 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002658 break;
2659 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002660 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002661 break;
2662 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002663 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002664 break;
2665 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002666 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002667 break;
2668 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002669 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002670 break;
2671
2672 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002673 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002674 break;
2675 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002676 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002677 break;
2678
2679 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002680 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002681 break;
2682 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002683 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002684 break;
2685 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002686 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002687 break;
2688 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002689 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002690 break;
2691 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002692 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002693 break;
2694 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002695 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002696 break;
2697
2698 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002699 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002700 break;
2701 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002702 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002703 break;
2704 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002705 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002706 break;
2707 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002709 break;
2710 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002711 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002712 break;
2713 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002714 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002715 break;
2716
2717 case glslang::EOpIsNan:
2718 unaryOp = spv::OpIsNan;
2719 break;
2720 case glslang::EOpIsInf:
2721 unaryOp = spv::OpIsInf;
2722 break;
2723
Rex Xucbc426e2015-12-15 16:03:10 +08002724 case glslang::EOpFloatBitsToInt:
2725 case glslang::EOpFloatBitsToUint:
2726 case glslang::EOpIntBitsToFloat:
2727 case glslang::EOpUintBitsToFloat:
2728 unaryOp = spv::OpBitcast;
2729 break;
2730
John Kessenich140f3df2015-06-26 16:58:36 -06002731 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002732 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002733 break;
2734 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002735 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002736 break;
2737 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002738 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002739 break;
2740 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002741 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002742 break;
2743 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002744 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002745 break;
2746 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002747 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002748 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002749 case glslang::EOpPackSnorm4x8:
2750 libCall = spv::GLSLstd450PackSnorm4x8;
2751 break;
2752 case glslang::EOpUnpackSnorm4x8:
2753 libCall = spv::GLSLstd450UnpackSnorm4x8;
2754 break;
2755 case glslang::EOpPackUnorm4x8:
2756 libCall = spv::GLSLstd450PackUnorm4x8;
2757 break;
2758 case glslang::EOpUnpackUnorm4x8:
2759 libCall = spv::GLSLstd450UnpackUnorm4x8;
2760 break;
2761 case glslang::EOpPackDouble2x32:
2762 libCall = spv::GLSLstd450PackDouble2x32;
2763 break;
2764 case glslang::EOpUnpackDouble2x32:
2765 libCall = spv::GLSLstd450UnpackDouble2x32;
2766 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002767
2768 case glslang::EOpDPdx:
2769 unaryOp = spv::OpDPdx;
2770 break;
2771 case glslang::EOpDPdy:
2772 unaryOp = spv::OpDPdy;
2773 break;
2774 case glslang::EOpFwidth:
2775 unaryOp = spv::OpFwidth;
2776 break;
2777 case glslang::EOpDPdxFine:
2778 unaryOp = spv::OpDPdxFine;
2779 break;
2780 case glslang::EOpDPdyFine:
2781 unaryOp = spv::OpDPdyFine;
2782 break;
2783 case glslang::EOpFwidthFine:
2784 unaryOp = spv::OpFwidthFine;
2785 break;
2786 case glslang::EOpDPdxCoarse:
2787 unaryOp = spv::OpDPdxCoarse;
2788 break;
2789 case glslang::EOpDPdyCoarse:
2790 unaryOp = spv::OpDPdyCoarse;
2791 break;
2792 case glslang::EOpFwidthCoarse:
2793 unaryOp = spv::OpFwidthCoarse;
2794 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002795 case glslang::EOpInterpolateAtCentroid:
2796 libCall = spv::GLSLstd450InterpolateAtCentroid;
2797 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002798 case glslang::EOpAny:
2799 unaryOp = spv::OpAny;
2800 break;
2801 case glslang::EOpAll:
2802 unaryOp = spv::OpAll;
2803 break;
2804
2805 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002806 if (isFloat)
2807 libCall = spv::GLSLstd450FAbs;
2808 else
2809 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002810 break;
2811 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002812 if (isFloat)
2813 libCall = spv::GLSLstd450FSign;
2814 else
2815 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002816 break;
2817
John Kessenichfc51d282015-08-19 13:34:18 -06002818 case glslang::EOpAtomicCounterIncrement:
2819 case glslang::EOpAtomicCounterDecrement:
2820 case glslang::EOpAtomicCounter:
2821 {
2822 // Handle all of the atomics in one place, in createAtomicOperation()
2823 std::vector<spv::Id> operands;
2824 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002825 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002826 }
2827
2828 case glslang::EOpImageLoad:
2829 unaryOp = spv::OpImageRead;
2830 break;
2831
2832 case glslang::EOpBitFieldReverse:
2833 unaryOp = spv::OpBitReverse;
2834 break;
2835 case glslang::EOpBitCount:
2836 unaryOp = spv::OpBitCount;
2837 break;
2838 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002839 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002840 break;
2841 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002842 if (isUnsigned)
2843 libCall = spv::GLSLstd450FindUMsb;
2844 else
2845 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002846 break;
2847
John Kessenich140f3df2015-06-26 16:58:36 -06002848 default:
2849 return 0;
2850 }
2851
2852 spv::Id id;
2853 if (libCall >= 0) {
2854 std::vector<spv::Id> args;
2855 args.push_back(operand);
2856 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2857 } else
2858 id = builder.createUnaryOp(unaryOp, typeId, operand);
2859
2860 builder.setPrecision(id, precision);
2861
2862 return id;
2863}
2864
2865spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2866{
2867 spv::Op convOp = spv::OpNop;
2868 spv::Id zero = 0;
2869 spv::Id one = 0;
2870
2871 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2872
2873 switch (op) {
2874 case glslang::EOpConvIntToBool:
2875 case glslang::EOpConvUintToBool:
2876 zero = builder.makeUintConstant(0);
2877 zero = makeSmearedConstant(zero, vectorSize);
2878 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2879
2880 case glslang::EOpConvFloatToBool:
2881 zero = builder.makeFloatConstant(0.0F);
2882 zero = makeSmearedConstant(zero, vectorSize);
2883 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2884
2885 case glslang::EOpConvDoubleToBool:
2886 zero = builder.makeDoubleConstant(0.0);
2887 zero = makeSmearedConstant(zero, vectorSize);
2888 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2889
2890 case glslang::EOpConvBoolToFloat:
2891 convOp = spv::OpSelect;
2892 zero = builder.makeFloatConstant(0.0);
2893 one = builder.makeFloatConstant(1.0);
2894 break;
2895 case glslang::EOpConvBoolToDouble:
2896 convOp = spv::OpSelect;
2897 zero = builder.makeDoubleConstant(0.0);
2898 one = builder.makeDoubleConstant(1.0);
2899 break;
2900 case glslang::EOpConvBoolToInt:
2901 zero = builder.makeIntConstant(0);
2902 one = builder.makeIntConstant(1);
2903 convOp = spv::OpSelect;
2904 break;
2905 case glslang::EOpConvBoolToUint:
2906 zero = builder.makeUintConstant(0);
2907 one = builder.makeUintConstant(1);
2908 convOp = spv::OpSelect;
2909 break;
2910
2911 case glslang::EOpConvIntToFloat:
2912 case glslang::EOpConvIntToDouble:
2913 convOp = spv::OpConvertSToF;
2914 break;
2915
2916 case glslang::EOpConvUintToFloat:
2917 case glslang::EOpConvUintToDouble:
2918 convOp = spv::OpConvertUToF;
2919 break;
2920
2921 case glslang::EOpConvDoubleToFloat:
2922 case glslang::EOpConvFloatToDouble:
2923 convOp = spv::OpFConvert;
2924 break;
2925
2926 case glslang::EOpConvFloatToInt:
2927 case glslang::EOpConvDoubleToInt:
2928 convOp = spv::OpConvertFToS;
2929 break;
2930
2931 case glslang::EOpConvUintToInt:
2932 case glslang::EOpConvIntToUint:
2933 convOp = spv::OpBitcast;
2934 break;
2935
2936 case glslang::EOpConvFloatToUint:
2937 case glslang::EOpConvDoubleToUint:
2938 convOp = spv::OpConvertFToU;
2939 break;
2940 default:
2941 break;
2942 }
2943
2944 spv::Id result = 0;
2945 if (convOp == spv::OpNop)
2946 return result;
2947
2948 if (convOp == spv::OpSelect) {
2949 zero = makeSmearedConstant(zero, vectorSize);
2950 one = makeSmearedConstant(one, vectorSize);
2951 result = builder.createTriOp(convOp, destType, operand, one, zero);
2952 } else
2953 result = builder.createUnaryOp(convOp, destType, operand);
2954
2955 builder.setPrecision(result, precision);
2956
2957 return result;
2958}
2959
2960spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2961{
2962 if (vectorSize == 0)
2963 return constant;
2964
2965 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2966 std::vector<spv::Id> components;
2967 for (int c = 0; c < vectorSize; ++c)
2968 components.push_back(constant);
2969 return builder.makeCompositeConstant(vectorTypeId, components);
2970}
2971
John Kessenich426394d2015-07-23 10:22:48 -06002972// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002973spv::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 -06002974{
2975 spv::Op opCode = spv::OpNop;
2976
2977 switch (op) {
2978 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002979 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002980 opCode = spv::OpAtomicIAdd;
2981 break;
2982 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002983 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002984 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002985 break;
2986 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002987 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002988 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002989 break;
2990 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002991 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002992 opCode = spv::OpAtomicAnd;
2993 break;
2994 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002995 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002996 opCode = spv::OpAtomicOr;
2997 break;
2998 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002999 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003000 opCode = spv::OpAtomicXor;
3001 break;
3002 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003003 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003004 opCode = spv::OpAtomicExchange;
3005 break;
3006 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003007 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003008 opCode = spv::OpAtomicCompareExchange;
3009 break;
3010 case glslang::EOpAtomicCounterIncrement:
3011 opCode = spv::OpAtomicIIncrement;
3012 break;
3013 case glslang::EOpAtomicCounterDecrement:
3014 opCode = spv::OpAtomicIDecrement;
3015 break;
3016 case glslang::EOpAtomicCounter:
3017 opCode = spv::OpAtomicLoad;
3018 break;
3019 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003020 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003021 break;
3022 }
3023
3024 // Sort out the operands
3025 // - mapping from glslang -> SPV
3026 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003027 // - compare-exchange swaps the value and comparator
3028 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003029 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3030 auto opIt = operands.begin(); // walk the glslang operands
3031 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003032 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3033 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3034 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003035 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3036 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003037 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003038 spvAtomicOperands.push_back(*(opIt + 1));
3039 spvAtomicOperands.push_back(*opIt);
3040 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003041 }
John Kessenich426394d2015-07-23 10:22:48 -06003042
John Kessenich3e60a6f2015-09-14 22:45:16 -06003043 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003044 for (; opIt != operands.end(); ++opIt)
3045 spvAtomicOperands.push_back(*opIt);
3046
3047 return builder.createOp(opCode, typeId, spvAtomicOperands);
3048}
3049
John Kessenich5e4b1242015-08-06 22:53:06 -06003050spv::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 -06003051{
John Kessenich5e4b1242015-08-06 22:53:06 -06003052 bool isUnsigned = typeProxy == glslang::EbtUint;
3053 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3054
John Kessenich140f3df2015-06-26 16:58:36 -06003055 spv::Op opCode = spv::OpNop;
3056 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003057 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003058 spv::Id typeId0 = 0;
3059 if (consumedOperands > 0)
3060 typeId0 = builder.getTypeId(operands[0]);
3061 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003062
3063 switch (op) {
3064 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003065 if (isFloat)
3066 libCall = spv::GLSLstd450FMin;
3067 else if (isUnsigned)
3068 libCall = spv::GLSLstd450UMin;
3069 else
3070 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003071 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003072 break;
3073 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003074 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003075 break;
3076 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003077 if (isFloat)
3078 libCall = spv::GLSLstd450FMax;
3079 else if (isUnsigned)
3080 libCall = spv::GLSLstd450UMax;
3081 else
3082 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003083 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003084 break;
3085 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003086 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003087 break;
3088 case glslang::EOpDot:
3089 opCode = spv::OpDot;
3090 break;
3091 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003092 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 break;
3094
3095 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003096 if (isFloat)
3097 libCall = spv::GLSLstd450FClamp;
3098 else if (isUnsigned)
3099 libCall = spv::GLSLstd450UClamp;
3100 else
3101 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003102 builder.promoteScalar(precision, operands.front(), operands[1]);
3103 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003104 break;
3105 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003106 if (isFloat)
3107 libCall = spv::GLSLstd450FMix;
3108 else
3109 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003110 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003111 break;
3112 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003113 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003114 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003115 break;
3116 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003117 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003118 builder.promoteScalar(precision, operands[0], operands[2]);
3119 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003120 break;
3121
3122 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003124 break;
3125 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003126 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 break;
3128 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003129 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
3131 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003133 break;
3134 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003135 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003136 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003137 case glslang::EOpInterpolateAtSample:
3138 libCall = spv::GLSLstd450InterpolateAtSample;
3139 break;
3140 case glslang::EOpInterpolateAtOffset:
3141 libCall = spv::GLSLstd450InterpolateAtOffset;
3142 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003143 case glslang::EOpAddCarry:
3144 opCode = spv::OpIAddCarry;
3145 typeId = builder.makeStructResultType(typeId0, typeId0);
3146 consumedOperands = 2;
3147 break;
3148 case glslang::EOpSubBorrow:
3149 opCode = spv::OpISubBorrow;
3150 typeId = builder.makeStructResultType(typeId0, typeId0);
3151 consumedOperands = 2;
3152 break;
3153 case glslang::EOpUMulExtended:
3154 opCode = spv::OpUMulExtended;
3155 typeId = builder.makeStructResultType(typeId0, typeId0);
3156 consumedOperands = 2;
3157 break;
3158 case glslang::EOpIMulExtended:
3159 opCode = spv::OpSMulExtended;
3160 typeId = builder.makeStructResultType(typeId0, typeId0);
3161 consumedOperands = 2;
3162 break;
3163 case glslang::EOpBitfieldExtract:
3164 if (isUnsigned)
3165 opCode = spv::OpBitFieldUExtract;
3166 else
3167 opCode = spv::OpBitFieldSExtract;
3168 break;
3169 case glslang::EOpBitfieldInsert:
3170 opCode = spv::OpBitFieldInsert;
3171 break;
3172
3173 case glslang::EOpFma:
3174 libCall = spv::GLSLstd450Fma;
3175 break;
3176 case glslang::EOpFrexp:
3177 libCall = spv::GLSLstd450FrexpStruct;
3178 if (builder.getNumComponents(operands[0]) == 1)
3179 frexpIntType = builder.makeIntegerType(32, true);
3180 else
3181 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3182 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3183 consumedOperands = 1;
3184 break;
3185 case glslang::EOpLdexp:
3186 libCall = spv::GLSLstd450Ldexp;
3187 break;
3188
John Kessenich140f3df2015-06-26 16:58:36 -06003189 default:
3190 return 0;
3191 }
3192
3193 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003194 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003195 // Use an extended instruction from the standard library.
3196 // Construct the call arguments, without modifying the original operands vector.
3197 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3198 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
3199 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003200 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003201 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003202 case 0:
3203 // should all be handled by visitAggregate and createNoArgOperation
3204 assert(0);
3205 return 0;
3206 case 1:
3207 // should all be handled by createUnaryOperation
3208 assert(0);
3209 return 0;
3210 case 2:
3211 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3212 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003213 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003214 // anything 3 or over doesn't have l-value operands, so all should be consumed
3215 assert(consumedOperands == operands.size());
3216 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003217 break;
3218 }
3219 }
3220
John Kessenich55e7d112015-11-15 21:33:39 -07003221 // Decode the return types that were structures
3222 switch (op) {
3223 case glslang::EOpAddCarry:
3224 case glslang::EOpSubBorrow:
3225 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3226 id = builder.createCompositeExtract(id, typeId0, 0);
3227 break;
3228 case glslang::EOpUMulExtended:
3229 case glslang::EOpIMulExtended:
3230 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3231 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3232 break;
3233 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003234 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003235 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3236 id = builder.createCompositeExtract(id, typeId0, 0);
3237 break;
3238 default:
3239 break;
3240 }
3241
John Kessenich140f3df2015-06-26 16:58:36 -06003242 builder.setPrecision(id, precision);
3243
3244 return id;
3245}
3246
3247// Intrinsics with no arguments, no return value, and no precision.
3248spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3249{
3250 // TODO: get the barrier operands correct
3251
3252 switch (op) {
3253 case glslang::EOpEmitVertex:
3254 builder.createNoResultOp(spv::OpEmitVertex);
3255 return 0;
3256 case glslang::EOpEndPrimitive:
3257 builder.createNoResultOp(spv::OpEndPrimitive);
3258 return 0;
3259 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003260 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3261 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003262 return 0;
3263 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003264 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003265 return 0;
3266 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003267 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003268 return 0;
3269 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003270 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003271 return 0;
3272 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003273 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003274 return 0;
3275 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003276 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003277 return 0;
3278 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003279 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003280 return 0;
3281 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003282 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003283 return 0;
3284 }
3285}
3286
3287spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3288{
John Kessenich2f273362015-07-18 22:34:27 -06003289 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003290 spv::Id id;
3291 if (symbolValues.end() != iter) {
3292 id = iter->second;
3293 return id;
3294 }
3295
3296 // it was not found, create it
3297 id = createSpvVariable(symbol);
3298 symbolValues[symbol->getId()] = id;
3299
3300 if (! symbol->getType().isStruct()) {
3301 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003302 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003303 if (symbol->getQualifier().hasLocation())
3304 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3305 if (symbol->getQualifier().hasIndex())
3306 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3307 if (symbol->getQualifier().hasComponent())
3308 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3309 if (glslangIntermediate->getXfbMode()) {
3310 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003311 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003312 if (symbol->getQualifier().hasXfbBuffer())
3313 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3314 if (symbol->getQualifier().hasXfbOffset())
3315 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3316 }
3317 }
3318
John Kesseniche0b6cad2015-12-24 10:30:13 -07003319 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003320 if (symbol->getQualifier().hasStream())
3321 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3322 if (symbol->getQualifier().hasSet())
3323 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3324 if (symbol->getQualifier().hasBinding())
3325 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3326 if (glslangIntermediate->getXfbMode()) {
3327 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003328 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003329 if (symbol->getQualifier().hasXfbBuffer())
3330 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3331 }
3332
3333 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003334 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003335 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003336 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003337
John Kessenich140f3df2015-06-26 16:58:36 -06003338 return id;
3339}
3340
John Kessenich55e7d112015-11-15 21:33:39 -07003341// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003342void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3343{
3344 if (dec != spv::BadValue)
3345 builder.addDecoration(id, dec);
3346}
3347
John Kessenich55e7d112015-11-15 21:33:39 -07003348// If 'dec' is valid, add a one-operand decoration to an object
3349void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3350{
3351 if (dec != spv::BadValue)
3352 builder.addDecoration(id, dec, value);
3353}
3354
3355// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003356void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3357{
3358 if (dec != spv::BadValue)
3359 builder.addMemberDecoration(id, (unsigned)member, dec);
3360}
3361
John Kessenich55e7d112015-11-15 21:33:39 -07003362// Make a full tree of instructions to build a SPIR-V specialization constant,
3363// or regularly constant if possible.
3364//
3365// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3366//
3367// Recursively walk the nodes. The nodes form a tree whose leaves are
3368// regular constants, which themselves are trees that createSpvConstant()
3369// recursively walks. So, this function walks the "top" of the tree:
3370// - emit specialization constant-building instructions for specConstant
3371// - when running into a non-spec-constant, switch to createSpvConstant()
3372spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3373{
3374 assert(node.getQualifier().storage == glslang::EvqConst);
3375
3376 // hand off to the non-spec-constant path
3377 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3378 int nextConst = 0;
3379 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3380}
3381
John Kessenich140f3df2015-06-26 16:58:36 -06003382// Use 'consts' as the flattened glslang source of scalar constants to recursively
3383// build the aggregate SPIR-V constant.
3384//
3385// If there are not enough elements present in 'consts', 0 will be substituted;
3386// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3387//
John Kessenich55e7d112015-11-15 21:33:39 -07003388spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003389{
3390 // vector of constants for SPIR-V
3391 std::vector<spv::Id> spvConsts;
3392
3393 // Type is used for struct and array constants
3394 spv::Id typeId = convertGlslangToSpvType(glslangType);
3395
3396 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003397 glslang::TType elementType(glslangType, 0);
3398 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003399 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003400 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003401 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003402 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003403 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003404 } else if (glslangType.getStruct()) {
3405 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3406 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003407 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003408 } else if (glslangType.isVector()) {
3409 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3410 bool zero = nextConst >= consts.size();
3411 switch (glslangType.getBasicType()) {
3412 case glslang::EbtInt:
3413 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3414 break;
3415 case glslang::EbtUint:
3416 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3417 break;
3418 case glslang::EbtFloat:
3419 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3420 break;
3421 case glslang::EbtDouble:
3422 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3423 break;
3424 case glslang::EbtBool:
3425 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3426 break;
3427 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003428 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003429 break;
3430 }
3431 ++nextConst;
3432 }
3433 } else {
3434 // we have a non-aggregate (scalar) constant
3435 bool zero = nextConst >= consts.size();
3436 spv::Id scalar = 0;
3437 switch (glslangType.getBasicType()) {
3438 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003439 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003440 break;
3441 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003442 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003443 break;
3444 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003445 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003446 break;
3447 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003448 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003449 break;
3450 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003451 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003452 break;
3453 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003454 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003455 break;
3456 }
3457 ++nextConst;
3458 return scalar;
3459 }
3460
3461 return builder.makeCompositeConstant(typeId, spvConsts);
3462}
3463
John Kessenich7c1aa102015-10-15 13:29:11 -06003464// Return true if the node is a constant or symbol whose reading has no
3465// non-trivial observable cost or effect.
3466bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3467{
3468 // don't know what this is
3469 if (node == nullptr)
3470 return false;
3471
3472 // a constant is safe
3473 if (node->getAsConstantUnion() != nullptr)
3474 return true;
3475
3476 // not a symbol means non-trivial
3477 if (node->getAsSymbolNode() == nullptr)
3478 return false;
3479
3480 // a symbol, depends on what's being read
3481 switch (node->getType().getQualifier().storage) {
3482 case glslang::EvqTemporary:
3483 case glslang::EvqGlobal:
3484 case glslang::EvqIn:
3485 case glslang::EvqInOut:
3486 case glslang::EvqConst:
3487 case glslang::EvqConstReadOnly:
3488 case glslang::EvqUniform:
3489 return true;
3490 default:
3491 return false;
3492 }
3493}
3494
3495// A node is trivial if it is a single operation with no side effects.
3496// Error on the side of saying non-trivial.
3497// Return true if trivial.
3498bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3499{
3500 if (node == nullptr)
3501 return false;
3502
3503 // symbols and constants are trivial
3504 if (isTrivialLeaf(node))
3505 return true;
3506
3507 // otherwise, it needs to be a simple operation or one or two leaf nodes
3508
3509 // not a simple operation
3510 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3511 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3512 if (binaryNode == nullptr && unaryNode == nullptr)
3513 return false;
3514
3515 // not on leaf nodes
3516 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3517 return false;
3518
3519 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3520 return false;
3521 }
3522
3523 switch (node->getAsOperator()->getOp()) {
3524 case glslang::EOpLogicalNot:
3525 case glslang::EOpConvIntToBool:
3526 case glslang::EOpConvUintToBool:
3527 case glslang::EOpConvFloatToBool:
3528 case glslang::EOpConvDoubleToBool:
3529 case glslang::EOpEqual:
3530 case glslang::EOpNotEqual:
3531 case glslang::EOpLessThan:
3532 case glslang::EOpGreaterThan:
3533 case glslang::EOpLessThanEqual:
3534 case glslang::EOpGreaterThanEqual:
3535 case glslang::EOpIndexDirect:
3536 case glslang::EOpIndexDirectStruct:
3537 case glslang::EOpLogicalXor:
3538 case glslang::EOpAny:
3539 case glslang::EOpAll:
3540 return true;
3541 default:
3542 return false;
3543 }
3544}
3545
3546// Emit short-circuiting code, where 'right' is never evaluated unless
3547// the left side is true (for &&) or false (for ||).
3548spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3549{
3550 spv::Id boolTypeId = builder.makeBoolType();
3551
3552 // emit left operand
3553 builder.clearAccessChain();
3554 left.traverse(this);
3555 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3556
3557 // Operands to accumulate OpPhi operands
3558 std::vector<spv::Id> phiOperands;
3559 // accumulate left operand's phi information
3560 phiOperands.push_back(leftId);
3561 phiOperands.push_back(builder.getBuildPoint()->getId());
3562
3563 // Make the two kinds of operation symmetric with a "!"
3564 // || => emit "if (! left) result = right"
3565 // && => emit "if ( left) result = right"
3566 //
3567 // TODO: this runtime "not" for || could be avoided by adding functionality
3568 // to 'builder' to have an "else" without an "then"
3569 if (op == glslang::EOpLogicalOr)
3570 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3571
3572 // make an "if" based on the left value
3573 spv::Builder::If ifBuilder(leftId, builder);
3574
3575 // emit right operand as the "then" part of the "if"
3576 builder.clearAccessChain();
3577 right.traverse(this);
3578 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3579
3580 // accumulate left operand's phi information
3581 phiOperands.push_back(rightId);
3582 phiOperands.push_back(builder.getBuildPoint()->getId());
3583
3584 // finish the "if"
3585 ifBuilder.makeEndIf();
3586
3587 // phi together the two results
3588 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3589}
3590
John Kessenich140f3df2015-06-26 16:58:36 -06003591}; // end anonymous namespace
3592
3593namespace glslang {
3594
John Kessenich68d78fd2015-07-12 19:28:10 -06003595void GetSpirvVersion(std::string& version)
3596{
John Kessenich9e55f632015-07-15 10:03:39 -06003597 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003598 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003599 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003600 version = buf;
3601}
3602
John Kessenich140f3df2015-06-26 16:58:36 -06003603// Write SPIR-V out to a binary file
3604void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3605{
3606 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003607 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003608 for (int i = 0; i < (int)spirv.size(); ++i) {
3609 unsigned int word = spirv[i];
3610 out.write((const char*)&word, 4);
3611 }
3612 out.close();
3613}
3614
3615//
3616// Set up the glslang traversal
3617//
3618void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3619{
3620 TIntermNode* root = intermediate.getTreeRoot();
3621
3622 if (root == 0)
3623 return;
3624
3625 glslang::GetThreadPoolAllocator().push();
3626
3627 TGlslangToSpvTraverser it(&intermediate);
3628
3629 root->traverse(&it);
3630
3631 it.dumpSpv(spirv);
3632
3633 glslang::GetThreadPoolAllocator().pop();
3634}
3635
3636}; // end namespace glslang