blob: 654fe87486ae41c490dec1401991c359658d5181 [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
147 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
148};
149
150//
151// Helper functions for translating glslang representations to SPIR-V enumerants.
152//
153
154// Translate glslang profile to SPIR-V source language.
155spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
156{
157 switch (profile) {
158 case ENoProfile:
159 case ECoreProfile:
160 case ECompatibilityProfile:
161 return spv::SourceLanguageGLSL;
162 case EEsProfile:
163 return spv::SourceLanguageESSL;
164 default:
165 return spv::SourceLanguageUnknown;
166 }
167}
168
169// Translate glslang language (stage) to SPIR-V execution model.
170spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
171{
172 switch (stage) {
173 case EShLangVertex: return spv::ExecutionModelVertex;
174 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
175 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
176 case EShLangGeometry: return spv::ExecutionModelGeometry;
177 case EShLangFragment: return spv::ExecutionModelFragment;
178 case EShLangCompute: return spv::ExecutionModelGLCompute;
179 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700180 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 return spv::ExecutionModelFragment;
182 }
183}
184
185// Translate glslang type to SPIR-V storage class.
186spv::StorageClass TranslateStorageClass(const glslang::TType& type)
187{
188 if (type.getQualifier().isPipeInput())
189 return spv::StorageClassInput;
190 else if (type.getQualifier().isPipeOutput())
191 return spv::StorageClassOutput;
192 else if (type.getQualifier().isUniformOrBuffer()) {
193 if (type.getBasicType() == glslang::EbtBlock)
194 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800195 else if (type.getBasicType() == glslang::EbtAtomicUint)
196 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600197 else
198 return spv::StorageClassUniformConstant;
199 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
200 } else {
201 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700202 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
203 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600204 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
205 case glslang::EvqTemporary: return spv::StorageClassFunction;
206 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700207 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600208 return spv::StorageClassFunction;
209 }
210 }
211}
212
213// Translate glslang sampler type to SPIR-V dimensionality.
214spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
215{
216 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700217 case glslang::Esd1D: return spv::Dim1D;
218 case glslang::Esd2D: return spv::Dim2D;
219 case glslang::Esd3D: return spv::Dim3D;
220 case glslang::EsdCube: return spv::DimCube;
221 case glslang::EsdRect: return spv::DimRect;
222 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600223 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700224 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600225 return spv::Dim2D;
226 }
227}
228
229// Translate glslang type to SPIR-V precision decorations.
230spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
231{
232 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700233 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600234 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
235 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 default:
237 return spv::NoPrecision;
238 }
239}
240
241// Translate glslang type to SPIR-V block decorations.
242spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
243{
244 if (type.getBasicType() == glslang::EbtBlock) {
245 switch (type.getQualifier().storage) {
246 case glslang::EvqUniform: return spv::DecorationBlock;
247 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
248 case glslang::EvqVaryingIn: return spv::DecorationBlock;
249 case glslang::EvqVaryingOut: return spv::DecorationBlock;
250 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700251 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600252 break;
253 }
254 }
255
256 return (spv::Decoration)spv::BadValue;
257}
258
259// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700260spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600261{
262 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700263 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600264 case glslang::ElmRowMajor:
265 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700266 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600267 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700268 default:
269 // opaque layouts don't need a majorness
270 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600271 }
272 } else {
273 switch (type.getBasicType()) {
274 default:
275 return (spv::Decoration)spv::BadValue;
276 break;
277 case glslang::EbtBlock:
278 switch (type.getQualifier().storage) {
279 case glslang::EvqUniform:
280 case glslang::EvqBuffer:
281 switch (type.getQualifier().layoutPacking) {
282 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600283 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
284 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600285 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 }
287 case glslang::EvqVaryingIn:
288 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return (spv::Decoration)spv::BadValue;
291 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700292 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600293 return (spv::Decoration)spv::BadValue;
294 }
295 }
296 }
297}
298
299// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700300// Returns spv::Decoration(spv::BadValue) when no decoration
301// should be applied.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700302spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600303{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700304 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700305 // Smooth decoration doesn't exist in SPIR-V 1.0
306 return (spv::Decoration)spv::BadValue;
307 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700308 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700309 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700310 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600311 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700312 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600313 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700314 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return spv::DecorationCentroid;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700316 else if (qualifier.sample)
John Kessenich140f3df2015-06-26 16:58:36 -0600317 return spv::DecorationSample;
318 else
319 return (spv::Decoration)spv::BadValue;
320}
321
322// If glslang type is invaraiant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700323spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600324{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700325 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::DecorationInvariant;
327 else
328 return (spv::Decoration)spv::BadValue;
329}
330
331// Translate glslang built-in variable to SPIR-V built in decoration.
332spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
333{
334 switch (builtIn) {
335 case glslang::EbvPosition: return spv::BuiltInPosition;
336 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600337 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
338 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
339 case glslang::EbvVertexId: return spv::BuiltInVertexId;
340 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600341 case glslang::EbvBaseVertex:
342 case glslang::EbvBaseInstance:
343 case glslang::EbvDrawId:
344 // TODO: Add SPIR-V builtin ID.
345 spv::MissingFunctionality("Draw parameters");
346 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
348 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
349 case glslang::EbvLayer: return spv::BuiltInLayer;
350 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
351 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
352 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
353 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
354 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
355 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
356 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
357 case glslang::EbvFace: return spv::BuiltInFrontFacing;
358 case glslang::EbvSampleId: return spv::BuiltInSampleId;
359 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
360 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600361 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
362 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
363 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
364 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
365 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
366 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
367 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
368 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
369 default: return (spv::BuiltIn)spv::BadValue;
370 }
371}
372
Rex Xufc618912015-09-09 16:42:49 +0800373// Translate glslang image layout format to SPIR-V image format.
374spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
375{
376 assert(type.getBasicType() == glslang::EbtSampler);
377
378 switch (type.getQualifier().layoutFormat) {
379 case glslang::ElfNone: return spv::ImageFormatUnknown;
380 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
381 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
382 case glslang::ElfR32f: return spv::ImageFormatR32f;
383 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
384 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
385 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
386 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
387 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
388 case glslang::ElfR16f: return spv::ImageFormatR16f;
389 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
390 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
391 case glslang::ElfRg16: return spv::ImageFormatRg16;
392 case glslang::ElfRg8: return spv::ImageFormatRg8;
393 case glslang::ElfR16: return spv::ImageFormatR16;
394 case glslang::ElfR8: return spv::ImageFormatR8;
395 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
396 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
397 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
398 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
399 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
400 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
401 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
402 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
403 case glslang::ElfR32i: return spv::ImageFormatR32i;
404 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
405 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
406 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
407 case glslang::ElfR16i: return spv::ImageFormatR16i;
408 case glslang::ElfR8i: return spv::ImageFormatR8i;
409 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
410 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
411 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
412 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
413 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
414 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
415 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
416 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
417 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
418 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
419 default: return (spv::ImageFormat)spv::BadValue;
420 }
421}
422
John Kesseniche0b6cad2015-12-24 10:30:13 -0700423void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
424{
425 if (child.layoutMatrix == glslang::ElmNone)
426 child.layoutMatrix = parent.layoutMatrix;
427
428 if (parent.invariant)
429 child.invariant = true;
430 if (parent.nopersp)
431 child.nopersp = true;
432 if (parent.flat)
433 child.flat = true;
434 if (parent.centroid)
435 child.centroid = true;
436 if (parent.patch)
437 child.patch = true;
438 if (parent.sample)
439 child.sample = true;
440}
441
442bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
443{
444 // This should list qualifiers that simultaneous satisify:
445 // - struct members can inherit from a struct declaration
446 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
447 // - are not part of the offset/st430/etc or row/column-major layout
448 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample;
449}
450
John Kessenich140f3df2015-06-26 16:58:36 -0600451//
452// Implement the TGlslangToSpvTraverser class.
453//
454
455TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
456 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700457 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600458 inMain(false), mainTerminated(false), linkageOnly(false),
459 glslangIntermediate(glslangIntermediate)
460{
461 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
462
463 builder.clearAccessChain();
464 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
465 stdBuiltins = builder.import("GLSL.std.450");
466 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
467 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700468 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600469
470 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600471 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
472 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600473 builder.addSourceExtension(it->c_str());
474
475 // Add the top-level modes for this shader.
476
477 if (glslangIntermediate->getXfbMode())
478 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
479
480 unsigned int mode;
481 switch (glslangIntermediate->getStage()) {
482 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600483 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600484 break;
485
486 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600487 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600488 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
489 break;
490
491 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600492 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600493 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700494 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
495 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
496 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600497 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600498 }
499 if (mode != spv::BadValue)
500 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
501
John Kesseniche6903322015-10-13 16:29:02 -0600502 switch (glslangIntermediate->getVertexSpacing()) {
503 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
504 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
505 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
506 default: mode = spv::BadValue; break;
507 }
508 if (mode != spv::BadValue)
509 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
510
511 switch (glslangIntermediate->getVertexOrder()) {
512 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
513 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
514 default: mode = spv::BadValue; break;
515 }
516 if (mode != spv::BadValue)
517 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
518
519 if (glslangIntermediate->getPointMode())
520 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600521 break;
522
523 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600524 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600525 switch (glslangIntermediate->getInputPrimitive()) {
526 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
527 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
528 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700529 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
531 default: mode = spv::BadValue; break;
532 }
533 if (mode != spv::BadValue)
534 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600535
John Kessenich140f3df2015-06-26 16:58:36 -0600536 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
537
538 switch (glslangIntermediate->getOutputPrimitive()) {
539 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
540 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
541 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
542 default: mode = spv::BadValue; break;
543 }
544 if (mode != spv::BadValue)
545 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
546 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
547 break;
548
549 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600550 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600551 if (glslangIntermediate->getPixelCenterInteger())
552 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600553
John Kessenich140f3df2015-06-26 16:58:36 -0600554 if (glslangIntermediate->getOriginUpperLeft())
555 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600556 else
557 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600558
559 if (glslangIntermediate->getEarlyFragmentTests())
560 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
561
562 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600563 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
564 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
565 default: mode = spv::BadValue; break;
566 }
567 if (mode != spv::BadValue)
568 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
569
570 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
571 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600572 break;
573
574 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600575 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600576 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
577 glslangIntermediate->getLocalSize(1),
578 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600579 break;
580
581 default:
582 break;
583 }
584
585}
586
John Kessenich7ba63412015-12-20 17:37:07 -0700587// Finish everything and dump
588void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
589{
590 // finish off the entry-point SPV instruction by adding the Input/Output <id>
591 for (auto it : iOSet)
592 entryPoint->addIdOperand(it);
593
594 builder.dump(out);
595}
596
John Kessenich140f3df2015-06-26 16:58:36 -0600597TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
598{
599 if (! mainTerminated) {
600 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
601 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600602 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600603 }
604}
605
606//
607// Implement the traversal functions.
608//
609// Return true from interior nodes to have the external traversal
610// continue on to children. Return false if children were
611// already processed.
612//
613
614//
615// Symbols can turn into
616// - uniform/input reads
617// - output writes
618// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
619// - something simple that degenerates into the last bullet
620//
621void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
622{
623 // getSymbolId() will set up all the IO decorations on the first call.
624 // Formal function parameters were mapped during makeFunctions().
625 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700626
627 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
628 if (builder.isPointer(id)) {
629 spv::StorageClass sc = builder.getStorageClass(id);
630 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
631 iOSet.insert(id);
632 }
633
634 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600635 if (! linkageOnly) {
636 // Prepare to generate code for the access
637
638 // L-value chains will be computed left to right. We're on the symbol now,
639 // which is the left-most part of the access chain, so now is "clear" time,
640 // followed by setting the base.
641 builder.clearAccessChain();
642
643 // For now, we consider all user variables as being in memory, so they are pointers,
644 // except for "const in" arguments to a function, which are an intermediate object.
645 // See comments in handleUserFunctionCall().
646 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
647 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
648 builder.setAccessChainRValue(id);
649 else
650 builder.setAccessChainLValue(id);
651 }
652}
653
654bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
655{
656 // First, handle special cases
657 switch (node->getOp()) {
658 case glslang::EOpAssign:
659 case glslang::EOpAddAssign:
660 case glslang::EOpSubAssign:
661 case glslang::EOpMulAssign:
662 case glslang::EOpVectorTimesMatrixAssign:
663 case glslang::EOpVectorTimesScalarAssign:
664 case glslang::EOpMatrixTimesScalarAssign:
665 case glslang::EOpMatrixTimesMatrixAssign:
666 case glslang::EOpDivAssign:
667 case glslang::EOpModAssign:
668 case glslang::EOpAndAssign:
669 case glslang::EOpInclusiveOrAssign:
670 case glslang::EOpExclusiveOrAssign:
671 case glslang::EOpLeftShiftAssign:
672 case glslang::EOpRightShiftAssign:
673 // A bin-op assign "a += b" means the same thing as "a = a + b"
674 // where a is evaluated before b. For a simple assignment, GLSL
675 // says to evaluate the left before the right. So, always, left
676 // node then right node.
677 {
678 // get the left l-value, save it away
679 builder.clearAccessChain();
680 node->getLeft()->traverse(this);
681 spv::Builder::AccessChain lValue = builder.getAccessChain();
682
683 // evaluate the right
684 builder.clearAccessChain();
685 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600686 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600687
688 if (node->getOp() != glslang::EOpAssign) {
689 // the left is also an r-value
690 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600691 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600692
693 // do the operation
694 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
695 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
696 node->getType().getBasicType());
697
698 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700699 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600700 }
701
702 // store the result
703 builder.setAccessChain(lValue);
704 builder.accessChainStore(rValue);
705
706 // assignments are expressions having an rValue after they are evaluated...
707 builder.clearAccessChain();
708 builder.setAccessChainRValue(rValue);
709 }
710 return false;
711 case glslang::EOpIndexDirect:
712 case glslang::EOpIndexDirectStruct:
713 {
714 // Get the left part of the access chain.
715 node->getLeft()->traverse(this);
716
717 // Add the next element in the chain
718
John Kessenich55e7d112015-11-15 21:33:39 -0700719 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600720 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
721 // This may be, e.g., an anonymous block-member selection, which generally need
722 // index remapping due to hidden members in anonymous blocks.
723 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700724 assert(remapper.size() > 0);
725 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600726 }
727
728 if (! node->getLeft()->getType().isArray() &&
729 node->getLeft()->getType().isVector() &&
730 node->getOp() == glslang::EOpIndexDirect) {
731 // This is essentially a hard-coded vector swizzle of size 1,
732 // so short circuit the access-chain stuff with a swizzle.
733 std::vector<unsigned> swizzle;
734 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600735 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600736 } else {
737 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600738 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600739 }
740 }
741 return false;
742 case glslang::EOpIndexIndirect:
743 {
744 // Structure or array or vector indirection.
745 // Will use native SPIR-V access-chain for struct and array indirection;
746 // matrices are arrays of vectors, so will also work for a matrix.
747 // Will use the access chain's 'component' for variable index into a vector.
748
749 // This adapter is building access chains left to right.
750 // Set up the access chain to the left.
751 node->getLeft()->traverse(this);
752
753 // save it so that computing the right side doesn't trash it
754 spv::Builder::AccessChain partial = builder.getAccessChain();
755
756 // compute the next index in the chain
757 builder.clearAccessChain();
758 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600759 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600760
761 // restore the saved access chain
762 builder.setAccessChain(partial);
763
764 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600765 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600766 else
John Kessenichfa668da2015-09-13 14:46:30 -0600767 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600768 }
769 return false;
770 case glslang::EOpVectorSwizzle:
771 {
772 node->getLeft()->traverse(this);
773 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
774 std::vector<unsigned> swizzle;
775 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
776 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600777 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600778 }
779 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600780 case glslang::EOpLogicalOr:
781 case glslang::EOpLogicalAnd:
782 {
783
784 // These may require short circuiting, but can sometimes be done as straight
785 // binary operations. The right operand must be short circuited if it has
786 // side effects, and should probably be if it is complex.
787 if (isTrivial(node->getRight()->getAsTyped()))
788 break; // handle below as a normal binary operation
789 // otherwise, we need to do dynamic short circuiting on the right operand
790 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
791 builder.clearAccessChain();
792 builder.setAccessChainRValue(result);
793 }
794 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600795 default:
796 break;
797 }
798
799 // Assume generic binary op...
800
801 // Get the operands
802 builder.clearAccessChain();
803 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600804 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600805
806 builder.clearAccessChain();
807 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600808 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600809
810 spv::Id result;
811 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
812
813 result = createBinaryOperation(node->getOp(), precision,
814 convertGlslangToSpvType(node->getType()), left, right,
815 node->getLeft()->getType().getBasicType());
816
John Kessenich50e57562015-12-21 21:21:11 -0700817 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600818 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700819 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700820 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600821 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600822 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600823 return false;
824 }
John Kessenich140f3df2015-06-26 16:58:36 -0600825}
826
827bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
828{
John Kessenichfc51d282015-08-19 13:34:18 -0600829 spv::Id result = spv::NoResult;
830
831 // try texturing first
832 result = createImageTextureFunctionCall(node);
833 if (result != spv::NoResult) {
834 builder.clearAccessChain();
835 builder.setAccessChainRValue(result);
836
837 return false; // done with this node
838 }
839
840 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600841
842 if (node->getOp() == glslang::EOpArrayLength) {
843 // Quite special; won't want to evaluate the operand.
844
845 // Normal .length() would have been constant folded by the front-end.
846 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600847 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600848 assert(node->getOperand()->getType().isRuntimeSizedArray());
849 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
850 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600851 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
852 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600853
854 builder.clearAccessChain();
855 builder.setAccessChainRValue(length);
856
857 return false;
858 }
859
John Kessenichfc51d282015-08-19 13:34:18 -0600860 // Start by evaluating the operand
861
John Kessenich140f3df2015-06-26 16:58:36 -0600862 builder.clearAccessChain();
863 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800864
Rex Xufc618912015-09-09 16:42:49 +0800865 spv::Id operand = spv::NoResult;
866
867 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
868 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800869 node->getOp() == glslang::EOpAtomicCounter ||
870 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800871 operand = builder.accessChainGetLValue(); // Special case l-value operands
872 else
Rex Xu30f92582015-09-14 10:38:56 +0800873 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600874
875 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
876
877 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600878 if (! result)
879 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600880
881 // if not, then possibly an operation
882 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700883 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600884
885 if (result) {
886 builder.clearAccessChain();
887 builder.setAccessChainRValue(result);
888
889 return false; // done with this node
890 }
891
892 // it must be a special case, check...
893 switch (node->getOp()) {
894 case glslang::EOpPostIncrement:
895 case glslang::EOpPostDecrement:
896 case glslang::EOpPreIncrement:
897 case glslang::EOpPreDecrement:
898 {
899 // we need the integer value "1" or the floating point "1.0" to add/subtract
900 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
901 builder.makeFloatConstant(1.0F) :
902 builder.makeIntConstant(1);
903 glslang::TOperator op;
904 if (node->getOp() == glslang::EOpPreIncrement ||
905 node->getOp() == glslang::EOpPostIncrement)
906 op = glslang::EOpAdd;
907 else
908 op = glslang::EOpSub;
909
910 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
911 convertGlslangToSpvType(node->getType()), operand, one,
912 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700913 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600914
915 // The result of operation is always stored, but conditionally the
916 // consumed result. The consumed result is always an r-value.
917 builder.accessChainStore(result);
918 builder.clearAccessChain();
919 if (node->getOp() == glslang::EOpPreIncrement ||
920 node->getOp() == glslang::EOpPreDecrement)
921 builder.setAccessChainRValue(result);
922 else
923 builder.setAccessChainRValue(operand);
924 }
925
926 return false;
927
928 case glslang::EOpEmitStreamVertex:
929 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
930 return false;
931 case glslang::EOpEndStreamPrimitive:
932 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
933 return false;
934
935 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700936 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -0700937 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -0600938 }
John Kessenich140f3df2015-06-26 16:58:36 -0600939}
940
941bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
942{
John Kessenichfc51d282015-08-19 13:34:18 -0600943 spv::Id result = spv::NoResult;
944
945 // try texturing
946 result = createImageTextureFunctionCall(node);
947 if (result != spv::NoResult) {
948 builder.clearAccessChain();
949 builder.setAccessChainRValue(result);
950
951 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600952 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800953 // "imageStore" is a special case, which has no result
954 return false;
955 }
John Kessenichfc51d282015-08-19 13:34:18 -0600956
John Kessenich140f3df2015-06-26 16:58:36 -0600957 glslang::TOperator binOp = glslang::EOpNull;
958 bool reduceComparison = true;
959 bool isMatrix = false;
960 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600961 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600962
963 assert(node->getOp());
964
965 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
966
967 switch (node->getOp()) {
968 case glslang::EOpSequence:
969 {
970 if (preVisit)
971 ++sequenceDepth;
972 else
973 --sequenceDepth;
974
975 if (sequenceDepth == 1) {
976 // If this is the parent node of all the functions, we want to see them
977 // early, so all call points have actual SPIR-V functions to reference.
978 // In all cases, still let the traverser visit the children for us.
979 makeFunctions(node->getAsAggregate()->getSequence());
980
981 // Also, we want all globals initializers to go into the entry of main(), before
982 // anything else gets there, so visit out of order, doing them all now.
983 makeGlobalInitializers(node->getAsAggregate()->getSequence());
984
985 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
986 // so do them manually.
987 visitFunctions(node->getAsAggregate()->getSequence());
988
989 return false;
990 }
991
992 return true;
993 }
994 case glslang::EOpLinkerObjects:
995 {
996 if (visit == glslang::EvPreVisit)
997 linkageOnly = true;
998 else
999 linkageOnly = false;
1000
1001 return true;
1002 }
1003 case glslang::EOpComma:
1004 {
1005 // processing from left to right naturally leaves the right-most
1006 // lying around in the access chain
1007 glslang::TIntermSequence& glslangOperands = node->getSequence();
1008 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1009 glslangOperands[i]->traverse(this);
1010
1011 return false;
1012 }
1013 case glslang::EOpFunction:
1014 if (visit == glslang::EvPreVisit) {
1015 if (isShaderEntrypoint(node)) {
1016 inMain = true;
1017 builder.setBuildPoint(shaderEntry->getLastBlock());
1018 } else {
1019 handleFunctionEntry(node);
1020 }
1021 } else {
1022 if (inMain)
1023 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001024 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001025 inMain = false;
1026 }
1027
1028 return true;
1029 case glslang::EOpParameters:
1030 // Parameters will have been consumed by EOpFunction processing, but not
1031 // the body, so we still visited the function node's children, making this
1032 // child redundant.
1033 return false;
1034 case glslang::EOpFunctionCall:
1035 {
1036 if (node->isUserDefined())
1037 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001038 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001039 builder.clearAccessChain();
1040 builder.setAccessChainRValue(result);
1041
1042 return false;
1043 }
1044 case glslang::EOpConstructMat2x2:
1045 case glslang::EOpConstructMat2x3:
1046 case glslang::EOpConstructMat2x4:
1047 case glslang::EOpConstructMat3x2:
1048 case glslang::EOpConstructMat3x3:
1049 case glslang::EOpConstructMat3x4:
1050 case glslang::EOpConstructMat4x2:
1051 case glslang::EOpConstructMat4x3:
1052 case glslang::EOpConstructMat4x4:
1053 case glslang::EOpConstructDMat2x2:
1054 case glslang::EOpConstructDMat2x3:
1055 case glslang::EOpConstructDMat2x4:
1056 case glslang::EOpConstructDMat3x2:
1057 case glslang::EOpConstructDMat3x3:
1058 case glslang::EOpConstructDMat3x4:
1059 case glslang::EOpConstructDMat4x2:
1060 case glslang::EOpConstructDMat4x3:
1061 case glslang::EOpConstructDMat4x4:
1062 isMatrix = true;
1063 // fall through
1064 case glslang::EOpConstructFloat:
1065 case glslang::EOpConstructVec2:
1066 case glslang::EOpConstructVec3:
1067 case glslang::EOpConstructVec4:
1068 case glslang::EOpConstructDouble:
1069 case glslang::EOpConstructDVec2:
1070 case glslang::EOpConstructDVec3:
1071 case glslang::EOpConstructDVec4:
1072 case glslang::EOpConstructBool:
1073 case glslang::EOpConstructBVec2:
1074 case glslang::EOpConstructBVec3:
1075 case glslang::EOpConstructBVec4:
1076 case glslang::EOpConstructInt:
1077 case glslang::EOpConstructIVec2:
1078 case glslang::EOpConstructIVec3:
1079 case glslang::EOpConstructIVec4:
1080 case glslang::EOpConstructUint:
1081 case glslang::EOpConstructUVec2:
1082 case glslang::EOpConstructUVec3:
1083 case glslang::EOpConstructUVec4:
1084 case glslang::EOpConstructStruct:
1085 {
1086 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001087 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001088 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1089 spv::Id constructed;
1090 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1091 std::vector<spv::Id> constituents;
1092 for (int c = 0; c < (int)arguments.size(); ++c)
1093 constituents.push_back(arguments[c]);
1094 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001095 } else if (isMatrix)
1096 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1097 else
1098 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001099
1100 builder.clearAccessChain();
1101 builder.setAccessChainRValue(constructed);
1102
1103 return false;
1104 }
1105
1106 // These six are component-wise compares with component-wise results.
1107 // Forward on to createBinaryOperation(), requesting a vector result.
1108 case glslang::EOpLessThan:
1109 case glslang::EOpGreaterThan:
1110 case glslang::EOpLessThanEqual:
1111 case glslang::EOpGreaterThanEqual:
1112 case glslang::EOpVectorEqual:
1113 case glslang::EOpVectorNotEqual:
1114 {
1115 // Map the operation to a binary
1116 binOp = node->getOp();
1117 reduceComparison = false;
1118 switch (node->getOp()) {
1119 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1120 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1121 default: binOp = node->getOp(); break;
1122 }
1123
1124 break;
1125 }
1126 case glslang::EOpMul:
1127 // compontent-wise matrix multiply
1128 binOp = glslang::EOpMul;
1129 break;
1130 case glslang::EOpOuterProduct:
1131 // two vectors multiplied to make a matrix
1132 binOp = glslang::EOpOuterProduct;
1133 break;
1134 case glslang::EOpDot:
1135 {
1136 // for scalar dot product, use multiply
1137 glslang::TIntermSequence& glslangOperands = node->getSequence();
1138 if (! glslangOperands[0]->getAsTyped()->isVector())
1139 binOp = glslang::EOpMul;
1140 break;
1141 }
1142 case glslang::EOpMod:
1143 // when an aggregate, this is the floating-point mod built-in function,
1144 // which can be emitted by the one in createBinaryOperation()
1145 binOp = glslang::EOpMod;
1146 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001147 case glslang::EOpEmitVertex:
1148 case glslang::EOpEndPrimitive:
1149 case glslang::EOpBarrier:
1150 case glslang::EOpMemoryBarrier:
1151 case glslang::EOpMemoryBarrierAtomicCounter:
1152 case glslang::EOpMemoryBarrierBuffer:
1153 case glslang::EOpMemoryBarrierImage:
1154 case glslang::EOpMemoryBarrierShared:
1155 case glslang::EOpGroupMemoryBarrier:
1156 noReturnValue = true;
1157 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1158 break;
1159
John Kessenich426394d2015-07-23 10:22:48 -06001160 case glslang::EOpAtomicAdd:
1161 case glslang::EOpAtomicMin:
1162 case glslang::EOpAtomicMax:
1163 case glslang::EOpAtomicAnd:
1164 case glslang::EOpAtomicOr:
1165 case glslang::EOpAtomicXor:
1166 case glslang::EOpAtomicExchange:
1167 case glslang::EOpAtomicCompSwap:
1168 atomic = true;
1169 break;
1170
John Kessenich140f3df2015-06-26 16:58:36 -06001171 default:
1172 break;
1173 }
1174
1175 //
1176 // See if it maps to a regular operation.
1177 //
John Kessenich140f3df2015-06-26 16:58:36 -06001178 if (binOp != glslang::EOpNull) {
1179 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1180 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1181 assert(left && right);
1182
1183 builder.clearAccessChain();
1184 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001185 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001186
1187 builder.clearAccessChain();
1188 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001189 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001190
1191 result = createBinaryOperation(binOp, precision,
1192 convertGlslangToSpvType(node->getType()), leftId, rightId,
1193 left->getType().getBasicType(), reduceComparison);
1194
1195 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001196 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 builder.clearAccessChain();
1198 builder.setAccessChainRValue(result);
1199
1200 return false;
1201 }
1202
John Kessenich426394d2015-07-23 10:22:48 -06001203 //
1204 // Create the list of operands.
1205 //
John Kessenich140f3df2015-06-26 16:58:36 -06001206 glslang::TIntermSequence& glslangOperands = node->getSequence();
1207 std::vector<spv::Id> operands;
1208 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1209 builder.clearAccessChain();
1210 glslangOperands[arg]->traverse(this);
1211
1212 // special case l-value operands; there are just a few
1213 bool lvalue = false;
1214 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001215 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001216 case glslang::EOpModf:
1217 if (arg == 1)
1218 lvalue = true;
1219 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001220 case glslang::EOpInterpolateAtSample:
1221 case glslang::EOpInterpolateAtOffset:
1222 if (arg == 0)
1223 lvalue = true;
1224 break;
Rex Xud4782c12015-09-06 16:30:11 +08001225 case glslang::EOpAtomicAdd:
1226 case glslang::EOpAtomicMin:
1227 case glslang::EOpAtomicMax:
1228 case glslang::EOpAtomicAnd:
1229 case glslang::EOpAtomicOr:
1230 case glslang::EOpAtomicXor:
1231 case glslang::EOpAtomicExchange:
1232 case glslang::EOpAtomicCompSwap:
1233 if (arg == 0)
1234 lvalue = true;
1235 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001236 case glslang::EOpAddCarry:
1237 case glslang::EOpSubBorrow:
1238 if (arg == 2)
1239 lvalue = true;
1240 break;
1241 case glslang::EOpUMulExtended:
1242 case glslang::EOpIMulExtended:
1243 if (arg >= 2)
1244 lvalue = true;
1245 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001246 default:
1247 break;
1248 }
1249 if (lvalue)
1250 operands.push_back(builder.accessChainGetLValue());
1251 else
John Kessenichfa668da2015-09-13 14:46:30 -06001252 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001253 }
John Kessenich426394d2015-07-23 10:22:48 -06001254
1255 if (atomic) {
1256 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001257 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001258 } else {
1259 // Pass through to generic operations.
1260 switch (glslangOperands.size()) {
1261 case 0:
1262 result = createNoArgOperation(node->getOp());
1263 break;
1264 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001265 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001266 break;
1267 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001268 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001269 break;
1270 }
John Kessenich140f3df2015-06-26 16:58:36 -06001271 }
1272
1273 if (noReturnValue)
1274 return false;
1275
1276 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001277 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001278 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001279 } else {
1280 builder.clearAccessChain();
1281 builder.setAccessChainRValue(result);
1282 return false;
1283 }
1284}
1285
1286bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1287{
1288 // This path handles both if-then-else and ?:
1289 // The if-then-else has a node type of void, while
1290 // ?: has a non-void node type
1291 spv::Id result = 0;
1292 if (node->getBasicType() != glslang::EbtVoid) {
1293 // don't handle this as just on-the-fly temporaries, because there will be two names
1294 // and better to leave SSA to later passes
1295 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1296 }
1297
1298 // emit the condition before doing anything with selection
1299 node->getCondition()->traverse(this);
1300
1301 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001302 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001303
1304 if (node->getTrueBlock()) {
1305 // emit the "then" statement
1306 node->getTrueBlock()->traverse(this);
1307 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001308 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001309 }
1310
1311 if (node->getFalseBlock()) {
1312 ifBuilder.makeBeginElse();
1313 // emit the "else" statement
1314 node->getFalseBlock()->traverse(this);
1315 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001316 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001317 }
1318
1319 ifBuilder.makeEndIf();
1320
1321 if (result) {
1322 // GLSL only has r-values as the result of a :?, but
1323 // if we have an l-value, that can be more efficient if it will
1324 // become the base of a complex r-value expression, because the
1325 // next layer copies r-values into memory to use the access-chain mechanism
1326 builder.clearAccessChain();
1327 builder.setAccessChainLValue(result);
1328 }
1329
1330 return false;
1331}
1332
1333bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1334{
1335 // emit and get the condition before doing anything with switch
1336 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001337 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 // browse the children to sort out code segments
1340 int defaultSegment = -1;
1341 std::vector<TIntermNode*> codeSegments;
1342 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1343 std::vector<int> caseValues;
1344 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1345 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1346 TIntermNode* child = *c;
1347 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001348 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001349 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001350 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001351 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1352 } else
1353 codeSegments.push_back(child);
1354 }
1355
1356 // handle the case where the last code segment is missing, due to no code
1357 // statements between the last case and the end of the switch statement
1358 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1359 (int)codeSegments.size() == defaultSegment)
1360 codeSegments.push_back(nullptr);
1361
1362 // make the switch statement
1363 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001364 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001365
1366 // emit all the code in the segments
1367 breakForLoop.push(false);
1368 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1369 builder.nextSwitchSegment(segmentBlocks, s);
1370 if (codeSegments[s])
1371 codeSegments[s]->traverse(this);
1372 else
1373 builder.addSwitchBreak();
1374 }
1375 breakForLoop.pop();
1376
1377 builder.endSwitch(segmentBlocks);
1378
1379 return false;
1380}
1381
1382void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1383{
1384 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001385 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001386
1387 builder.clearAccessChain();
1388 builder.setAccessChainRValue(constant);
1389}
1390
1391bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1392{
1393 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1394 loopTerminal.push(node->getTerminal());
1395
David Netoc22f37c2015-07-15 16:21:26 -04001396 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001397
1398 if (node->getTest()) {
1399 node->getTest()->traverse(this);
1400 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001401 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001402 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001403 } else {
1404 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001405 }
1406
David Netoc22f37c2015-07-15 16:21:26 -04001407 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001408 breakForLoop.push(true);
1409 node->getBody()->traverse(this);
1410 breakForLoop.pop();
1411 }
1412
1413 if (loopTerminal.top())
1414 loopTerminal.top()->traverse(this);
1415
1416 builder.closeLoop();
1417
1418 loopTerminal.pop();
1419
1420 return false;
1421}
1422
1423bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1424{
1425 if (node->getExpression())
1426 node->getExpression()->traverse(this);
1427
1428 switch (node->getFlowOp()) {
1429 case glslang::EOpKill:
1430 builder.makeDiscard();
1431 break;
1432 case glslang::EOpBreak:
1433 if (breakForLoop.top())
1434 builder.createLoopExit();
1435 else
1436 builder.addSwitchBreak();
1437 break;
1438 case glslang::EOpContinue:
1439 if (loopTerminal.top())
1440 loopTerminal.top()->traverse(this);
1441 builder.createLoopContinue();
1442 break;
1443 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001444 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001445 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001446 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001447 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001448
1449 builder.clearAccessChain();
1450 break;
1451
1452 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001453 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001454 break;
1455 }
1456
1457 return false;
1458}
1459
1460spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1461{
1462 // First, steer off constants, which are not SPIR-V variables, but
1463 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001464 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001465 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001466 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001467 }
1468
1469 // Now, handle actual variables
1470 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1471 spv::Id spvType = convertGlslangToSpvType(node->getType());
1472
1473 const char* name = node->getName().c_str();
1474 if (glslang::IsAnonymous(name))
1475 name = "";
1476
1477 return builder.createVariable(storageClass, spvType, name);
1478}
1479
1480// Return type Id of the sampled type.
1481spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1482{
1483 switch (sampler.type) {
1484 case glslang::EbtFloat: return builder.makeFloatType(32);
1485 case glslang::EbtInt: return builder.makeIntType(32);
1486 case glslang::EbtUint: return builder.makeUintType(32);
1487 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001488 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001489 return builder.makeFloatType(32);
1490 }
1491}
1492
John Kessenich3ac051e2015-12-20 11:29:16 -07001493// Convert from a glslang type to an SPV type, by calling into a
1494// recursive version of this function. This establishes the inherited
1495// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001496spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1497{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001498 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001499}
1500
1501// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1502// explicitLayout can be kept the same throughout the heirarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001503spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001504{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001505 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001506
1507 switch (type.getBasicType()) {
1508 case glslang::EbtVoid:
1509 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001510 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001511 break;
1512 case glslang::EbtFloat:
1513 spvType = builder.makeFloatType(32);
1514 break;
1515 case glslang::EbtDouble:
1516 spvType = builder.makeFloatType(64);
1517 break;
1518 case glslang::EbtBool:
1519 spvType = builder.makeBoolType();
1520 break;
1521 case glslang::EbtInt:
1522 spvType = builder.makeIntType(32);
1523 break;
1524 case glslang::EbtUint:
1525 spvType = builder.makeUintType(32);
1526 break;
John Kessenich426394d2015-07-23 10:22:48 -06001527 case glslang::EbtAtomicUint:
1528 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1529 spvType = builder.makeUintType(32);
1530 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001531 case glslang::EbtSampler:
1532 {
1533 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001534 // an image is present, make its type
1535 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1536 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001537 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001538 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001539 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001540 }
John Kessenich140f3df2015-06-26 16:58:36 -06001541 break;
1542 case glslang::EbtStruct:
1543 case glslang::EbtBlock:
1544 {
1545 // If we've seen this struct type, return it
1546 const glslang::TTypeList* glslangStruct = type.getStruct();
1547 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001548
1549 // Try to share structs for different layouts, but not yet for other
1550 // kinds of qualification (primarily not yet including interpolant qualification).
1551 if (! HasNonLayoutQualifiers(qualifier))
1552 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1553 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001554 break;
1555
1556 // else, we haven't seen it...
1557
1558 // Create a vector of struct types for SPIR-V to consume
1559 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1560 if (type.getBasicType() == glslang::EbtBlock)
1561 memberRemapper[glslangStruct].resize(glslangStruct->size());
1562 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1563 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1564 if (glslangType.hiddenMember()) {
1565 ++memberDelta;
1566 if (type.getBasicType() == glslang::EbtBlock)
1567 memberRemapper[glslangStruct][i] = -1;
1568 } else {
1569 if (type.getBasicType() == glslang::EbtBlock)
1570 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001571 // modify just this child's view of the qualifier
1572 glslang::TQualifier subQualifier = glslangType.getQualifier();
1573 InheritQualifiers(subQualifier, qualifier);
1574 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001575 }
1576 }
1577
1578 // Make the SPIR-V type
1579 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001580 if (! HasNonLayoutQualifiers(qualifier))
1581 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001582
1583 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001584 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001585 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1586 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1587 int member = i;
1588 if (type.getBasicType() == glslang::EbtBlock)
1589 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001590
John Kesseniche0b6cad2015-12-24 10:30:13 -07001591 // modify just this child's view of the qualifier
1592 glslang::TQualifier subQualifier = glslangType.getQualifier();
1593 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001594
John Kessenich140f3df2015-06-26 16:58:36 -06001595 // using -1 above to indicate a hidden member
1596 if (member >= 0) {
1597 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001598 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001599 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001600 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1601 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001602 if (glslangType.getQualifier().hasLocation())
1603 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1604 if (glslangType.getQualifier().hasComponent())
1605 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1606 if (glslangType.getQualifier().hasXfbOffset())
1607 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001608 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001609 // figure out what to do with offset, which is accumulating
1610 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001611 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001612 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001613 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001614 offset = nextOffset;
1615 }
John Kessenich140f3df2015-06-26 16:58:36 -06001616
John Kessenichf85e8062015-12-19 13:57:10 -07001617 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001618 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001619
John Kessenich140f3df2015-06-26 16:58:36 -06001620 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001621 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1622 if (builtIn != spv::BadValue)
1623 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001624 }
1625 }
1626
1627 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001628 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001629 addDecoration(spvType, TranslateBlockDecoration(type));
1630 if (type.getQualifier().hasStream())
1631 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1632 if (glslangIntermediate->getXfbMode()) {
1633 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001634 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001635 if (type.getQualifier().hasXfbBuffer())
1636 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1637 }
1638 }
1639 break;
1640 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001641 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001642 break;
1643 }
1644
1645 if (type.isMatrix())
1646 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1647 else {
1648 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1649 if (type.getVectorSize() > 1)
1650 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1651 }
1652
1653 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001654 // Do all but the outer dimension
1655 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1656 assert(type.getArraySizes()->getDimSize(dim) > 0);
1657 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1658 }
John Kessenich31ed4832015-09-09 17:51:38 -06001659
John Kessenichc9a80832015-09-12 12:17:44 -06001660 // Do the outer dimension, which might not be known for a runtime-sized array
1661 if (type.isRuntimeSizedArray()) {
1662 spvType = builder.makeRuntimeArray(spvType);
1663 } else {
1664 assert(type.getOuterArraySize() > 0);
1665 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1666 }
1667
John Kessenich55e7d112015-11-15 21:33:39 -07001668 // TODO: explicit layout still needs to be done hierarchically for arrays of arrays, which
John Kessenichc9a80832015-09-12 12:17:44 -06001669 // may still require additional "link time" support from the front-end
1670 // for arrays of arrays
John Kessenich55e7d112015-11-15 21:33:39 -07001671
1672 // We need to decorate array strides for types needing explicit layout,
1673 // except for the very top if it is an array of blocks; that array is
1674 // not laid out in memory in a way needing a stride.
1675 if (explicitLayout && type.getBasicType() != glslang::EbtBlock)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001676 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type, explicitLayout, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001677 }
1678
1679 return spvType;
1680}
1681
John Kessenichf85e8062015-12-19 13:57:10 -07001682// Decide whether or not this type should be
1683// decorated with offsets and strides, and if so
1684// whether std140 or std430 rules should be applied.
1685glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001686{
John Kessenichf85e8062015-12-19 13:57:10 -07001687 // has to be a block
1688 if (type.getBasicType() != glslang::EbtBlock)
1689 return glslang::ElpNone;
1690
1691 // has to be a uniform or buffer block
1692 if (type.getQualifier().storage != glslang::EvqUniform &&
1693 type.getQualifier().storage != glslang::EvqBuffer)
1694 return glslang::ElpNone;
1695
1696 // return the layout to use
1697 switch (type.getQualifier().layoutPacking) {
1698 case glslang::ElpStd140:
1699 case glslang::ElpStd430:
1700 return type.getQualifier().layoutPacking;
1701 default:
1702 return glslang::ElpNone;
1703 }
John Kessenich31ed4832015-09-09 17:51:38 -06001704}
1705
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001706// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001707int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001708{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001709 int size;
John Kessenich3ac051e2015-12-20 11:29:16 -07001710 int stride = glslangIntermediate->getBaseAlignment(arrayType, size, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001711 if (arrayType.isMatrix()) {
1712 // GLSL strides are set to alignments of the matrix flattened to individual rows/cols,
1713 // but SPV needs an array stride for the whole matrix, not the rows/cols
John Kessenich3ac051e2015-12-20 11:29:16 -07001714 if (matrixLayout == glslang::ElmRowMajor)
John Kesseniche721f492015-12-06 19:17:49 -07001715 stride *= arrayType.getMatrixRows();
1716 else
1717 stride *= arrayType.getMatrixCols();
1718 }
1719
1720 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001721}
1722
1723// Given a matrix type, returns the integer stride required for that matrix
1724// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001725int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001726{
1727 int size;
John Kessenich3ac051e2015-12-20 11:29:16 -07001728 return glslangIntermediate->getBaseAlignment(matrixType, size, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001729}
1730
John Kessenich5e4b1242015-08-06 22:53:06 -06001731// Given a member type of a struct, realign the current offset for it, and compute
1732// the next (not yet aligned) offset for the next member, which will get aligned
1733// on the next call.
1734// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1735// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1736// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001737void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001738 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001739{
1740 // this will get a positive value when deemed necessary
1741 nextOffset = -1;
1742
John Kessenich5e4b1242015-08-06 22:53:06 -06001743 // override anything in currentOffset with user-set offset
1744 if (memberType.getQualifier().hasOffset())
1745 currentOffset = memberType.getQualifier().layoutOffset;
1746
1747 // It could be that current linker usage in glslang updated all the layoutOffset,
1748 // in which case the following code does not matter. But, that's not quite right
1749 // once cross-compilation unit GLSL validation is done, as the original user
1750 // settings are needed in layoutOffset, and then the following will come into play.
1751
John Kessenichf85e8062015-12-19 13:57:10 -07001752 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001753 if (! memberType.getQualifier().hasOffset())
1754 currentOffset = -1;
1755
1756 return;
1757 }
1758
John Kessenichf85e8062015-12-19 13:57:10 -07001759 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001760 if (currentOffset < 0)
1761 currentOffset = 0;
1762
1763 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1764 // but possibly not yet correctly aligned.
1765
1766 int memberSize;
John Kessenich3ac051e2015-12-20 11:29:16 -07001767 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001768 glslang::RoundToPow2(currentOffset, memberAlignment);
1769 nextOffset = currentOffset + memberSize;
1770}
1771
John Kessenich140f3df2015-06-26 16:58:36 -06001772bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1773{
1774 return node->getName() == "main(";
1775}
1776
1777// Make all the functions, skeletally, without actually visiting their bodies.
1778void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1779{
1780 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1781 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1782 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1783 continue;
1784
1785 // We're on a user function. Set up the basic interface for the function now,
1786 // so that it's available to call.
1787 // Translating the body will happen later.
1788 //
1789 // Typically (except for a "const in" parameter), an address will be passed to the
1790 // function. What it is an address of varies:
1791 //
1792 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1793 // so that write needs to be to a copy, hence the address of a copy works.
1794 //
1795 // - "const in" parameters can just be the r-value, as no writes need occur.
1796 //
1797 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1798 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1799
1800 std::vector<spv::Id> paramTypes;
1801 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1802
1803 for (int p = 0; p < (int)parameters.size(); ++p) {
1804 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1805 spv::Id typeId = convertGlslangToSpvType(paramType);
1806 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1807 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1808 else
1809 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1810 paramTypes.push_back(typeId);
1811 }
1812
1813 spv::Block* functionBlock;
1814 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1815 paramTypes, &functionBlock);
1816
1817 // Track function to emit/call later
1818 functionMap[glslFunction->getName().c_str()] = function;
1819
1820 // Set the parameter id's
1821 for (int p = 0; p < (int)parameters.size(); ++p) {
1822 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1823 // give a name too
1824 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1825 }
1826 }
1827}
1828
1829// Process all the initializers, while skipping the functions and link objects
1830void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1831{
1832 builder.setBuildPoint(shaderEntry->getLastBlock());
1833 for (int i = 0; i < (int)initializers.size(); ++i) {
1834 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1835 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1836
1837 // We're on a top-level node that's not a function. Treat as an initializer, whose
1838 // code goes into the beginning of main.
1839 initializer->traverse(this);
1840 }
1841 }
1842}
1843
1844// Process all the functions, while skipping initializers.
1845void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1846{
1847 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1848 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1849 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1850 node->traverse(this);
1851 }
1852}
1853
1854void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1855{
1856 // SPIR-V functions should already be in the functionMap from the prepass
1857 // that called makeFunctions().
1858 spv::Function* function = functionMap[node->getName().c_str()];
1859 spv::Block* functionBlock = function->getEntryBlock();
1860 builder.setBuildPoint(functionBlock);
1861}
1862
Rex Xu04db3f52015-09-16 11:44:02 +08001863void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001864{
Rex Xufc618912015-09-09 16:42:49 +08001865 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001866 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1867 builder.clearAccessChain();
1868 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001869
1870 // Special case l-value operands
1871 bool lvalue = false;
1872 switch (node.getOp()) {
1873 case glslang::EOpImageAtomicAdd:
1874 case glslang::EOpImageAtomicMin:
1875 case glslang::EOpImageAtomicMax:
1876 case glslang::EOpImageAtomicAnd:
1877 case glslang::EOpImageAtomicOr:
1878 case glslang::EOpImageAtomicXor:
1879 case glslang::EOpImageAtomicExchange:
1880 case glslang::EOpImageAtomicCompSwap:
1881 if (i == 0)
1882 lvalue = true;
1883 break;
1884 default:
1885 break;
1886 }
1887
Rex Xu6b86d492015-09-16 17:48:22 +08001888 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001889 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001890 else
Rex Xu30f92582015-09-14 10:38:56 +08001891 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001892 }
1893}
1894
John Kessenichfc51d282015-08-19 13:34:18 -06001895void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001896{
John Kessenichfc51d282015-08-19 13:34:18 -06001897 builder.clearAccessChain();
1898 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001899 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001900}
John Kessenich140f3df2015-06-26 16:58:36 -06001901
John Kessenichfc51d282015-08-19 13:34:18 -06001902spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1903{
Rex Xufc618912015-09-09 16:42:49 +08001904 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001905 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001906 }
1907
John Kessenichfc51d282015-08-19 13:34:18 -06001908 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001909 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1910 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1911 std::vector<spv::Id> arguments;
1912 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001913 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001914 else
1915 translateArguments(*node->getAsUnaryNode(), arguments);
1916 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1917
1918 spv::Builder::TextureParameters params = { };
1919 params.sampler = arguments[0];
1920
Rex Xu04db3f52015-09-16 11:44:02 +08001921 glslang::TCrackedTextureOp cracked;
1922 node->crackTexture(sampler, cracked);
1923
John Kessenichfc51d282015-08-19 13:34:18 -06001924 // Check for queries
1925 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07001926 // a sampled image needs to have the image extracted first
1927 if (builder.isSampledImage(params.sampler))
1928 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06001929 switch (node->getOp()) {
1930 case glslang::EOpImageQuerySize:
1931 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001932 if (arguments.size() > 1) {
1933 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001934 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001935 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001936 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001937 case glslang::EOpImageQuerySamples:
1938 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001939 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001940 case glslang::EOpTextureQueryLod:
1941 params.coords = arguments[1];
1942 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1943 case glslang::EOpTextureQueryLevels:
1944 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1945 default:
1946 assert(0);
1947 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001948 }
John Kessenich140f3df2015-06-26 16:58:36 -06001949 }
1950
Rex Xufc618912015-09-09 16:42:49 +08001951 // Check for image functions other than queries
1952 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001953 std::vector<spv::Id> operands;
1954 auto opIt = arguments.begin();
1955 operands.push_back(*(opIt++));
1956 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001957 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07001958 if (sampler.ms) {
1959 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08001960 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07001961 }
John Kessenich56bab042015-09-16 10:54:31 -06001962 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1963 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08001964 if (sampler.ms) {
1965 operands.push_back(*(opIt + 1));
1966 operands.push_back(spv::ImageOperandsSampleMask);
1967 operands.push_back(*opIt);
1968 } else
1969 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06001970 builder.createNoResultOp(spv::OpImageWrite, operands);
1971 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001972 } else {
1973 // Process image atomic operations
1974
1975 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1976 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001977 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001978
Rex Xufc618912015-09-09 16:42:49 +08001979 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001980 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001981
1982 std::vector<spv::Id> operands;
1983 operands.push_back(pointer);
1984 for (; opIt != arguments.end(); ++opIt)
1985 operands.push_back(*opIt);
1986
Rex Xu04db3f52015-09-16 11:44:02 +08001987 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001988 }
1989 }
1990
1991 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001992
Rex Xu71519fe2015-11-11 15:35:47 +08001993 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1994
John Kessenichfc51d282015-08-19 13:34:18 -06001995 // check for bias argument
1996 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08001997 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06001998 int nonBiasArgCount = 2;
1999 if (cracked.offset)
2000 ++nonBiasArgCount;
2001 if (cracked.grad)
2002 nonBiasArgCount += 2;
2003
2004 if ((int)arguments.size() > nonBiasArgCount)
2005 bias = true;
2006 }
2007
John Kessenichfc51d282015-08-19 13:34:18 -06002008 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002009
John Kessenichfc51d282015-08-19 13:34:18 -06002010 params.coords = arguments[1];
2011 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002012
2013 // sort out where Dref is coming from
2014 if (sampler.shadow && sampler.dim == glslang::EsdCube && sampler.arrayed)
John Kessenichfc51d282015-08-19 13:34:18 -06002015 params.Dref = arguments[2];
John Kessenich55e7d112015-11-15 21:33:39 -07002016 else if (sampler.shadow && cracked.gather) {
2017 params.Dref = arguments[2];
2018 ++extraArgs;
2019 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002020 std::vector<spv::Id> indexes;
2021 int comp;
2022 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002023 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002024 else
2025 comp = builder.getNumComponents(params.coords) - 1;
2026 indexes.push_back(comp);
2027 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2028 }
2029 if (cracked.lod) {
2030 params.lod = arguments[2];
2031 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002032 } else if (sampler.ms) {
2033 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002034 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002035 }
2036 if (cracked.grad) {
2037 params.gradX = arguments[2 + extraArgs];
2038 params.gradY = arguments[3 + extraArgs];
2039 extraArgs += 2;
2040 }
John Kessenich55e7d112015-11-15 21:33:39 -07002041 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002042 params.offset = arguments[2 + extraArgs];
2043 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002044 } else if (cracked.offsets) {
2045 params.offsets = arguments[2 + extraArgs];
2046 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002047 }
2048 if (bias) {
2049 params.bias = arguments[2 + extraArgs];
2050 ++extraArgs;
2051 }
John Kessenich55e7d112015-11-15 21:33:39 -07002052 if (cracked.gather && ! sampler.shadow) {
2053 // default component is 0, if missing, otherwise an argument
2054 if (2 + extraArgs < (int)arguments.size()) {
2055 params.comp = arguments[2 + extraArgs];
2056 ++extraArgs;
2057 } else {
2058 params.comp = builder.makeIntConstant(0);
2059 }
2060 }
John Kessenichfc51d282015-08-19 13:34:18 -06002061
John Kessenich55e7d112015-11-15 21:33:39 -07002062 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002063}
2064
2065spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2066{
2067 // Grab the function's pointer from the previously created function
2068 spv::Function* function = functionMap[node->getName().c_str()];
2069 if (! function)
2070 return 0;
2071
2072 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2073 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2074
2075 // See comments in makeFunctions() for details about the semantics for parameter passing.
2076 //
2077 // These imply we need a four step process:
2078 // 1. Evaluate the arguments
2079 // 2. Allocate and make copies of in, out, and inout arguments
2080 // 3. Make the call
2081 // 4. Copy back the results
2082
2083 // 1. Evaluate the arguments
2084 std::vector<spv::Builder::AccessChain> lValues;
2085 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002086 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002087 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2088 // build l-value
2089 builder.clearAccessChain();
2090 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002091 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002092 // keep outputs as l-values, evaluate input-only as r-values
2093 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2094 // save l-value
2095 lValues.push_back(builder.getAccessChain());
2096 } else {
2097 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002098 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002099 }
2100 }
2101
2102 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2103 // copy the original into that space.
2104 //
2105 // Also, build up the list of actual arguments to pass in for the call
2106 int lValueCount = 0;
2107 int rValueCount = 0;
2108 std::vector<spv::Id> spvArgs;
2109 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2110 spv::Id arg;
2111 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2112 // need space to hold the copy
2113 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2114 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2115 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2116 // need to copy the input into output space
2117 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002118 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002119 builder.createStore(copy, arg);
2120 }
2121 ++lValueCount;
2122 } else {
2123 arg = rValues[rValueCount];
2124 ++rValueCount;
2125 }
2126 spvArgs.push_back(arg);
2127 }
2128
2129 // 3. Make the call.
2130 spv::Id result = builder.createFunctionCall(function, spvArgs);
2131
2132 // 4. Copy back out an "out" arguments.
2133 lValueCount = 0;
2134 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2135 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2136 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2137 spv::Id copy = builder.createLoad(spvArgs[a]);
2138 builder.setAccessChain(lValues[lValueCount]);
2139 builder.accessChainStore(copy);
2140 }
2141 ++lValueCount;
2142 }
2143 }
2144
2145 return result;
2146}
2147
2148// Translate AST operation to SPV operation, already having SPV-based operands/types.
2149spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2150 spv::Id typeId, spv::Id left, spv::Id right,
2151 glslang::TBasicType typeProxy, bool reduceComparison)
2152{
2153 bool isUnsigned = typeProxy == glslang::EbtUint;
2154 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2155
2156 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002157 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002158 bool comparison = false;
2159
2160 switch (op) {
2161 case glslang::EOpAdd:
2162 case glslang::EOpAddAssign:
2163 if (isFloat)
2164 binOp = spv::OpFAdd;
2165 else
2166 binOp = spv::OpIAdd;
2167 break;
2168 case glslang::EOpSub:
2169 case glslang::EOpSubAssign:
2170 if (isFloat)
2171 binOp = spv::OpFSub;
2172 else
2173 binOp = spv::OpISub;
2174 break;
2175 case glslang::EOpMul:
2176 case glslang::EOpMulAssign:
2177 if (isFloat)
2178 binOp = spv::OpFMul;
2179 else
2180 binOp = spv::OpIMul;
2181 break;
2182 case glslang::EOpVectorTimesScalar:
2183 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002184 if (isFloat) {
2185 if (builder.isVector(right))
2186 std::swap(left, right);
2187 assert(builder.isScalar(right));
2188 needMatchingVectors = false;
2189 binOp = spv::OpVectorTimesScalar;
2190 } else
2191 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002192 break;
2193 case glslang::EOpVectorTimesMatrix:
2194 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002195 binOp = spv::OpVectorTimesMatrix;
2196 break;
2197 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002198 binOp = spv::OpMatrixTimesVector;
2199 break;
2200 case glslang::EOpMatrixTimesScalar:
2201 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002202 binOp = spv::OpMatrixTimesScalar;
2203 break;
2204 case glslang::EOpMatrixTimesMatrix:
2205 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002206 binOp = spv::OpMatrixTimesMatrix;
2207 break;
2208 case glslang::EOpOuterProduct:
2209 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002210 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002211 break;
2212
2213 case glslang::EOpDiv:
2214 case glslang::EOpDivAssign:
2215 if (isFloat)
2216 binOp = spv::OpFDiv;
2217 else if (isUnsigned)
2218 binOp = spv::OpUDiv;
2219 else
2220 binOp = spv::OpSDiv;
2221 break;
2222 case glslang::EOpMod:
2223 case glslang::EOpModAssign:
2224 if (isFloat)
2225 binOp = spv::OpFMod;
2226 else if (isUnsigned)
2227 binOp = spv::OpUMod;
2228 else
2229 binOp = spv::OpSMod;
2230 break;
2231 case glslang::EOpRightShift:
2232 case glslang::EOpRightShiftAssign:
2233 if (isUnsigned)
2234 binOp = spv::OpShiftRightLogical;
2235 else
2236 binOp = spv::OpShiftRightArithmetic;
2237 break;
2238 case glslang::EOpLeftShift:
2239 case glslang::EOpLeftShiftAssign:
2240 binOp = spv::OpShiftLeftLogical;
2241 break;
2242 case glslang::EOpAnd:
2243 case glslang::EOpAndAssign:
2244 binOp = spv::OpBitwiseAnd;
2245 break;
2246 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002247 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002248 binOp = spv::OpLogicalAnd;
2249 break;
2250 case glslang::EOpInclusiveOr:
2251 case glslang::EOpInclusiveOrAssign:
2252 binOp = spv::OpBitwiseOr;
2253 break;
2254 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002255 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002256 binOp = spv::OpLogicalOr;
2257 break;
2258 case glslang::EOpExclusiveOr:
2259 case glslang::EOpExclusiveOrAssign:
2260 binOp = spv::OpBitwiseXor;
2261 break;
2262 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002263 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002264 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002265 break;
2266
2267 case glslang::EOpLessThan:
2268 case glslang::EOpGreaterThan:
2269 case glslang::EOpLessThanEqual:
2270 case glslang::EOpGreaterThanEqual:
2271 case glslang::EOpEqual:
2272 case glslang::EOpNotEqual:
2273 case glslang::EOpVectorEqual:
2274 case glslang::EOpVectorNotEqual:
2275 comparison = true;
2276 break;
2277 default:
2278 break;
2279 }
2280
John Kessenich7c1aa102015-10-15 13:29:11 -06002281 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002282 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002283 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002284 if (builder.isMatrix(left) || builder.isMatrix(right))
2285 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002286
2287 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002288 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002289 builder.promoteScalar(precision, left, right);
2290
2291 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2292 builder.setPrecision(id, precision);
2293
2294 return id;
2295 }
2296
2297 if (! comparison)
2298 return 0;
2299
John Kessenich7c1aa102015-10-15 13:29:11 -06002300 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002301
2302 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2303 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2304
John Kessenich22118352015-12-21 20:54:09 -07002305 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002306 }
2307
2308 switch (op) {
2309 case glslang::EOpLessThan:
2310 if (isFloat)
2311 binOp = spv::OpFOrdLessThan;
2312 else if (isUnsigned)
2313 binOp = spv::OpULessThan;
2314 else
2315 binOp = spv::OpSLessThan;
2316 break;
2317 case glslang::EOpGreaterThan:
2318 if (isFloat)
2319 binOp = spv::OpFOrdGreaterThan;
2320 else if (isUnsigned)
2321 binOp = spv::OpUGreaterThan;
2322 else
2323 binOp = spv::OpSGreaterThan;
2324 break;
2325 case glslang::EOpLessThanEqual:
2326 if (isFloat)
2327 binOp = spv::OpFOrdLessThanEqual;
2328 else if (isUnsigned)
2329 binOp = spv::OpULessThanEqual;
2330 else
2331 binOp = spv::OpSLessThanEqual;
2332 break;
2333 case glslang::EOpGreaterThanEqual:
2334 if (isFloat)
2335 binOp = spv::OpFOrdGreaterThanEqual;
2336 else if (isUnsigned)
2337 binOp = spv::OpUGreaterThanEqual;
2338 else
2339 binOp = spv::OpSGreaterThanEqual;
2340 break;
2341 case glslang::EOpEqual:
2342 case glslang::EOpVectorEqual:
2343 if (isFloat)
2344 binOp = spv::OpFOrdEqual;
2345 else
2346 binOp = spv::OpIEqual;
2347 break;
2348 case glslang::EOpNotEqual:
2349 case glslang::EOpVectorNotEqual:
2350 if (isFloat)
2351 binOp = spv::OpFOrdNotEqual;
2352 else
2353 binOp = spv::OpINotEqual;
2354 break;
2355 default:
2356 break;
2357 }
2358
2359 if (binOp != spv::OpNop) {
2360 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2361 builder.setPrecision(id, precision);
2362
2363 return id;
2364 }
2365
2366 return 0;
2367}
2368
John Kessenich04bb8a02015-12-12 12:28:14 -07002369//
2370// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2371// These can be any of:
2372//
2373// matrix * scalar
2374// scalar * matrix
2375// matrix * matrix linear algebraic
2376// matrix * vector
2377// vector * matrix
2378// matrix * matrix componentwise
2379// matrix op matrix op in {+, -, /}
2380// matrix op scalar op in {+, -, /}
2381// scalar op matrix op in {+, -, /}
2382//
2383spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2384{
2385 bool firstClass = true;
2386
2387 // First, handle first-class matrix operations (* and matrix/scalar)
2388 switch (op) {
2389 case spv::OpFDiv:
2390 if (builder.isMatrix(left) && builder.isScalar(right)) {
2391 // turn matrix / scalar into a multiply...
2392 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2393 op = spv::OpMatrixTimesScalar;
2394 } else
2395 firstClass = false;
2396 break;
2397 case spv::OpMatrixTimesScalar:
2398 if (builder.isMatrix(right))
2399 std::swap(left, right);
2400 assert(builder.isScalar(right));
2401 break;
2402 case spv::OpVectorTimesMatrix:
2403 assert(builder.isVector(left));
2404 assert(builder.isMatrix(right));
2405 break;
2406 case spv::OpMatrixTimesVector:
2407 assert(builder.isMatrix(left));
2408 assert(builder.isVector(right));
2409 break;
2410 case spv::OpMatrixTimesMatrix:
2411 assert(builder.isMatrix(left));
2412 assert(builder.isMatrix(right));
2413 break;
2414 default:
2415 firstClass = false;
2416 break;
2417 }
2418
2419 if (firstClass) {
2420 spv::Id id = builder.createBinOp(op, typeId, left, right);
2421 builder.setPrecision(id, precision);
2422
2423 return id;
2424 }
2425
2426 // Handle component-wise +, -, *, and / for all combinations of type.
2427 // The result type of all of them is the same type as the (a) matrix operand.
2428 // The algorithm is to:
2429 // - break the matrix(es) into vectors
2430 // - smear any scalar to a vector
2431 // - do vector operations
2432 // - make a matrix out the vector results
2433 switch (op) {
2434 case spv::OpFAdd:
2435 case spv::OpFSub:
2436 case spv::OpFDiv:
2437 case spv::OpFMul:
2438 {
2439 // one time set up...
2440 bool leftMat = builder.isMatrix(left);
2441 bool rightMat = builder.isMatrix(right);
2442 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2443 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2444 spv::Id scalarType = builder.getScalarTypeId(typeId);
2445 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2446 std::vector<spv::Id> results;
2447 spv::Id smearVec = spv::NoResult;
2448 if (builder.isScalar(left))
2449 smearVec = builder.smearScalar(precision, left, vecType);
2450 else if (builder.isScalar(right))
2451 smearVec = builder.smearScalar(precision, right, vecType);
2452
2453 // do each vector op
2454 for (unsigned int c = 0; c < numCols; ++c) {
2455 std::vector<unsigned int> indexes;
2456 indexes.push_back(c);
2457 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2458 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2459 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2460 builder.setPrecision(results.back(), precision);
2461 }
2462
2463 // put the pieces together
2464 spv::Id id = builder.createCompositeConstruct(typeId, results);
2465 builder.setPrecision(id, precision);
2466 return id;
2467 }
2468 default:
2469 assert(0);
2470 return spv::NoResult;
2471 }
2472}
2473
Rex Xu04db3f52015-09-16 11:44:02 +08002474spv::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 -06002475{
2476 spv::Op unaryOp = spv::OpNop;
2477 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002478 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002479 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002480
2481 switch (op) {
2482 case glslang::EOpNegative:
2483 if (isFloat)
2484 unaryOp = spv::OpFNegate;
2485 else
2486 unaryOp = spv::OpSNegate;
2487 break;
2488
2489 case glslang::EOpLogicalNot:
2490 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002491 unaryOp = spv::OpLogicalNot;
2492 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002493 case glslang::EOpBitwiseNot:
2494 unaryOp = spv::OpNot;
2495 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002496
John Kessenich140f3df2015-06-26 16:58:36 -06002497 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002498 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002499 break;
2500 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002501 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002502 break;
2503 case glslang::EOpTranspose:
2504 unaryOp = spv::OpTranspose;
2505 break;
2506
2507 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002508 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002509 break;
2510 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002511 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002512 break;
2513 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002514 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002515 break;
2516 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002517 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002518 break;
2519 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002520 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002521 break;
2522 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002523 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002524 break;
2525 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002526 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002527 break;
2528 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002529 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002530 break;
2531
2532 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002533 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002534 break;
2535 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002536 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002537 break;
2538 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002539 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002540 break;
2541 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002542 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002543 break;
2544 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002545 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002546 break;
2547 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002548 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002549 break;
2550
2551 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002552 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002553 break;
2554 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002555 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002556 break;
2557
2558 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002559 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002560 break;
2561 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002562 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002563 break;
2564 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002565 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002566 break;
2567 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002568 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002569 break;
2570 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002571 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002572 break;
2573 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002574 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002575 break;
2576
2577 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002578 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002579 break;
2580 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002581 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002582 break;
2583 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002584 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002585 break;
2586 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002587 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002588 break;
2589 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002590 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002591 break;
2592 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002593 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002594 break;
2595
2596 case glslang::EOpIsNan:
2597 unaryOp = spv::OpIsNan;
2598 break;
2599 case glslang::EOpIsInf:
2600 unaryOp = spv::OpIsInf;
2601 break;
2602
Rex Xucbc426e2015-12-15 16:03:10 +08002603 case glslang::EOpFloatBitsToInt:
2604 case glslang::EOpFloatBitsToUint:
2605 case glslang::EOpIntBitsToFloat:
2606 case glslang::EOpUintBitsToFloat:
2607 unaryOp = spv::OpBitcast;
2608 break;
2609
John Kessenich140f3df2015-06-26 16:58:36 -06002610 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002611 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002612 break;
2613 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002614 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002615 break;
2616 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002617 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002618 break;
2619 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002620 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002621 break;
2622 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002623 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002624 break;
2625 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002626 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002627 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002628 case glslang::EOpPackSnorm4x8:
2629 libCall = spv::GLSLstd450PackSnorm4x8;
2630 break;
2631 case glslang::EOpUnpackSnorm4x8:
2632 libCall = spv::GLSLstd450UnpackSnorm4x8;
2633 break;
2634 case glslang::EOpPackUnorm4x8:
2635 libCall = spv::GLSLstd450PackUnorm4x8;
2636 break;
2637 case glslang::EOpUnpackUnorm4x8:
2638 libCall = spv::GLSLstd450UnpackUnorm4x8;
2639 break;
2640 case glslang::EOpPackDouble2x32:
2641 libCall = spv::GLSLstd450PackDouble2x32;
2642 break;
2643 case glslang::EOpUnpackDouble2x32:
2644 libCall = spv::GLSLstd450UnpackDouble2x32;
2645 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002646
2647 case glslang::EOpDPdx:
2648 unaryOp = spv::OpDPdx;
2649 break;
2650 case glslang::EOpDPdy:
2651 unaryOp = spv::OpDPdy;
2652 break;
2653 case glslang::EOpFwidth:
2654 unaryOp = spv::OpFwidth;
2655 break;
2656 case glslang::EOpDPdxFine:
2657 unaryOp = spv::OpDPdxFine;
2658 break;
2659 case glslang::EOpDPdyFine:
2660 unaryOp = spv::OpDPdyFine;
2661 break;
2662 case glslang::EOpFwidthFine:
2663 unaryOp = spv::OpFwidthFine;
2664 break;
2665 case glslang::EOpDPdxCoarse:
2666 unaryOp = spv::OpDPdxCoarse;
2667 break;
2668 case glslang::EOpDPdyCoarse:
2669 unaryOp = spv::OpDPdyCoarse;
2670 break;
2671 case glslang::EOpFwidthCoarse:
2672 unaryOp = spv::OpFwidthCoarse;
2673 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002674 case glslang::EOpInterpolateAtCentroid:
2675 libCall = spv::GLSLstd450InterpolateAtCentroid;
2676 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002677 case glslang::EOpAny:
2678 unaryOp = spv::OpAny;
2679 break;
2680 case glslang::EOpAll:
2681 unaryOp = spv::OpAll;
2682 break;
2683
2684 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002685 if (isFloat)
2686 libCall = spv::GLSLstd450FAbs;
2687 else
2688 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002689 break;
2690 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002691 if (isFloat)
2692 libCall = spv::GLSLstd450FSign;
2693 else
2694 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002695 break;
2696
John Kessenichfc51d282015-08-19 13:34:18 -06002697 case glslang::EOpAtomicCounterIncrement:
2698 case glslang::EOpAtomicCounterDecrement:
2699 case glslang::EOpAtomicCounter:
2700 {
2701 // Handle all of the atomics in one place, in createAtomicOperation()
2702 std::vector<spv::Id> operands;
2703 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002704 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002705 }
2706
2707 case glslang::EOpImageLoad:
2708 unaryOp = spv::OpImageRead;
2709 break;
2710
2711 case glslang::EOpBitFieldReverse:
2712 unaryOp = spv::OpBitReverse;
2713 break;
2714 case glslang::EOpBitCount:
2715 unaryOp = spv::OpBitCount;
2716 break;
2717 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002718 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002719 break;
2720 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002721 if (isUnsigned)
2722 libCall = spv::GLSLstd450FindUMsb;
2723 else
2724 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002725 break;
2726
John Kessenich140f3df2015-06-26 16:58:36 -06002727 default:
2728 return 0;
2729 }
2730
2731 spv::Id id;
2732 if (libCall >= 0) {
2733 std::vector<spv::Id> args;
2734 args.push_back(operand);
2735 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2736 } else
2737 id = builder.createUnaryOp(unaryOp, typeId, operand);
2738
2739 builder.setPrecision(id, precision);
2740
2741 return id;
2742}
2743
2744spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2745{
2746 spv::Op convOp = spv::OpNop;
2747 spv::Id zero = 0;
2748 spv::Id one = 0;
2749
2750 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2751
2752 switch (op) {
2753 case glslang::EOpConvIntToBool:
2754 case glslang::EOpConvUintToBool:
2755 zero = builder.makeUintConstant(0);
2756 zero = makeSmearedConstant(zero, vectorSize);
2757 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2758
2759 case glslang::EOpConvFloatToBool:
2760 zero = builder.makeFloatConstant(0.0F);
2761 zero = makeSmearedConstant(zero, vectorSize);
2762 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2763
2764 case glslang::EOpConvDoubleToBool:
2765 zero = builder.makeDoubleConstant(0.0);
2766 zero = makeSmearedConstant(zero, vectorSize);
2767 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2768
2769 case glslang::EOpConvBoolToFloat:
2770 convOp = spv::OpSelect;
2771 zero = builder.makeFloatConstant(0.0);
2772 one = builder.makeFloatConstant(1.0);
2773 break;
2774 case glslang::EOpConvBoolToDouble:
2775 convOp = spv::OpSelect;
2776 zero = builder.makeDoubleConstant(0.0);
2777 one = builder.makeDoubleConstant(1.0);
2778 break;
2779 case glslang::EOpConvBoolToInt:
2780 zero = builder.makeIntConstant(0);
2781 one = builder.makeIntConstant(1);
2782 convOp = spv::OpSelect;
2783 break;
2784 case glslang::EOpConvBoolToUint:
2785 zero = builder.makeUintConstant(0);
2786 one = builder.makeUintConstant(1);
2787 convOp = spv::OpSelect;
2788 break;
2789
2790 case glslang::EOpConvIntToFloat:
2791 case glslang::EOpConvIntToDouble:
2792 convOp = spv::OpConvertSToF;
2793 break;
2794
2795 case glslang::EOpConvUintToFloat:
2796 case glslang::EOpConvUintToDouble:
2797 convOp = spv::OpConvertUToF;
2798 break;
2799
2800 case glslang::EOpConvDoubleToFloat:
2801 case glslang::EOpConvFloatToDouble:
2802 convOp = spv::OpFConvert;
2803 break;
2804
2805 case glslang::EOpConvFloatToInt:
2806 case glslang::EOpConvDoubleToInt:
2807 convOp = spv::OpConvertFToS;
2808 break;
2809
2810 case glslang::EOpConvUintToInt:
2811 case glslang::EOpConvIntToUint:
2812 convOp = spv::OpBitcast;
2813 break;
2814
2815 case glslang::EOpConvFloatToUint:
2816 case glslang::EOpConvDoubleToUint:
2817 convOp = spv::OpConvertFToU;
2818 break;
2819 default:
2820 break;
2821 }
2822
2823 spv::Id result = 0;
2824 if (convOp == spv::OpNop)
2825 return result;
2826
2827 if (convOp == spv::OpSelect) {
2828 zero = makeSmearedConstant(zero, vectorSize);
2829 one = makeSmearedConstant(one, vectorSize);
2830 result = builder.createTriOp(convOp, destType, operand, one, zero);
2831 } else
2832 result = builder.createUnaryOp(convOp, destType, operand);
2833
2834 builder.setPrecision(result, precision);
2835
2836 return result;
2837}
2838
2839spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2840{
2841 if (vectorSize == 0)
2842 return constant;
2843
2844 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2845 std::vector<spv::Id> components;
2846 for (int c = 0; c < vectorSize; ++c)
2847 components.push_back(constant);
2848 return builder.makeCompositeConstant(vectorTypeId, components);
2849}
2850
John Kessenich426394d2015-07-23 10:22:48 -06002851// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002852spv::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 -06002853{
2854 spv::Op opCode = spv::OpNop;
2855
2856 switch (op) {
2857 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002858 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002859 opCode = spv::OpAtomicIAdd;
2860 break;
2861 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002862 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002863 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002864 break;
2865 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002866 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002867 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002868 break;
2869 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002870 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002871 opCode = spv::OpAtomicAnd;
2872 break;
2873 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002874 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002875 opCode = spv::OpAtomicOr;
2876 break;
2877 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002878 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002879 opCode = spv::OpAtomicXor;
2880 break;
2881 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002882 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002883 opCode = spv::OpAtomicExchange;
2884 break;
2885 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002886 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002887 opCode = spv::OpAtomicCompareExchange;
2888 break;
2889 case glslang::EOpAtomicCounterIncrement:
2890 opCode = spv::OpAtomicIIncrement;
2891 break;
2892 case glslang::EOpAtomicCounterDecrement:
2893 opCode = spv::OpAtomicIDecrement;
2894 break;
2895 case glslang::EOpAtomicCounter:
2896 opCode = spv::OpAtomicLoad;
2897 break;
2898 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002899 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06002900 break;
2901 }
2902
2903 // Sort out the operands
2904 // - mapping from glslang -> SPV
2905 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002906 // - compare-exchange swaps the value and comparator
2907 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002908 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2909 auto opIt = operands.begin(); // walk the glslang operands
2910 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002911 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2912 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2913 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002914 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2915 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002916 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002917 spvAtomicOperands.push_back(*(opIt + 1));
2918 spvAtomicOperands.push_back(*opIt);
2919 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002920 }
John Kessenich426394d2015-07-23 10:22:48 -06002921
John Kessenich3e60a6f2015-09-14 22:45:16 -06002922 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002923 for (; opIt != operands.end(); ++opIt)
2924 spvAtomicOperands.push_back(*opIt);
2925
2926 return builder.createOp(opCode, typeId, spvAtomicOperands);
2927}
2928
John Kessenich5e4b1242015-08-06 22:53:06 -06002929spv::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 -06002930{
John Kessenich5e4b1242015-08-06 22:53:06 -06002931 bool isUnsigned = typeProxy == glslang::EbtUint;
2932 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2933
John Kessenich140f3df2015-06-26 16:58:36 -06002934 spv::Op opCode = spv::OpNop;
2935 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002936 int consumedOperands = operands.size();
2937 spv::Id typeId0 = 0;
2938 if (consumedOperands > 0)
2939 typeId0 = builder.getTypeId(operands[0]);
2940 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002941
2942 switch (op) {
2943 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002944 if (isFloat)
2945 libCall = spv::GLSLstd450FMin;
2946 else if (isUnsigned)
2947 libCall = spv::GLSLstd450UMin;
2948 else
2949 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002950 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002951 break;
2952 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002953 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002954 break;
2955 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002956 if (isFloat)
2957 libCall = spv::GLSLstd450FMax;
2958 else if (isUnsigned)
2959 libCall = spv::GLSLstd450UMax;
2960 else
2961 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002962 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002963 break;
2964 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002965 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002966 break;
2967 case glslang::EOpDot:
2968 opCode = spv::OpDot;
2969 break;
2970 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002971 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002972 break;
2973
2974 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002975 if (isFloat)
2976 libCall = spv::GLSLstd450FClamp;
2977 else if (isUnsigned)
2978 libCall = spv::GLSLstd450UClamp;
2979 else
2980 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002981 builder.promoteScalar(precision, operands.front(), operands[1]);
2982 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002983 break;
2984 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07002985 if (isFloat)
2986 libCall = spv::GLSLstd450FMix;
2987 else
2988 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002989 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002990 break;
2991 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002992 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002993 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002994 break;
2995 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002996 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002997 builder.promoteScalar(precision, operands[0], operands[2]);
2998 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002999 break;
3000
3001 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003002 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003003 break;
3004 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003005 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003006 break;
3007 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003008 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003009 break;
3010 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003011 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003012 break;
3013 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003014 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003015 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003016 case glslang::EOpInterpolateAtSample:
3017 libCall = spv::GLSLstd450InterpolateAtSample;
3018 break;
3019 case glslang::EOpInterpolateAtOffset:
3020 libCall = spv::GLSLstd450InterpolateAtOffset;
3021 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003022 case glslang::EOpAddCarry:
3023 opCode = spv::OpIAddCarry;
3024 typeId = builder.makeStructResultType(typeId0, typeId0);
3025 consumedOperands = 2;
3026 break;
3027 case glslang::EOpSubBorrow:
3028 opCode = spv::OpISubBorrow;
3029 typeId = builder.makeStructResultType(typeId0, typeId0);
3030 consumedOperands = 2;
3031 break;
3032 case glslang::EOpUMulExtended:
3033 opCode = spv::OpUMulExtended;
3034 typeId = builder.makeStructResultType(typeId0, typeId0);
3035 consumedOperands = 2;
3036 break;
3037 case glslang::EOpIMulExtended:
3038 opCode = spv::OpSMulExtended;
3039 typeId = builder.makeStructResultType(typeId0, typeId0);
3040 consumedOperands = 2;
3041 break;
3042 case glslang::EOpBitfieldExtract:
3043 if (isUnsigned)
3044 opCode = spv::OpBitFieldUExtract;
3045 else
3046 opCode = spv::OpBitFieldSExtract;
3047 break;
3048 case glslang::EOpBitfieldInsert:
3049 opCode = spv::OpBitFieldInsert;
3050 break;
3051
3052 case glslang::EOpFma:
3053 libCall = spv::GLSLstd450Fma;
3054 break;
3055 case glslang::EOpFrexp:
3056 libCall = spv::GLSLstd450FrexpStruct;
3057 if (builder.getNumComponents(operands[0]) == 1)
3058 frexpIntType = builder.makeIntegerType(32, true);
3059 else
3060 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3061 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3062 consumedOperands = 1;
3063 break;
3064 case glslang::EOpLdexp:
3065 libCall = spv::GLSLstd450Ldexp;
3066 break;
3067
John Kessenich140f3df2015-06-26 16:58:36 -06003068 default:
3069 return 0;
3070 }
3071
3072 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003073 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003074 // Use an extended instruction from the standard library.
3075 // Construct the call arguments, without modifying the original operands vector.
3076 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3077 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
3078 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003079 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003080 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003081 case 0:
3082 // should all be handled by visitAggregate and createNoArgOperation
3083 assert(0);
3084 return 0;
3085 case 1:
3086 // should all be handled by createUnaryOperation
3087 assert(0);
3088 return 0;
3089 case 2:
3090 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3091 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003092 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003093 // anything 3 or over doesn't have l-value operands, so all should be consumed
3094 assert(consumedOperands == operands.size());
3095 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003096 break;
3097 }
3098 }
3099
John Kessenich55e7d112015-11-15 21:33:39 -07003100 // Decode the return types that were structures
3101 switch (op) {
3102 case glslang::EOpAddCarry:
3103 case glslang::EOpSubBorrow:
3104 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3105 id = builder.createCompositeExtract(id, typeId0, 0);
3106 break;
3107 case glslang::EOpUMulExtended:
3108 case glslang::EOpIMulExtended:
3109 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3110 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3111 break;
3112 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003113 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003114 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3115 id = builder.createCompositeExtract(id, typeId0, 0);
3116 break;
3117 default:
3118 break;
3119 }
3120
John Kessenich140f3df2015-06-26 16:58:36 -06003121 builder.setPrecision(id, precision);
3122
3123 return id;
3124}
3125
3126// Intrinsics with no arguments, no return value, and no precision.
3127spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3128{
3129 // TODO: get the barrier operands correct
3130
3131 switch (op) {
3132 case glslang::EOpEmitVertex:
3133 builder.createNoResultOp(spv::OpEmitVertex);
3134 return 0;
3135 case glslang::EOpEndPrimitive:
3136 builder.createNoResultOp(spv::OpEndPrimitive);
3137 return 0;
3138 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003139 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3140 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003141 return 0;
3142 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003143 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003144 return 0;
3145 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003146 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003147 return 0;
3148 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003149 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003150 return 0;
3151 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003152 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003153 return 0;
3154 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003155 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003156 return 0;
3157 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003158 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003159 return 0;
3160 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003161 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003162 return 0;
3163 }
3164}
3165
3166spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3167{
John Kessenich2f273362015-07-18 22:34:27 -06003168 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003169 spv::Id id;
3170 if (symbolValues.end() != iter) {
3171 id = iter->second;
3172 return id;
3173 }
3174
3175 // it was not found, create it
3176 id = createSpvVariable(symbol);
3177 symbolValues[symbol->getId()] = id;
3178
3179 if (! symbol->getType().isStruct()) {
3180 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003181 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003182 if (symbol->getQualifier().hasLocation())
3183 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3184 if (symbol->getQualifier().hasIndex())
3185 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3186 if (symbol->getQualifier().hasComponent())
3187 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3188 if (glslangIntermediate->getXfbMode()) {
3189 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003190 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003191 if (symbol->getQualifier().hasXfbBuffer())
3192 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3193 if (symbol->getQualifier().hasXfbOffset())
3194 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3195 }
3196 }
3197
John Kesseniche0b6cad2015-12-24 10:30:13 -07003198 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003199 if (symbol->getQualifier().hasStream())
3200 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3201 if (symbol->getQualifier().hasSet())
3202 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3203 if (symbol->getQualifier().hasBinding())
3204 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3205 if (glslangIntermediate->getXfbMode()) {
3206 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003207 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003208 if (symbol->getQualifier().hasXfbBuffer())
3209 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3210 }
3211
3212 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003213 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003214 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003215 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003216
John Kessenich140f3df2015-06-26 16:58:36 -06003217 return id;
3218}
3219
John Kessenich55e7d112015-11-15 21:33:39 -07003220// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003221void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3222{
3223 if (dec != spv::BadValue)
3224 builder.addDecoration(id, dec);
3225}
3226
John Kessenich55e7d112015-11-15 21:33:39 -07003227// If 'dec' is valid, add a one-operand decoration to an object
3228void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3229{
3230 if (dec != spv::BadValue)
3231 builder.addDecoration(id, dec, value);
3232}
3233
3234// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003235void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3236{
3237 if (dec != spv::BadValue)
3238 builder.addMemberDecoration(id, (unsigned)member, dec);
3239}
3240
John Kessenich55e7d112015-11-15 21:33:39 -07003241// Make a full tree of instructions to build a SPIR-V specialization constant,
3242// or regularly constant if possible.
3243//
3244// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3245//
3246// Recursively walk the nodes. The nodes form a tree whose leaves are
3247// regular constants, which themselves are trees that createSpvConstant()
3248// recursively walks. So, this function walks the "top" of the tree:
3249// - emit specialization constant-building instructions for specConstant
3250// - when running into a non-spec-constant, switch to createSpvConstant()
3251spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3252{
3253 assert(node.getQualifier().storage == glslang::EvqConst);
3254
3255 // hand off to the non-spec-constant path
3256 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3257 int nextConst = 0;
3258 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3259}
3260
John Kessenich140f3df2015-06-26 16:58:36 -06003261// Use 'consts' as the flattened glslang source of scalar constants to recursively
3262// build the aggregate SPIR-V constant.
3263//
3264// If there are not enough elements present in 'consts', 0 will be substituted;
3265// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3266//
John Kessenich55e7d112015-11-15 21:33:39 -07003267spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003268{
3269 // vector of constants for SPIR-V
3270 std::vector<spv::Id> spvConsts;
3271
3272 // Type is used for struct and array constants
3273 spv::Id typeId = convertGlslangToSpvType(glslangType);
3274
3275 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003276 glslang::TType elementType(glslangType, 0);
3277 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003278 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003279 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003280 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003281 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003282 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003283 } else if (glslangType.getStruct()) {
3284 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3285 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003286 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003287 } else if (glslangType.isVector()) {
3288 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3289 bool zero = nextConst >= consts.size();
3290 switch (glslangType.getBasicType()) {
3291 case glslang::EbtInt:
3292 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3293 break;
3294 case glslang::EbtUint:
3295 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3296 break;
3297 case glslang::EbtFloat:
3298 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3299 break;
3300 case glslang::EbtDouble:
3301 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3302 break;
3303 case glslang::EbtBool:
3304 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3305 break;
3306 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003307 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003308 break;
3309 }
3310 ++nextConst;
3311 }
3312 } else {
3313 // we have a non-aggregate (scalar) constant
3314 bool zero = nextConst >= consts.size();
3315 spv::Id scalar = 0;
3316 switch (glslangType.getBasicType()) {
3317 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003318 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003319 break;
3320 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003321 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003322 break;
3323 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003324 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003325 break;
3326 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003327 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003328 break;
3329 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003330 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003331 break;
3332 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003333 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003334 break;
3335 }
3336 ++nextConst;
3337 return scalar;
3338 }
3339
3340 return builder.makeCompositeConstant(typeId, spvConsts);
3341}
3342
John Kessenich7c1aa102015-10-15 13:29:11 -06003343// Return true if the node is a constant or symbol whose reading has no
3344// non-trivial observable cost or effect.
3345bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3346{
3347 // don't know what this is
3348 if (node == nullptr)
3349 return false;
3350
3351 // a constant is safe
3352 if (node->getAsConstantUnion() != nullptr)
3353 return true;
3354
3355 // not a symbol means non-trivial
3356 if (node->getAsSymbolNode() == nullptr)
3357 return false;
3358
3359 // a symbol, depends on what's being read
3360 switch (node->getType().getQualifier().storage) {
3361 case glslang::EvqTemporary:
3362 case glslang::EvqGlobal:
3363 case glslang::EvqIn:
3364 case glslang::EvqInOut:
3365 case glslang::EvqConst:
3366 case glslang::EvqConstReadOnly:
3367 case glslang::EvqUniform:
3368 return true;
3369 default:
3370 return false;
3371 }
3372}
3373
3374// A node is trivial if it is a single operation with no side effects.
3375// Error on the side of saying non-trivial.
3376// Return true if trivial.
3377bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3378{
3379 if (node == nullptr)
3380 return false;
3381
3382 // symbols and constants are trivial
3383 if (isTrivialLeaf(node))
3384 return true;
3385
3386 // otherwise, it needs to be a simple operation or one or two leaf nodes
3387
3388 // not a simple operation
3389 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3390 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3391 if (binaryNode == nullptr && unaryNode == nullptr)
3392 return false;
3393
3394 // not on leaf nodes
3395 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3396 return false;
3397
3398 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3399 return false;
3400 }
3401
3402 switch (node->getAsOperator()->getOp()) {
3403 case glslang::EOpLogicalNot:
3404 case glslang::EOpConvIntToBool:
3405 case glslang::EOpConvUintToBool:
3406 case glslang::EOpConvFloatToBool:
3407 case glslang::EOpConvDoubleToBool:
3408 case glslang::EOpEqual:
3409 case glslang::EOpNotEqual:
3410 case glslang::EOpLessThan:
3411 case glslang::EOpGreaterThan:
3412 case glslang::EOpLessThanEqual:
3413 case glslang::EOpGreaterThanEqual:
3414 case glslang::EOpIndexDirect:
3415 case glslang::EOpIndexDirectStruct:
3416 case glslang::EOpLogicalXor:
3417 case glslang::EOpAny:
3418 case glslang::EOpAll:
3419 return true;
3420 default:
3421 return false;
3422 }
3423}
3424
3425// Emit short-circuiting code, where 'right' is never evaluated unless
3426// the left side is true (for &&) or false (for ||).
3427spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3428{
3429 spv::Id boolTypeId = builder.makeBoolType();
3430
3431 // emit left operand
3432 builder.clearAccessChain();
3433 left.traverse(this);
3434 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3435
3436 // Operands to accumulate OpPhi operands
3437 std::vector<spv::Id> phiOperands;
3438 // accumulate left operand's phi information
3439 phiOperands.push_back(leftId);
3440 phiOperands.push_back(builder.getBuildPoint()->getId());
3441
3442 // Make the two kinds of operation symmetric with a "!"
3443 // || => emit "if (! left) result = right"
3444 // && => emit "if ( left) result = right"
3445 //
3446 // TODO: this runtime "not" for || could be avoided by adding functionality
3447 // to 'builder' to have an "else" without an "then"
3448 if (op == glslang::EOpLogicalOr)
3449 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3450
3451 // make an "if" based on the left value
3452 spv::Builder::If ifBuilder(leftId, builder);
3453
3454 // emit right operand as the "then" part of the "if"
3455 builder.clearAccessChain();
3456 right.traverse(this);
3457 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3458
3459 // accumulate left operand's phi information
3460 phiOperands.push_back(rightId);
3461 phiOperands.push_back(builder.getBuildPoint()->getId());
3462
3463 // finish the "if"
3464 ifBuilder.makeEndIf();
3465
3466 // phi together the two results
3467 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3468}
3469
John Kessenich140f3df2015-06-26 16:58:36 -06003470}; // end anonymous namespace
3471
3472namespace glslang {
3473
John Kessenich68d78fd2015-07-12 19:28:10 -06003474void GetSpirvVersion(std::string& version)
3475{
John Kessenich9e55f632015-07-15 10:03:39 -06003476 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003477 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003478 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003479 version = buf;
3480}
3481
John Kessenich140f3df2015-06-26 16:58:36 -06003482// Write SPIR-V out to a binary file
3483void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3484{
3485 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003486 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003487 for (int i = 0; i < (int)spirv.size(); ++i) {
3488 unsigned int word = spirv[i];
3489 out.write((const char*)&word, 4);
3490 }
3491 out.close();
3492}
3493
3494//
3495// Set up the glslang traversal
3496//
3497void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3498{
3499 TIntermNode* root = intermediate.getTreeRoot();
3500
3501 if (root == 0)
3502 return;
3503
3504 glslang::GetThreadPoolAllocator().push();
3505
3506 TGlslangToSpvTraverser it(&intermediate);
3507
3508 root->traverse(&it);
3509
3510 it.dumpSpv(spirv);
3511
3512 glslang::GetThreadPoolAllocator().pop();
3513}
3514
3515}; // end namespace glslang