blob: fb4e115675fcc44bdda1493558701b4929d21c62 [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
88 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
89
90protected:
91 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
92 spv::Id getSampledType(const glslang::TSampler&);
93 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich3ac051e2015-12-20 11:29:16 -070094 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, glslang::TLayoutMatrix);
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;
136 bool linkageOnly;
137 const glslang::TIntermediate* glslangIntermediate;
138 spv::Id stdBuiltins;
139
John Kessenich2f273362015-07-18 22:34:27 -0600140 std::unordered_map<int, spv::Id> symbolValues;
141 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
142 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700143 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600144 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 -0600145 std::stack<bool> breakForLoop; // false means break for switch
146 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
147};
148
149//
150// Helper functions for translating glslang representations to SPIR-V enumerants.
151//
152
153// Translate glslang profile to SPIR-V source language.
154spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
155{
156 switch (profile) {
157 case ENoProfile:
158 case ECoreProfile:
159 case ECompatibilityProfile:
160 return spv::SourceLanguageGLSL;
161 case EEsProfile:
162 return spv::SourceLanguageESSL;
163 default:
164 return spv::SourceLanguageUnknown;
165 }
166}
167
168// Translate glslang language (stage) to SPIR-V execution model.
169spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
170{
171 switch (stage) {
172 case EShLangVertex: return spv::ExecutionModelVertex;
173 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
174 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
175 case EShLangGeometry: return spv::ExecutionModelGeometry;
176 case EShLangFragment: return spv::ExecutionModelFragment;
177 case EShLangCompute: return spv::ExecutionModelGLCompute;
178 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700179 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600180 return spv::ExecutionModelFragment;
181 }
182}
183
184// Translate glslang type to SPIR-V storage class.
185spv::StorageClass TranslateStorageClass(const glslang::TType& type)
186{
187 if (type.getQualifier().isPipeInput())
188 return spv::StorageClassInput;
189 else if (type.getQualifier().isPipeOutput())
190 return spv::StorageClassOutput;
191 else if (type.getQualifier().isUniformOrBuffer()) {
192 if (type.getBasicType() == glslang::EbtBlock)
193 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800194 else if (type.getBasicType() == glslang::EbtAtomicUint)
195 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600196 else
197 return spv::StorageClassUniformConstant;
198 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
199 } else {
200 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700201 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
202 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600203 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
204 case glslang::EvqTemporary: return spv::StorageClassFunction;
205 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700206 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600207 return spv::StorageClassFunction;
208 }
209 }
210}
211
212// Translate glslang sampler type to SPIR-V dimensionality.
213spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
214{
215 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700216 case glslang::Esd1D: return spv::Dim1D;
217 case glslang::Esd2D: return spv::Dim2D;
218 case glslang::Esd3D: return spv::Dim3D;
219 case glslang::EsdCube: return spv::DimCube;
220 case glslang::EsdRect: return spv::DimRect;
221 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600222 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700223 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600224 return spv::Dim2D;
225 }
226}
227
228// Translate glslang type to SPIR-V precision decorations.
229spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
230{
231 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700232 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600233 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
234 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 default:
236 return spv::NoPrecision;
237 }
238}
239
240// Translate glslang type to SPIR-V block decorations.
241spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
242{
243 if (type.getBasicType() == glslang::EbtBlock) {
244 switch (type.getQualifier().storage) {
245 case glslang::EvqUniform: return spv::DecorationBlock;
246 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
247 case glslang::EvqVaryingIn: return spv::DecorationBlock;
248 case glslang::EvqVaryingOut: return spv::DecorationBlock;
249 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700250 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600251 break;
252 }
253 }
254
255 return (spv::Decoration)spv::BadValue;
256}
257
258// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700259spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600260{
261 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700262 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600263 case glslang::ElmRowMajor:
264 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700265 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600266 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700267 default:
268 // opaque layouts don't need a majorness
269 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 }
271 } else {
272 switch (type.getBasicType()) {
273 default:
274 return (spv::Decoration)spv::BadValue;
275 break;
276 case glslang::EbtBlock:
277 switch (type.getQualifier().storage) {
278 case glslang::EvqUniform:
279 case glslang::EvqBuffer:
280 switch (type.getQualifier().layoutPacking) {
281 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600282 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
283 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600284 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600285 }
286 case glslang::EvqVaryingIn:
287 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700288 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600289 return (spv::Decoration)spv::BadValue;
290 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return (spv::Decoration)spv::BadValue;
293 }
294 }
295 }
296}
297
298// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700299// Returns spv::Decoration(spv::BadValue) when no decoration
300// should be applied.
John Kessenich140f3df2015-06-26 16:58:36 -0600301spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
302{
John Kessenich55e7d112015-11-15 21:33:39 -0700303 if (type.getQualifier().smooth) {
304 // Smooth decoration doesn't exist in SPIR-V 1.0
305 return (spv::Decoration)spv::BadValue;
306 }
John Kessenich140f3df2015-06-26 16:58:36 -0600307 if (type.getQualifier().nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700308 return spv::DecorationNoPerspective;
John Kessenich140f3df2015-06-26 16:58:36 -0600309 else if (type.getQualifier().patch)
310 return spv::DecorationPatch;
311 else if (type.getQualifier().flat)
312 return spv::DecorationFlat;
313 else if (type.getQualifier().centroid)
314 return spv::DecorationCentroid;
315 else if (type.getQualifier().sample)
316 return spv::DecorationSample;
317 else
318 return (spv::Decoration)spv::BadValue;
319}
320
321// If glslang type is invaraiant, return SPIR-V invariant decoration.
322spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
323{
324 if (type.getQualifier().invariant)
325 return spv::DecorationInvariant;
326 else
327 return (spv::Decoration)spv::BadValue;
328}
329
330// Translate glslang built-in variable to SPIR-V built in decoration.
331spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
332{
333 switch (builtIn) {
334 case glslang::EbvPosition: return spv::BuiltInPosition;
335 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600336 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
337 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
338 case glslang::EbvVertexId: return spv::BuiltInVertexId;
339 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600340 case glslang::EbvBaseVertex:
341 case glslang::EbvBaseInstance:
342 case glslang::EbvDrawId:
343 // TODO: Add SPIR-V builtin ID.
344 spv::MissingFunctionality("Draw parameters");
345 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600346 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
347 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
348 case glslang::EbvLayer: return spv::BuiltInLayer;
349 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
350 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
351 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
352 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
353 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
354 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
355 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
356 case glslang::EbvFace: return spv::BuiltInFrontFacing;
357 case glslang::EbvSampleId: return spv::BuiltInSampleId;
358 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
359 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600360 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
361 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
362 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
363 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
364 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
365 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
366 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
367 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
368 default: return (spv::BuiltIn)spv::BadValue;
369 }
370}
371
Rex Xufc618912015-09-09 16:42:49 +0800372// Translate glslang image layout format to SPIR-V image format.
373spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
374{
375 assert(type.getBasicType() == glslang::EbtSampler);
376
377 switch (type.getQualifier().layoutFormat) {
378 case glslang::ElfNone: return spv::ImageFormatUnknown;
379 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
380 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
381 case glslang::ElfR32f: return spv::ImageFormatR32f;
382 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
383 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
384 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
385 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
386 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
387 case glslang::ElfR16f: return spv::ImageFormatR16f;
388 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
389 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
390 case glslang::ElfRg16: return spv::ImageFormatRg16;
391 case glslang::ElfRg8: return spv::ImageFormatRg8;
392 case glslang::ElfR16: return spv::ImageFormatR16;
393 case glslang::ElfR8: return spv::ImageFormatR8;
394 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
395 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
396 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
397 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
398 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
399 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
400 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
401 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
402 case glslang::ElfR32i: return spv::ImageFormatR32i;
403 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
404 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
405 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
406 case glslang::ElfR16i: return spv::ImageFormatR16i;
407 case glslang::ElfR8i: return spv::ImageFormatR8i;
408 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
409 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
410 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
411 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
412 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
413 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
414 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
415 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
416 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
417 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
418 default: return (spv::ImageFormat)spv::BadValue;
419 }
420}
421
John Kessenich140f3df2015-06-26 16:58:36 -0600422//
423// Implement the TGlslangToSpvTraverser class.
424//
425
426TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
427 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700428 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600429 inMain(false), mainTerminated(false), linkageOnly(false),
430 glslangIntermediate(glslangIntermediate)
431{
432 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
433
434 builder.clearAccessChain();
435 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
436 stdBuiltins = builder.import("GLSL.std.450");
437 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
438 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700439 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600440
441 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600442 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
443 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600444 builder.addSourceExtension(it->c_str());
445
446 // Add the top-level modes for this shader.
447
448 if (glslangIntermediate->getXfbMode())
449 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
450
451 unsigned int mode;
452 switch (glslangIntermediate->getStage()) {
453 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600454 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600455 break;
456
457 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600458 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600459 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
460 break;
461
462 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600463 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600464 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700465 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
466 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
467 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600468 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600469 }
470 if (mode != spv::BadValue)
471 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
472
John Kesseniche6903322015-10-13 16:29:02 -0600473 switch (glslangIntermediate->getVertexSpacing()) {
474 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
475 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
476 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
477 default: mode = spv::BadValue; break;
478 }
479 if (mode != spv::BadValue)
480 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
481
482 switch (glslangIntermediate->getVertexOrder()) {
483 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
484 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
485 default: mode = spv::BadValue; break;
486 }
487 if (mode != spv::BadValue)
488 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
489
490 if (glslangIntermediate->getPointMode())
491 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600492 break;
493
494 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600495 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600496 switch (glslangIntermediate->getInputPrimitive()) {
497 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
498 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
499 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700500 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600501 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
502 default: mode = spv::BadValue; break;
503 }
504 if (mode != spv::BadValue)
505 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600506
John Kessenich140f3df2015-06-26 16:58:36 -0600507 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
508
509 switch (glslangIntermediate->getOutputPrimitive()) {
510 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
511 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
512 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
513 default: mode = spv::BadValue; break;
514 }
515 if (mode != spv::BadValue)
516 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
517 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
518 break;
519
520 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600521 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600522 if (glslangIntermediate->getPixelCenterInteger())
523 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600524
John Kessenich140f3df2015-06-26 16:58:36 -0600525 if (glslangIntermediate->getOriginUpperLeft())
526 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600527 else
528 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600529
530 if (glslangIntermediate->getEarlyFragmentTests())
531 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
532
533 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600534 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
535 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
536 default: mode = spv::BadValue; break;
537 }
538 if (mode != spv::BadValue)
539 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
540
541 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
542 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600543 break;
544
545 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600546 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600547 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
548 glslangIntermediate->getLocalSize(1),
549 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600550 break;
551
552 default:
553 break;
554 }
555
556}
557
558TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
559{
560 if (! mainTerminated) {
561 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
562 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600563 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600564 }
565}
566
567//
568// Implement the traversal functions.
569//
570// Return true from interior nodes to have the external traversal
571// continue on to children. Return false if children were
572// already processed.
573//
574
575//
576// Symbols can turn into
577// - uniform/input reads
578// - output writes
579// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
580// - something simple that degenerates into the last bullet
581//
582void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
583{
584 // getSymbolId() will set up all the IO decorations on the first call.
585 // Formal function parameters were mapped during makeFunctions().
586 spv::Id id = getSymbolId(symbol);
587
588 if (! linkageOnly) {
589 // Prepare to generate code for the access
590
591 // L-value chains will be computed left to right. We're on the symbol now,
592 // which is the left-most part of the access chain, so now is "clear" time,
593 // followed by setting the base.
594 builder.clearAccessChain();
595
596 // For now, we consider all user variables as being in memory, so they are pointers,
597 // except for "const in" arguments to a function, which are an intermediate object.
598 // See comments in handleUserFunctionCall().
599 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
600 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
601 builder.setAccessChainRValue(id);
602 else
603 builder.setAccessChainLValue(id);
John Kessenich55e7d112015-11-15 21:33:39 -0700604 } else {
605 // finish off the entry-point SPV instruction by adding the Input/Output <id>
John Kesseniche00e72d2015-12-08 20:48:49 -0700606 if (builder.isPointer(id)) {
607 spv::StorageClass sc = builder.getStorageClass(id);
608 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
609 entryPoint->addIdOperand(id);
610 }
John Kessenich140f3df2015-06-26 16:58:36 -0600611 }
612}
613
614bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
615{
616 // First, handle special cases
617 switch (node->getOp()) {
618 case glslang::EOpAssign:
619 case glslang::EOpAddAssign:
620 case glslang::EOpSubAssign:
621 case glslang::EOpMulAssign:
622 case glslang::EOpVectorTimesMatrixAssign:
623 case glslang::EOpVectorTimesScalarAssign:
624 case glslang::EOpMatrixTimesScalarAssign:
625 case glslang::EOpMatrixTimesMatrixAssign:
626 case glslang::EOpDivAssign:
627 case glslang::EOpModAssign:
628 case glslang::EOpAndAssign:
629 case glslang::EOpInclusiveOrAssign:
630 case glslang::EOpExclusiveOrAssign:
631 case glslang::EOpLeftShiftAssign:
632 case glslang::EOpRightShiftAssign:
633 // A bin-op assign "a += b" means the same thing as "a = a + b"
634 // where a is evaluated before b. For a simple assignment, GLSL
635 // says to evaluate the left before the right. So, always, left
636 // node then right node.
637 {
638 // get the left l-value, save it away
639 builder.clearAccessChain();
640 node->getLeft()->traverse(this);
641 spv::Builder::AccessChain lValue = builder.getAccessChain();
642
643 // evaluate the right
644 builder.clearAccessChain();
645 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600646 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600647
648 if (node->getOp() != glslang::EOpAssign) {
649 // the left is also an r-value
650 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600651 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600652
653 // do the operation
654 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
655 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
656 node->getType().getBasicType());
657
658 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700659 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600660 }
661
662 // store the result
663 builder.setAccessChain(lValue);
664 builder.accessChainStore(rValue);
665
666 // assignments are expressions having an rValue after they are evaluated...
667 builder.clearAccessChain();
668 builder.setAccessChainRValue(rValue);
669 }
670 return false;
671 case glslang::EOpIndexDirect:
672 case glslang::EOpIndexDirectStruct:
673 {
674 // Get the left part of the access chain.
675 node->getLeft()->traverse(this);
676
677 // Add the next element in the chain
678
John Kessenich55e7d112015-11-15 21:33:39 -0700679 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600680 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
681 // This may be, e.g., an anonymous block-member selection, which generally need
682 // index remapping due to hidden members in anonymous blocks.
683 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700684 assert(remapper.size() > 0);
685 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600686 }
687
688 if (! node->getLeft()->getType().isArray() &&
689 node->getLeft()->getType().isVector() &&
690 node->getOp() == glslang::EOpIndexDirect) {
691 // This is essentially a hard-coded vector swizzle of size 1,
692 // so short circuit the access-chain stuff with a swizzle.
693 std::vector<unsigned> swizzle;
694 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600695 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600696 } else {
697 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600698 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600699 }
700 }
701 return false;
702 case glslang::EOpIndexIndirect:
703 {
704 // Structure or array or vector indirection.
705 // Will use native SPIR-V access-chain for struct and array indirection;
706 // matrices are arrays of vectors, so will also work for a matrix.
707 // Will use the access chain's 'component' for variable index into a vector.
708
709 // This adapter is building access chains left to right.
710 // Set up the access chain to the left.
711 node->getLeft()->traverse(this);
712
713 // save it so that computing the right side doesn't trash it
714 spv::Builder::AccessChain partial = builder.getAccessChain();
715
716 // compute the next index in the chain
717 builder.clearAccessChain();
718 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600719 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600720
721 // restore the saved access chain
722 builder.setAccessChain(partial);
723
724 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600725 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600726 else
John Kessenichfa668da2015-09-13 14:46:30 -0600727 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600728 }
729 return false;
730 case glslang::EOpVectorSwizzle:
731 {
732 node->getLeft()->traverse(this);
733 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
734 std::vector<unsigned> swizzle;
735 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
736 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600737 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600738 }
739 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600740 case glslang::EOpLogicalOr:
741 case glslang::EOpLogicalAnd:
742 {
743
744 // These may require short circuiting, but can sometimes be done as straight
745 // binary operations. The right operand must be short circuited if it has
746 // side effects, and should probably be if it is complex.
747 if (isTrivial(node->getRight()->getAsTyped()))
748 break; // handle below as a normal binary operation
749 // otherwise, we need to do dynamic short circuiting on the right operand
750 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
751 builder.clearAccessChain();
752 builder.setAccessChainRValue(result);
753 }
754 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600755 default:
756 break;
757 }
758
759 // Assume generic binary op...
760
761 // Get the operands
762 builder.clearAccessChain();
763 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600764 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600765
766 builder.clearAccessChain();
767 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600768 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600769
770 spv::Id result;
771 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
772
773 result = createBinaryOperation(node->getOp(), precision,
774 convertGlslangToSpvType(node->getType()), left, right,
775 node->getLeft()->getType().getBasicType());
776
777 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700778 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich140f3df2015-06-26 16:58:36 -0600779 } else {
780 builder.clearAccessChain();
781 builder.setAccessChainRValue(result);
782
783 return false;
784 }
785
786 return true;
787}
788
789bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
790{
John Kessenichfc51d282015-08-19 13:34:18 -0600791 spv::Id result = spv::NoResult;
792
793 // try texturing first
794 result = createImageTextureFunctionCall(node);
795 if (result != spv::NoResult) {
796 builder.clearAccessChain();
797 builder.setAccessChainRValue(result);
798
799 return false; // done with this node
800 }
801
802 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600803
804 if (node->getOp() == glslang::EOpArrayLength) {
805 // Quite special; won't want to evaluate the operand.
806
807 // Normal .length() would have been constant folded by the front-end.
808 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600809 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600810 assert(node->getOperand()->getType().isRuntimeSizedArray());
811 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
812 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600813 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
814 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600815
816 builder.clearAccessChain();
817 builder.setAccessChainRValue(length);
818
819 return false;
820 }
821
John Kessenichfc51d282015-08-19 13:34:18 -0600822 // Start by evaluating the operand
823
John Kessenich140f3df2015-06-26 16:58:36 -0600824 builder.clearAccessChain();
825 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800826
Rex Xufc618912015-09-09 16:42:49 +0800827 spv::Id operand = spv::NoResult;
828
829 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
830 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800831 node->getOp() == glslang::EOpAtomicCounter ||
832 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800833 operand = builder.accessChainGetLValue(); // Special case l-value operands
834 else
Rex Xu30f92582015-09-14 10:38:56 +0800835 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600836
837 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
838
839 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600840 if (! result)
841 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600842
843 // if not, then possibly an operation
844 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700845 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600846
847 if (result) {
848 builder.clearAccessChain();
849 builder.setAccessChainRValue(result);
850
851 return false; // done with this node
852 }
853
854 // it must be a special case, check...
855 switch (node->getOp()) {
856 case glslang::EOpPostIncrement:
857 case glslang::EOpPostDecrement:
858 case glslang::EOpPreIncrement:
859 case glslang::EOpPreDecrement:
860 {
861 // we need the integer value "1" or the floating point "1.0" to add/subtract
862 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
863 builder.makeFloatConstant(1.0F) :
864 builder.makeIntConstant(1);
865 glslang::TOperator op;
866 if (node->getOp() == glslang::EOpPreIncrement ||
867 node->getOp() == glslang::EOpPostIncrement)
868 op = glslang::EOpAdd;
869 else
870 op = glslang::EOpSub;
871
872 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
873 convertGlslangToSpvType(node->getType()), operand, one,
874 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700875 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600876
877 // The result of operation is always stored, but conditionally the
878 // consumed result. The consumed result is always an r-value.
879 builder.accessChainStore(result);
880 builder.clearAccessChain();
881 if (node->getOp() == glslang::EOpPreIncrement ||
882 node->getOp() == glslang::EOpPreDecrement)
883 builder.setAccessChainRValue(result);
884 else
885 builder.setAccessChainRValue(operand);
886 }
887
888 return false;
889
890 case glslang::EOpEmitStreamVertex:
891 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
892 return false;
893 case glslang::EOpEndStreamPrimitive:
894 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
895 return false;
896
897 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700898 spv::MissingFunctionality("unknown glslang unary");
John Kessenich140f3df2015-06-26 16:58:36 -0600899 break;
900 }
901
902 return true;
903}
904
905bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
906{
John Kessenichfc51d282015-08-19 13:34:18 -0600907 spv::Id result = spv::NoResult;
908
909 // try texturing
910 result = createImageTextureFunctionCall(node);
911 if (result != spv::NoResult) {
912 builder.clearAccessChain();
913 builder.setAccessChainRValue(result);
914
915 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600916 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800917 // "imageStore" is a special case, which has no result
918 return false;
919 }
John Kessenichfc51d282015-08-19 13:34:18 -0600920
John Kessenich140f3df2015-06-26 16:58:36 -0600921 glslang::TOperator binOp = glslang::EOpNull;
922 bool reduceComparison = true;
923 bool isMatrix = false;
924 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600925 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600926
927 assert(node->getOp());
928
929 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
930
931 switch (node->getOp()) {
932 case glslang::EOpSequence:
933 {
934 if (preVisit)
935 ++sequenceDepth;
936 else
937 --sequenceDepth;
938
939 if (sequenceDepth == 1) {
940 // If this is the parent node of all the functions, we want to see them
941 // early, so all call points have actual SPIR-V functions to reference.
942 // In all cases, still let the traverser visit the children for us.
943 makeFunctions(node->getAsAggregate()->getSequence());
944
945 // Also, we want all globals initializers to go into the entry of main(), before
946 // anything else gets there, so visit out of order, doing them all now.
947 makeGlobalInitializers(node->getAsAggregate()->getSequence());
948
949 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
950 // so do them manually.
951 visitFunctions(node->getAsAggregate()->getSequence());
952
953 return false;
954 }
955
956 return true;
957 }
958 case glslang::EOpLinkerObjects:
959 {
960 if (visit == glslang::EvPreVisit)
961 linkageOnly = true;
962 else
963 linkageOnly = false;
964
965 return true;
966 }
967 case glslang::EOpComma:
968 {
969 // processing from left to right naturally leaves the right-most
970 // lying around in the access chain
971 glslang::TIntermSequence& glslangOperands = node->getSequence();
972 for (int i = 0; i < (int)glslangOperands.size(); ++i)
973 glslangOperands[i]->traverse(this);
974
975 return false;
976 }
977 case glslang::EOpFunction:
978 if (visit == glslang::EvPreVisit) {
979 if (isShaderEntrypoint(node)) {
980 inMain = true;
981 builder.setBuildPoint(shaderEntry->getLastBlock());
982 } else {
983 handleFunctionEntry(node);
984 }
985 } else {
986 if (inMain)
987 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600988 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600989 inMain = false;
990 }
991
992 return true;
993 case glslang::EOpParameters:
994 // Parameters will have been consumed by EOpFunction processing, but not
995 // the body, so we still visited the function node's children, making this
996 // child redundant.
997 return false;
998 case glslang::EOpFunctionCall:
999 {
1000 if (node->isUserDefined())
1001 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001002 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001003 builder.clearAccessChain();
1004 builder.setAccessChainRValue(result);
1005
1006 return false;
1007 }
1008 case glslang::EOpConstructMat2x2:
1009 case glslang::EOpConstructMat2x3:
1010 case glslang::EOpConstructMat2x4:
1011 case glslang::EOpConstructMat3x2:
1012 case glslang::EOpConstructMat3x3:
1013 case glslang::EOpConstructMat3x4:
1014 case glslang::EOpConstructMat4x2:
1015 case glslang::EOpConstructMat4x3:
1016 case glslang::EOpConstructMat4x4:
1017 case glslang::EOpConstructDMat2x2:
1018 case glslang::EOpConstructDMat2x3:
1019 case glslang::EOpConstructDMat2x4:
1020 case glslang::EOpConstructDMat3x2:
1021 case glslang::EOpConstructDMat3x3:
1022 case glslang::EOpConstructDMat3x4:
1023 case glslang::EOpConstructDMat4x2:
1024 case glslang::EOpConstructDMat4x3:
1025 case glslang::EOpConstructDMat4x4:
1026 isMatrix = true;
1027 // fall through
1028 case glslang::EOpConstructFloat:
1029 case glslang::EOpConstructVec2:
1030 case glslang::EOpConstructVec3:
1031 case glslang::EOpConstructVec4:
1032 case glslang::EOpConstructDouble:
1033 case glslang::EOpConstructDVec2:
1034 case glslang::EOpConstructDVec3:
1035 case glslang::EOpConstructDVec4:
1036 case glslang::EOpConstructBool:
1037 case glslang::EOpConstructBVec2:
1038 case glslang::EOpConstructBVec3:
1039 case glslang::EOpConstructBVec4:
1040 case glslang::EOpConstructInt:
1041 case glslang::EOpConstructIVec2:
1042 case glslang::EOpConstructIVec3:
1043 case glslang::EOpConstructIVec4:
1044 case glslang::EOpConstructUint:
1045 case glslang::EOpConstructUVec2:
1046 case glslang::EOpConstructUVec3:
1047 case glslang::EOpConstructUVec4:
1048 case glslang::EOpConstructStruct:
1049 {
1050 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001051 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001052 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1053 spv::Id constructed;
1054 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1055 std::vector<spv::Id> constituents;
1056 for (int c = 0; c < (int)arguments.size(); ++c)
1057 constituents.push_back(arguments[c]);
1058 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001059 } else if (isMatrix)
1060 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1061 else
1062 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001063
1064 builder.clearAccessChain();
1065 builder.setAccessChainRValue(constructed);
1066
1067 return false;
1068 }
1069
1070 // These six are component-wise compares with component-wise results.
1071 // Forward on to createBinaryOperation(), requesting a vector result.
1072 case glslang::EOpLessThan:
1073 case glslang::EOpGreaterThan:
1074 case glslang::EOpLessThanEqual:
1075 case glslang::EOpGreaterThanEqual:
1076 case glslang::EOpVectorEqual:
1077 case glslang::EOpVectorNotEqual:
1078 {
1079 // Map the operation to a binary
1080 binOp = node->getOp();
1081 reduceComparison = false;
1082 switch (node->getOp()) {
1083 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1084 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1085 default: binOp = node->getOp(); break;
1086 }
1087
1088 break;
1089 }
1090 case glslang::EOpMul:
1091 // compontent-wise matrix multiply
1092 binOp = glslang::EOpMul;
1093 break;
1094 case glslang::EOpOuterProduct:
1095 // two vectors multiplied to make a matrix
1096 binOp = glslang::EOpOuterProduct;
1097 break;
1098 case glslang::EOpDot:
1099 {
1100 // for scalar dot product, use multiply
1101 glslang::TIntermSequence& glslangOperands = node->getSequence();
1102 if (! glslangOperands[0]->getAsTyped()->isVector())
1103 binOp = glslang::EOpMul;
1104 break;
1105 }
1106 case glslang::EOpMod:
1107 // when an aggregate, this is the floating-point mod built-in function,
1108 // which can be emitted by the one in createBinaryOperation()
1109 binOp = glslang::EOpMod;
1110 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001111 case glslang::EOpEmitVertex:
1112 case glslang::EOpEndPrimitive:
1113 case glslang::EOpBarrier:
1114 case glslang::EOpMemoryBarrier:
1115 case glslang::EOpMemoryBarrierAtomicCounter:
1116 case glslang::EOpMemoryBarrierBuffer:
1117 case glslang::EOpMemoryBarrierImage:
1118 case glslang::EOpMemoryBarrierShared:
1119 case glslang::EOpGroupMemoryBarrier:
1120 noReturnValue = true;
1121 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1122 break;
1123
John Kessenich426394d2015-07-23 10:22:48 -06001124 case glslang::EOpAtomicAdd:
1125 case glslang::EOpAtomicMin:
1126 case glslang::EOpAtomicMax:
1127 case glslang::EOpAtomicAnd:
1128 case glslang::EOpAtomicOr:
1129 case glslang::EOpAtomicXor:
1130 case glslang::EOpAtomicExchange:
1131 case glslang::EOpAtomicCompSwap:
1132 atomic = true;
1133 break;
1134
John Kessenich140f3df2015-06-26 16:58:36 -06001135 default:
1136 break;
1137 }
1138
1139 //
1140 // See if it maps to a regular operation.
1141 //
John Kessenich140f3df2015-06-26 16:58:36 -06001142 if (binOp != glslang::EOpNull) {
1143 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1144 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1145 assert(left && right);
1146
1147 builder.clearAccessChain();
1148 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001149 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001150
1151 builder.clearAccessChain();
1152 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001153 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001154
1155 result = createBinaryOperation(binOp, precision,
1156 convertGlslangToSpvType(node->getType()), leftId, rightId,
1157 left->getType().getBasicType(), reduceComparison);
1158
1159 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001160 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001161 builder.clearAccessChain();
1162 builder.setAccessChainRValue(result);
1163
1164 return false;
1165 }
1166
John Kessenich426394d2015-07-23 10:22:48 -06001167 //
1168 // Create the list of operands.
1169 //
John Kessenich140f3df2015-06-26 16:58:36 -06001170 glslang::TIntermSequence& glslangOperands = node->getSequence();
1171 std::vector<spv::Id> operands;
1172 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1173 builder.clearAccessChain();
1174 glslangOperands[arg]->traverse(this);
1175
1176 // special case l-value operands; there are just a few
1177 bool lvalue = false;
1178 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001179 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001180 case glslang::EOpModf:
1181 if (arg == 1)
1182 lvalue = true;
1183 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001184 case glslang::EOpInterpolateAtSample:
1185 case glslang::EOpInterpolateAtOffset:
1186 if (arg == 0)
1187 lvalue = true;
1188 break;
Rex Xud4782c12015-09-06 16:30:11 +08001189 case glslang::EOpAtomicAdd:
1190 case glslang::EOpAtomicMin:
1191 case glslang::EOpAtomicMax:
1192 case glslang::EOpAtomicAnd:
1193 case glslang::EOpAtomicOr:
1194 case glslang::EOpAtomicXor:
1195 case glslang::EOpAtomicExchange:
1196 case glslang::EOpAtomicCompSwap:
1197 if (arg == 0)
1198 lvalue = true;
1199 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001200 case glslang::EOpAddCarry:
1201 case glslang::EOpSubBorrow:
1202 if (arg == 2)
1203 lvalue = true;
1204 break;
1205 case glslang::EOpUMulExtended:
1206 case glslang::EOpIMulExtended:
1207 if (arg >= 2)
1208 lvalue = true;
1209 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001210 default:
1211 break;
1212 }
1213 if (lvalue)
1214 operands.push_back(builder.accessChainGetLValue());
1215 else
John Kessenichfa668da2015-09-13 14:46:30 -06001216 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001217 }
John Kessenich426394d2015-07-23 10:22:48 -06001218
1219 if (atomic) {
1220 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001221 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001222 } else {
1223 // Pass through to generic operations.
1224 switch (glslangOperands.size()) {
1225 case 0:
1226 result = createNoArgOperation(node->getOp());
1227 break;
1228 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001229 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001230 break;
1231 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001232 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001233 break;
1234 }
John Kessenich140f3df2015-06-26 16:58:36 -06001235 }
1236
1237 if (noReturnValue)
1238 return false;
1239
1240 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001241 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich140f3df2015-06-26 16:58:36 -06001242 return true;
1243 } else {
1244 builder.clearAccessChain();
1245 builder.setAccessChainRValue(result);
1246 return false;
1247 }
1248}
1249
1250bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1251{
1252 // This path handles both if-then-else and ?:
1253 // The if-then-else has a node type of void, while
1254 // ?: has a non-void node type
1255 spv::Id result = 0;
1256 if (node->getBasicType() != glslang::EbtVoid) {
1257 // don't handle this as just on-the-fly temporaries, because there will be two names
1258 // and better to leave SSA to later passes
1259 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1260 }
1261
1262 // emit the condition before doing anything with selection
1263 node->getCondition()->traverse(this);
1264
1265 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001266 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001267
1268 if (node->getTrueBlock()) {
1269 // emit the "then" statement
1270 node->getTrueBlock()->traverse(this);
1271 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001272 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001273 }
1274
1275 if (node->getFalseBlock()) {
1276 ifBuilder.makeBeginElse();
1277 // emit the "else" statement
1278 node->getFalseBlock()->traverse(this);
1279 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001280 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001281 }
1282
1283 ifBuilder.makeEndIf();
1284
1285 if (result) {
1286 // GLSL only has r-values as the result of a :?, but
1287 // if we have an l-value, that can be more efficient if it will
1288 // become the base of a complex r-value expression, because the
1289 // next layer copies r-values into memory to use the access-chain mechanism
1290 builder.clearAccessChain();
1291 builder.setAccessChainLValue(result);
1292 }
1293
1294 return false;
1295}
1296
1297bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1298{
1299 // emit and get the condition before doing anything with switch
1300 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001301 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001302
1303 // browse the children to sort out code segments
1304 int defaultSegment = -1;
1305 std::vector<TIntermNode*> codeSegments;
1306 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1307 std::vector<int> caseValues;
1308 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1309 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1310 TIntermNode* child = *c;
1311 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001312 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001313 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001314 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001315 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1316 } else
1317 codeSegments.push_back(child);
1318 }
1319
1320 // handle the case where the last code segment is missing, due to no code
1321 // statements between the last case and the end of the switch statement
1322 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1323 (int)codeSegments.size() == defaultSegment)
1324 codeSegments.push_back(nullptr);
1325
1326 // make the switch statement
1327 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001328 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 // emit all the code in the segments
1331 breakForLoop.push(false);
1332 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1333 builder.nextSwitchSegment(segmentBlocks, s);
1334 if (codeSegments[s])
1335 codeSegments[s]->traverse(this);
1336 else
1337 builder.addSwitchBreak();
1338 }
1339 breakForLoop.pop();
1340
1341 builder.endSwitch(segmentBlocks);
1342
1343 return false;
1344}
1345
1346void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1347{
1348 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001349 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001350
1351 builder.clearAccessChain();
1352 builder.setAccessChainRValue(constant);
1353}
1354
1355bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1356{
1357 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1358 loopTerminal.push(node->getTerminal());
1359
David Netoc22f37c2015-07-15 16:21:26 -04001360 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001361
1362 if (node->getTest()) {
1363 node->getTest()->traverse(this);
1364 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001365 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001366 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001367 } else {
1368 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001369 }
1370
David Netoc22f37c2015-07-15 16:21:26 -04001371 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001372 breakForLoop.push(true);
1373 node->getBody()->traverse(this);
1374 breakForLoop.pop();
1375 }
1376
1377 if (loopTerminal.top())
1378 loopTerminal.top()->traverse(this);
1379
1380 builder.closeLoop();
1381
1382 loopTerminal.pop();
1383
1384 return false;
1385}
1386
1387bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1388{
1389 if (node->getExpression())
1390 node->getExpression()->traverse(this);
1391
1392 switch (node->getFlowOp()) {
1393 case glslang::EOpKill:
1394 builder.makeDiscard();
1395 break;
1396 case glslang::EOpBreak:
1397 if (breakForLoop.top())
1398 builder.createLoopExit();
1399 else
1400 builder.addSwitchBreak();
1401 break;
1402 case glslang::EOpContinue:
1403 if (loopTerminal.top())
1404 loopTerminal.top()->traverse(this);
1405 builder.createLoopContinue();
1406 break;
1407 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001408 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001409 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001410 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001411 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001412
1413 builder.clearAccessChain();
1414 break;
1415
1416 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001417 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001418 break;
1419 }
1420
1421 return false;
1422}
1423
1424spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1425{
1426 // First, steer off constants, which are not SPIR-V variables, but
1427 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001428 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001429 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001430 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001431 }
1432
1433 // Now, handle actual variables
1434 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1435 spv::Id spvType = convertGlslangToSpvType(node->getType());
1436
1437 const char* name = node->getName().c_str();
1438 if (glslang::IsAnonymous(name))
1439 name = "";
1440
1441 return builder.createVariable(storageClass, spvType, name);
1442}
1443
1444// Return type Id of the sampled type.
1445spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1446{
1447 switch (sampler.type) {
1448 case glslang::EbtFloat: return builder.makeFloatType(32);
1449 case glslang::EbtInt: return builder.makeIntType(32);
1450 case glslang::EbtUint: return builder.makeUintType(32);
1451 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001452 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001453 return builder.makeFloatType(32);
1454 }
1455}
1456
John Kessenich3ac051e2015-12-20 11:29:16 -07001457// Convert from a glslang type to an SPV type, by calling into a
1458// recursive version of this function. This establishes the inherited
1459// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001460spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1461{
John Kessenich3ac051e2015-12-20 11:29:16 -07001462 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier().layoutMatrix);
John Kessenich31ed4832015-09-09 17:51:38 -06001463}
1464
1465// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1466// explicitLayout can be kept the same throughout the heirarchical recursive walk.
John Kessenich3ac051e2015-12-20 11:29:16 -07001467spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich31ed4832015-09-09 17:51:38 -06001468{
John Kessenich140f3df2015-06-26 16:58:36 -06001469 spv::Id spvType = 0;
1470
1471 switch (type.getBasicType()) {
1472 case glslang::EbtVoid:
1473 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001474 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001475 break;
1476 case glslang::EbtFloat:
1477 spvType = builder.makeFloatType(32);
1478 break;
1479 case glslang::EbtDouble:
1480 spvType = builder.makeFloatType(64);
1481 break;
1482 case glslang::EbtBool:
1483 spvType = builder.makeBoolType();
1484 break;
1485 case glslang::EbtInt:
1486 spvType = builder.makeIntType(32);
1487 break;
1488 case glslang::EbtUint:
1489 spvType = builder.makeUintType(32);
1490 break;
John Kessenich426394d2015-07-23 10:22:48 -06001491 case glslang::EbtAtomicUint:
1492 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1493 spvType = builder.makeUintType(32);
1494 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001495 case glslang::EbtSampler:
1496 {
1497 const glslang::TSampler& sampler = type.getSampler();
John Kessenich55e7d112015-11-15 21:33:39 -07001498 // an image is present, make its type
1499 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1500 sampler.image ? 2 : 1, TranslateImageFormat(type));
1501 if (! sampler.image) {
1502 spvType = builder.makeSampledImageType(spvType);
1503 }
1504 }
John Kessenich140f3df2015-06-26 16:58:36 -06001505 break;
1506 case glslang::EbtStruct:
1507 case glslang::EbtBlock:
1508 {
1509 // If we've seen this struct type, return it
1510 const glslang::TTypeList* glslangStruct = type.getStruct();
1511 std::vector<spv::Id> structFields;
John Kessenich3ac051e2015-12-20 11:29:16 -07001512 spvType = structMap[explicitLayout][matrixLayout][glslangStruct];
John Kessenich140f3df2015-06-26 16:58:36 -06001513 if (spvType)
1514 break;
1515
1516 // else, we haven't seen it...
1517
1518 // Create a vector of struct types for SPIR-V to consume
1519 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1520 if (type.getBasicType() == glslang::EbtBlock)
1521 memberRemapper[glslangStruct].resize(glslangStruct->size());
1522 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1523 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1524 if (glslangType.hiddenMember()) {
1525 ++memberDelta;
1526 if (type.getBasicType() == glslang::EbtBlock)
1527 memberRemapper[glslangStruct][i] = -1;
1528 } else {
1529 if (type.getBasicType() == glslang::EbtBlock)
1530 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich3ac051e2015-12-20 11:29:16 -07001531 // modify just the children's view of matrix layout, if there is one for this member
1532 glslang::TLayoutMatrix subMatrixLayout = glslangType.getQualifier().layoutMatrix;
1533 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout,
1534 subMatrixLayout != glslang::ElmNone ? subMatrixLayout : matrixLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001535 }
1536 }
1537
1538 // Make the SPIR-V type
1539 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kessenich3ac051e2015-12-20 11:29:16 -07001540 structMap[explicitLayout][matrixLayout][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001541
1542 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001543 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001544 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1545 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1546 int member = i;
1547 if (type.getBasicType() == glslang::EbtBlock)
1548 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001549
1550 // modify just the children's view of matrix layout, if there is one for this member
1551 glslang::TLayoutMatrix subMatrixLayout = glslangType.getQualifier().layoutMatrix;
1552 if (subMatrixLayout == glslang::ElmNone)
1553 subMatrixLayout = matrixLayout;
1554
John Kessenich140f3df2015-06-26 16:58:36 -06001555 // using -1 above to indicate a hidden member
1556 if (member >= 0) {
1557 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kessenich3ac051e2015-12-20 11:29:16 -07001558 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subMatrixLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001559 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1560 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1561 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1562 if (glslangType.getQualifier().hasLocation())
1563 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1564 if (glslangType.getQualifier().hasComponent())
1565 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1566 if (glslangType.getQualifier().hasXfbOffset())
1567 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001568 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001569 // figure out what to do with offset, which is accumulating
1570 int nextOffset;
John Kessenich3ac051e2015-12-20 11:29:16 -07001571 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subMatrixLayout);
John Kessenich5e4b1242015-08-06 22:53:06 -06001572 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001573 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001574 offset = nextOffset;
1575 }
John Kessenich140f3df2015-06-26 16:58:36 -06001576
John Kessenichf85e8062015-12-19 13:57:10 -07001577 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kessenich3ac051e2015-12-20 11:29:16 -07001578 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subMatrixLayout));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001579
John Kessenich140f3df2015-06-26 16:58:36 -06001580 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001581 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1582 if (builtIn != spv::BadValue)
1583 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001584 }
1585 }
1586
1587 // Decorate the structure
John Kessenich3ac051e2015-12-20 11:29:16 -07001588 addDecoration(spvType, TranslateLayoutDecoration(type, matrixLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001589 addDecoration(spvType, TranslateBlockDecoration(type));
1590 if (type.getQualifier().hasStream())
1591 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1592 if (glslangIntermediate->getXfbMode()) {
1593 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001594 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001595 if (type.getQualifier().hasXfbBuffer())
1596 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1597 }
1598 }
1599 break;
1600 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001601 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001602 break;
1603 }
1604
1605 if (type.isMatrix())
1606 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1607 else {
1608 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1609 if (type.getVectorSize() > 1)
1610 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1611 }
1612
1613 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001614 // Do all but the outer dimension
1615 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1616 assert(type.getArraySizes()->getDimSize(dim) > 0);
1617 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1618 }
John Kessenich31ed4832015-09-09 17:51:38 -06001619
John Kessenichc9a80832015-09-12 12:17:44 -06001620 // Do the outer dimension, which might not be known for a runtime-sized array
1621 if (type.isRuntimeSizedArray()) {
1622 spvType = builder.makeRuntimeArray(spvType);
1623 } else {
1624 assert(type.getOuterArraySize() > 0);
1625 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1626 }
1627
John Kessenich55e7d112015-11-15 21:33:39 -07001628 // TODO: explicit layout still needs to be done hierarchically for arrays of arrays, which
John Kessenichc9a80832015-09-12 12:17:44 -06001629 // may still require additional "link time" support from the front-end
1630 // for arrays of arrays
John Kessenich55e7d112015-11-15 21:33:39 -07001631
1632 // We need to decorate array strides for types needing explicit layout,
1633 // except for the very top if it is an array of blocks; that array is
1634 // not laid out in memory in a way needing a stride.
1635 if (explicitLayout && type.getBasicType() != glslang::EbtBlock)
John Kessenich3ac051e2015-12-20 11:29:16 -07001636 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type, explicitLayout, matrixLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001637 }
1638
1639 return spvType;
1640}
1641
John Kessenichf85e8062015-12-19 13:57:10 -07001642// Decide whether or not this type should be
1643// decorated with offsets and strides, and if so
1644// whether std140 or std430 rules should be applied.
1645glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001646{
John Kessenichf85e8062015-12-19 13:57:10 -07001647 // has to be a block
1648 if (type.getBasicType() != glslang::EbtBlock)
1649 return glslang::ElpNone;
1650
1651 // has to be a uniform or buffer block
1652 if (type.getQualifier().storage != glslang::EvqUniform &&
1653 type.getQualifier().storage != glslang::EvqBuffer)
1654 return glslang::ElpNone;
1655
1656 // return the layout to use
1657 switch (type.getQualifier().layoutPacking) {
1658 case glslang::ElpStd140:
1659 case glslang::ElpStd430:
1660 return type.getQualifier().layoutPacking;
1661 default:
1662 return glslang::ElpNone;
1663 }
John Kessenich31ed4832015-09-09 17:51:38 -06001664}
1665
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001666// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001667int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001668{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001669 int size;
John Kessenich3ac051e2015-12-20 11:29:16 -07001670 int stride = glslangIntermediate->getBaseAlignment(arrayType, size, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001671 if (arrayType.isMatrix()) {
1672 // GLSL strides are set to alignments of the matrix flattened to individual rows/cols,
1673 // but SPV needs an array stride for the whole matrix, not the rows/cols
John Kessenich3ac051e2015-12-20 11:29:16 -07001674 if (matrixLayout == glslang::ElmRowMajor)
John Kesseniche721f492015-12-06 19:17:49 -07001675 stride *= arrayType.getMatrixRows();
1676 else
1677 stride *= arrayType.getMatrixCols();
1678 }
1679
1680 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001681}
1682
1683// Given a matrix type, returns the integer stride required for that matrix
1684// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001685int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001686{
1687 int size;
John Kessenich3ac051e2015-12-20 11:29:16 -07001688 return glslangIntermediate->getBaseAlignment(matrixType, size, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001689}
1690
John Kessenich5e4b1242015-08-06 22:53:06 -06001691// Given a member type of a struct, realign the current offset for it, and compute
1692// the next (not yet aligned) offset for the next member, which will get aligned
1693// on the next call.
1694// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1695// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1696// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001697void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001698 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001699{
1700 // this will get a positive value when deemed necessary
1701 nextOffset = -1;
1702
John Kessenich5e4b1242015-08-06 22:53:06 -06001703 // override anything in currentOffset with user-set offset
1704 if (memberType.getQualifier().hasOffset())
1705 currentOffset = memberType.getQualifier().layoutOffset;
1706
1707 // It could be that current linker usage in glslang updated all the layoutOffset,
1708 // in which case the following code does not matter. But, that's not quite right
1709 // once cross-compilation unit GLSL validation is done, as the original user
1710 // settings are needed in layoutOffset, and then the following will come into play.
1711
John Kessenichf85e8062015-12-19 13:57:10 -07001712 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001713 if (! memberType.getQualifier().hasOffset())
1714 currentOffset = -1;
1715
1716 return;
1717 }
1718
John Kessenichf85e8062015-12-19 13:57:10 -07001719 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001720 if (currentOffset < 0)
1721 currentOffset = 0;
1722
1723 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1724 // but possibly not yet correctly aligned.
1725
1726 int memberSize;
John Kessenich3ac051e2015-12-20 11:29:16 -07001727 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001728 glslang::RoundToPow2(currentOffset, memberAlignment);
1729 nextOffset = currentOffset + memberSize;
1730}
1731
John Kessenich140f3df2015-06-26 16:58:36 -06001732bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1733{
1734 return node->getName() == "main(";
1735}
1736
1737// Make all the functions, skeletally, without actually visiting their bodies.
1738void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1739{
1740 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1741 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1742 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1743 continue;
1744
1745 // We're on a user function. Set up the basic interface for the function now,
1746 // so that it's available to call.
1747 // Translating the body will happen later.
1748 //
1749 // Typically (except for a "const in" parameter), an address will be passed to the
1750 // function. What it is an address of varies:
1751 //
1752 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1753 // so that write needs to be to a copy, hence the address of a copy works.
1754 //
1755 // - "const in" parameters can just be the r-value, as no writes need occur.
1756 //
1757 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1758 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1759
1760 std::vector<spv::Id> paramTypes;
1761 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1762
1763 for (int p = 0; p < (int)parameters.size(); ++p) {
1764 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1765 spv::Id typeId = convertGlslangToSpvType(paramType);
1766 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1767 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1768 else
1769 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1770 paramTypes.push_back(typeId);
1771 }
1772
1773 spv::Block* functionBlock;
1774 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1775 paramTypes, &functionBlock);
1776
1777 // Track function to emit/call later
1778 functionMap[glslFunction->getName().c_str()] = function;
1779
1780 // Set the parameter id's
1781 for (int p = 0; p < (int)parameters.size(); ++p) {
1782 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1783 // give a name too
1784 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1785 }
1786 }
1787}
1788
1789// Process all the initializers, while skipping the functions and link objects
1790void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1791{
1792 builder.setBuildPoint(shaderEntry->getLastBlock());
1793 for (int i = 0; i < (int)initializers.size(); ++i) {
1794 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1795 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1796
1797 // We're on a top-level node that's not a function. Treat as an initializer, whose
1798 // code goes into the beginning of main.
1799 initializer->traverse(this);
1800 }
1801 }
1802}
1803
1804// Process all the functions, while skipping initializers.
1805void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1806{
1807 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1808 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1809 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1810 node->traverse(this);
1811 }
1812}
1813
1814void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1815{
1816 // SPIR-V functions should already be in the functionMap from the prepass
1817 // that called makeFunctions().
1818 spv::Function* function = functionMap[node->getName().c_str()];
1819 spv::Block* functionBlock = function->getEntryBlock();
1820 builder.setBuildPoint(functionBlock);
1821}
1822
Rex Xu04db3f52015-09-16 11:44:02 +08001823void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001824{
Rex Xufc618912015-09-09 16:42:49 +08001825 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001826 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1827 builder.clearAccessChain();
1828 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001829
1830 // Special case l-value operands
1831 bool lvalue = false;
1832 switch (node.getOp()) {
1833 case glslang::EOpImageAtomicAdd:
1834 case glslang::EOpImageAtomicMin:
1835 case glslang::EOpImageAtomicMax:
1836 case glslang::EOpImageAtomicAnd:
1837 case glslang::EOpImageAtomicOr:
1838 case glslang::EOpImageAtomicXor:
1839 case glslang::EOpImageAtomicExchange:
1840 case glslang::EOpImageAtomicCompSwap:
1841 if (i == 0)
1842 lvalue = true;
1843 break;
1844 default:
1845 break;
1846 }
1847
Rex Xu6b86d492015-09-16 17:48:22 +08001848 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001849 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001850 else
Rex Xu30f92582015-09-14 10:38:56 +08001851 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001852 }
1853}
1854
John Kessenichfc51d282015-08-19 13:34:18 -06001855void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001856{
John Kessenichfc51d282015-08-19 13:34:18 -06001857 builder.clearAccessChain();
1858 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001859 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001860}
John Kessenich140f3df2015-06-26 16:58:36 -06001861
John Kessenichfc51d282015-08-19 13:34:18 -06001862spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1863{
Rex Xufc618912015-09-09 16:42:49 +08001864 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001865 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001866 }
1867
John Kessenichfc51d282015-08-19 13:34:18 -06001868 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001869 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1870 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1871 std::vector<spv::Id> arguments;
1872 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001873 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001874 else
1875 translateArguments(*node->getAsUnaryNode(), arguments);
1876 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1877
1878 spv::Builder::TextureParameters params = { };
1879 params.sampler = arguments[0];
1880
Rex Xu04db3f52015-09-16 11:44:02 +08001881 glslang::TCrackedTextureOp cracked;
1882 node->crackTexture(sampler, cracked);
1883
John Kessenichfc51d282015-08-19 13:34:18 -06001884 // Check for queries
1885 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07001886 // a sampled image needs to have the image extracted first
1887 if (builder.isSampledImage(params.sampler))
1888 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06001889 switch (node->getOp()) {
1890 case glslang::EOpImageQuerySize:
1891 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001892 if (arguments.size() > 1) {
1893 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001894 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001895 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001896 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001897 case glslang::EOpImageQuerySamples:
1898 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001899 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001900 case glslang::EOpTextureQueryLod:
1901 params.coords = arguments[1];
1902 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1903 case glslang::EOpTextureQueryLevels:
1904 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1905 default:
1906 assert(0);
1907 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001908 }
John Kessenich140f3df2015-06-26 16:58:36 -06001909 }
1910
Rex Xufc618912015-09-09 16:42:49 +08001911 // Check for image functions other than queries
1912 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001913 std::vector<spv::Id> operands;
1914 auto opIt = arguments.begin();
1915 operands.push_back(*(opIt++));
1916 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001917 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07001918 if (sampler.ms) {
1919 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08001920 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07001921 }
John Kessenich56bab042015-09-16 10:54:31 -06001922 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1923 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08001924 if (sampler.ms) {
1925 operands.push_back(*(opIt + 1));
1926 operands.push_back(spv::ImageOperandsSampleMask);
1927 operands.push_back(*opIt);
1928 } else
1929 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06001930 builder.createNoResultOp(spv::OpImageWrite, operands);
1931 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001932 } else {
1933 // Process image atomic operations
1934
1935 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1936 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001937 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001938
Rex Xufc618912015-09-09 16:42:49 +08001939 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001940 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001941
1942 std::vector<spv::Id> operands;
1943 operands.push_back(pointer);
1944 for (; opIt != arguments.end(); ++opIt)
1945 operands.push_back(*opIt);
1946
Rex Xu04db3f52015-09-16 11:44:02 +08001947 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001948 }
1949 }
1950
1951 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001952
Rex Xu71519fe2015-11-11 15:35:47 +08001953 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1954
John Kessenichfc51d282015-08-19 13:34:18 -06001955 // check for bias argument
1956 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08001957 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06001958 int nonBiasArgCount = 2;
1959 if (cracked.offset)
1960 ++nonBiasArgCount;
1961 if (cracked.grad)
1962 nonBiasArgCount += 2;
1963
1964 if ((int)arguments.size() > nonBiasArgCount)
1965 bias = true;
1966 }
1967
John Kessenichfc51d282015-08-19 13:34:18 -06001968 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07001969
John Kessenichfc51d282015-08-19 13:34:18 -06001970 params.coords = arguments[1];
1971 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001972
1973 // sort out where Dref is coming from
1974 if (sampler.shadow && sampler.dim == glslang::EsdCube && sampler.arrayed)
John Kessenichfc51d282015-08-19 13:34:18 -06001975 params.Dref = arguments[2];
John Kessenich55e7d112015-11-15 21:33:39 -07001976 else if (sampler.shadow && cracked.gather) {
1977 params.Dref = arguments[2];
1978 ++extraArgs;
1979 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06001980 std::vector<spv::Id> indexes;
1981 int comp;
1982 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07001983 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06001984 else
1985 comp = builder.getNumComponents(params.coords) - 1;
1986 indexes.push_back(comp);
1987 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1988 }
1989 if (cracked.lod) {
1990 params.lod = arguments[2];
1991 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08001992 } else if (sampler.ms) {
1993 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08001994 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001995 }
1996 if (cracked.grad) {
1997 params.gradX = arguments[2 + extraArgs];
1998 params.gradY = arguments[3 + extraArgs];
1999 extraArgs += 2;
2000 }
John Kessenich55e7d112015-11-15 21:33:39 -07002001 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002002 params.offset = arguments[2 + extraArgs];
2003 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002004 } else if (cracked.offsets) {
2005 params.offsets = arguments[2 + extraArgs];
2006 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002007 }
2008 if (bias) {
2009 params.bias = arguments[2 + extraArgs];
2010 ++extraArgs;
2011 }
John Kessenich55e7d112015-11-15 21:33:39 -07002012 if (cracked.gather && ! sampler.shadow) {
2013 // default component is 0, if missing, otherwise an argument
2014 if (2 + extraArgs < (int)arguments.size()) {
2015 params.comp = arguments[2 + extraArgs];
2016 ++extraArgs;
2017 } else {
2018 params.comp = builder.makeIntConstant(0);
2019 }
2020 }
John Kessenichfc51d282015-08-19 13:34:18 -06002021
John Kessenich55e7d112015-11-15 21:33:39 -07002022 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002023}
2024
2025spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2026{
2027 // Grab the function's pointer from the previously created function
2028 spv::Function* function = functionMap[node->getName().c_str()];
2029 if (! function)
2030 return 0;
2031
2032 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2033 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2034
2035 // See comments in makeFunctions() for details about the semantics for parameter passing.
2036 //
2037 // These imply we need a four step process:
2038 // 1. Evaluate the arguments
2039 // 2. Allocate and make copies of in, out, and inout arguments
2040 // 3. Make the call
2041 // 4. Copy back the results
2042
2043 // 1. Evaluate the arguments
2044 std::vector<spv::Builder::AccessChain> lValues;
2045 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002046 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002047 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2048 // build l-value
2049 builder.clearAccessChain();
2050 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002051 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002052 // keep outputs as l-values, evaluate input-only as r-values
2053 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2054 // save l-value
2055 lValues.push_back(builder.getAccessChain());
2056 } else {
2057 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002058 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002059 }
2060 }
2061
2062 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2063 // copy the original into that space.
2064 //
2065 // Also, build up the list of actual arguments to pass in for the call
2066 int lValueCount = 0;
2067 int rValueCount = 0;
2068 std::vector<spv::Id> spvArgs;
2069 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2070 spv::Id arg;
2071 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2072 // need space to hold the copy
2073 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2074 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2075 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2076 // need to copy the input into output space
2077 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002078 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002079 builder.createStore(copy, arg);
2080 }
2081 ++lValueCount;
2082 } else {
2083 arg = rValues[rValueCount];
2084 ++rValueCount;
2085 }
2086 spvArgs.push_back(arg);
2087 }
2088
2089 // 3. Make the call.
2090 spv::Id result = builder.createFunctionCall(function, spvArgs);
2091
2092 // 4. Copy back out an "out" arguments.
2093 lValueCount = 0;
2094 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2095 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2096 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2097 spv::Id copy = builder.createLoad(spvArgs[a]);
2098 builder.setAccessChain(lValues[lValueCount]);
2099 builder.accessChainStore(copy);
2100 }
2101 ++lValueCount;
2102 }
2103 }
2104
2105 return result;
2106}
2107
2108// Translate AST operation to SPV operation, already having SPV-based operands/types.
2109spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2110 spv::Id typeId, spv::Id left, spv::Id right,
2111 glslang::TBasicType typeProxy, bool reduceComparison)
2112{
2113 bool isUnsigned = typeProxy == glslang::EbtUint;
2114 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2115
2116 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002117 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002118 bool comparison = false;
2119
2120 switch (op) {
2121 case glslang::EOpAdd:
2122 case glslang::EOpAddAssign:
2123 if (isFloat)
2124 binOp = spv::OpFAdd;
2125 else
2126 binOp = spv::OpIAdd;
2127 break;
2128 case glslang::EOpSub:
2129 case glslang::EOpSubAssign:
2130 if (isFloat)
2131 binOp = spv::OpFSub;
2132 else
2133 binOp = spv::OpISub;
2134 break;
2135 case glslang::EOpMul:
2136 case glslang::EOpMulAssign:
2137 if (isFloat)
2138 binOp = spv::OpFMul;
2139 else
2140 binOp = spv::OpIMul;
2141 break;
2142 case glslang::EOpVectorTimesScalar:
2143 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002144 if (isFloat) {
2145 if (builder.isVector(right))
2146 std::swap(left, right);
2147 assert(builder.isScalar(right));
2148 needMatchingVectors = false;
2149 binOp = spv::OpVectorTimesScalar;
2150 } else
2151 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002152 break;
2153 case glslang::EOpVectorTimesMatrix:
2154 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002155 binOp = spv::OpVectorTimesMatrix;
2156 break;
2157 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002158 binOp = spv::OpMatrixTimesVector;
2159 break;
2160 case glslang::EOpMatrixTimesScalar:
2161 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002162 binOp = spv::OpMatrixTimesScalar;
2163 break;
2164 case glslang::EOpMatrixTimesMatrix:
2165 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002166 binOp = spv::OpMatrixTimesMatrix;
2167 break;
2168 case glslang::EOpOuterProduct:
2169 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002170 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002171 break;
2172
2173 case glslang::EOpDiv:
2174 case glslang::EOpDivAssign:
2175 if (isFloat)
2176 binOp = spv::OpFDiv;
2177 else if (isUnsigned)
2178 binOp = spv::OpUDiv;
2179 else
2180 binOp = spv::OpSDiv;
2181 break;
2182 case glslang::EOpMod:
2183 case glslang::EOpModAssign:
2184 if (isFloat)
2185 binOp = spv::OpFMod;
2186 else if (isUnsigned)
2187 binOp = spv::OpUMod;
2188 else
2189 binOp = spv::OpSMod;
2190 break;
2191 case glslang::EOpRightShift:
2192 case glslang::EOpRightShiftAssign:
2193 if (isUnsigned)
2194 binOp = spv::OpShiftRightLogical;
2195 else
2196 binOp = spv::OpShiftRightArithmetic;
2197 break;
2198 case glslang::EOpLeftShift:
2199 case glslang::EOpLeftShiftAssign:
2200 binOp = spv::OpShiftLeftLogical;
2201 break;
2202 case glslang::EOpAnd:
2203 case glslang::EOpAndAssign:
2204 binOp = spv::OpBitwiseAnd;
2205 break;
2206 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002207 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002208 binOp = spv::OpLogicalAnd;
2209 break;
2210 case glslang::EOpInclusiveOr:
2211 case glslang::EOpInclusiveOrAssign:
2212 binOp = spv::OpBitwiseOr;
2213 break;
2214 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002215 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002216 binOp = spv::OpLogicalOr;
2217 break;
2218 case glslang::EOpExclusiveOr:
2219 case glslang::EOpExclusiveOrAssign:
2220 binOp = spv::OpBitwiseXor;
2221 break;
2222 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002223 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002224 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002225 break;
2226
2227 case glslang::EOpLessThan:
2228 case glslang::EOpGreaterThan:
2229 case glslang::EOpLessThanEqual:
2230 case glslang::EOpGreaterThanEqual:
2231 case glslang::EOpEqual:
2232 case glslang::EOpNotEqual:
2233 case glslang::EOpVectorEqual:
2234 case glslang::EOpVectorNotEqual:
2235 comparison = true;
2236 break;
2237 default:
2238 break;
2239 }
2240
John Kessenich7c1aa102015-10-15 13:29:11 -06002241 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002242 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002243 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002244 if (builder.isMatrix(left) || builder.isMatrix(right))
2245 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002246
2247 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002248 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002249 builder.promoteScalar(precision, left, right);
2250
2251 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2252 builder.setPrecision(id, precision);
2253
2254 return id;
2255 }
2256
2257 if (! comparison)
2258 return 0;
2259
John Kessenich7c1aa102015-10-15 13:29:11 -06002260 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002261
2262 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2263 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2264
2265 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2266 }
2267
2268 switch (op) {
2269 case glslang::EOpLessThan:
2270 if (isFloat)
2271 binOp = spv::OpFOrdLessThan;
2272 else if (isUnsigned)
2273 binOp = spv::OpULessThan;
2274 else
2275 binOp = spv::OpSLessThan;
2276 break;
2277 case glslang::EOpGreaterThan:
2278 if (isFloat)
2279 binOp = spv::OpFOrdGreaterThan;
2280 else if (isUnsigned)
2281 binOp = spv::OpUGreaterThan;
2282 else
2283 binOp = spv::OpSGreaterThan;
2284 break;
2285 case glslang::EOpLessThanEqual:
2286 if (isFloat)
2287 binOp = spv::OpFOrdLessThanEqual;
2288 else if (isUnsigned)
2289 binOp = spv::OpULessThanEqual;
2290 else
2291 binOp = spv::OpSLessThanEqual;
2292 break;
2293 case glslang::EOpGreaterThanEqual:
2294 if (isFloat)
2295 binOp = spv::OpFOrdGreaterThanEqual;
2296 else if (isUnsigned)
2297 binOp = spv::OpUGreaterThanEqual;
2298 else
2299 binOp = spv::OpSGreaterThanEqual;
2300 break;
2301 case glslang::EOpEqual:
2302 case glslang::EOpVectorEqual:
2303 if (isFloat)
2304 binOp = spv::OpFOrdEqual;
2305 else
2306 binOp = spv::OpIEqual;
2307 break;
2308 case glslang::EOpNotEqual:
2309 case glslang::EOpVectorNotEqual:
2310 if (isFloat)
2311 binOp = spv::OpFOrdNotEqual;
2312 else
2313 binOp = spv::OpINotEqual;
2314 break;
2315 default:
2316 break;
2317 }
2318
2319 if (binOp != spv::OpNop) {
2320 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2321 builder.setPrecision(id, precision);
2322
2323 return id;
2324 }
2325
2326 return 0;
2327}
2328
John Kessenich04bb8a02015-12-12 12:28:14 -07002329//
2330// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2331// These can be any of:
2332//
2333// matrix * scalar
2334// scalar * matrix
2335// matrix * matrix linear algebraic
2336// matrix * vector
2337// vector * matrix
2338// matrix * matrix componentwise
2339// matrix op matrix op in {+, -, /}
2340// matrix op scalar op in {+, -, /}
2341// scalar op matrix op in {+, -, /}
2342//
2343spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2344{
2345 bool firstClass = true;
2346
2347 // First, handle first-class matrix operations (* and matrix/scalar)
2348 switch (op) {
2349 case spv::OpFDiv:
2350 if (builder.isMatrix(left) && builder.isScalar(right)) {
2351 // turn matrix / scalar into a multiply...
2352 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2353 op = spv::OpMatrixTimesScalar;
2354 } else
2355 firstClass = false;
2356 break;
2357 case spv::OpMatrixTimesScalar:
2358 if (builder.isMatrix(right))
2359 std::swap(left, right);
2360 assert(builder.isScalar(right));
2361 break;
2362 case spv::OpVectorTimesMatrix:
2363 assert(builder.isVector(left));
2364 assert(builder.isMatrix(right));
2365 break;
2366 case spv::OpMatrixTimesVector:
2367 assert(builder.isMatrix(left));
2368 assert(builder.isVector(right));
2369 break;
2370 case spv::OpMatrixTimesMatrix:
2371 assert(builder.isMatrix(left));
2372 assert(builder.isMatrix(right));
2373 break;
2374 default:
2375 firstClass = false;
2376 break;
2377 }
2378
2379 if (firstClass) {
2380 spv::Id id = builder.createBinOp(op, typeId, left, right);
2381 builder.setPrecision(id, precision);
2382
2383 return id;
2384 }
2385
2386 // Handle component-wise +, -, *, and / for all combinations of type.
2387 // The result type of all of them is the same type as the (a) matrix operand.
2388 // The algorithm is to:
2389 // - break the matrix(es) into vectors
2390 // - smear any scalar to a vector
2391 // - do vector operations
2392 // - make a matrix out the vector results
2393 switch (op) {
2394 case spv::OpFAdd:
2395 case spv::OpFSub:
2396 case spv::OpFDiv:
2397 case spv::OpFMul:
2398 {
2399 // one time set up...
2400 bool leftMat = builder.isMatrix(left);
2401 bool rightMat = builder.isMatrix(right);
2402 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2403 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2404 spv::Id scalarType = builder.getScalarTypeId(typeId);
2405 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2406 std::vector<spv::Id> results;
2407 spv::Id smearVec = spv::NoResult;
2408 if (builder.isScalar(left))
2409 smearVec = builder.smearScalar(precision, left, vecType);
2410 else if (builder.isScalar(right))
2411 smearVec = builder.smearScalar(precision, right, vecType);
2412
2413 // do each vector op
2414 for (unsigned int c = 0; c < numCols; ++c) {
2415 std::vector<unsigned int> indexes;
2416 indexes.push_back(c);
2417 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2418 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2419 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2420 builder.setPrecision(results.back(), precision);
2421 }
2422
2423 // put the pieces together
2424 spv::Id id = builder.createCompositeConstruct(typeId, results);
2425 builder.setPrecision(id, precision);
2426 return id;
2427 }
2428 default:
2429 assert(0);
2430 return spv::NoResult;
2431 }
2432}
2433
Rex Xu04db3f52015-09-16 11:44:02 +08002434spv::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 -06002435{
2436 spv::Op unaryOp = spv::OpNop;
2437 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002438 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002439 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002440
2441 switch (op) {
2442 case glslang::EOpNegative:
2443 if (isFloat)
2444 unaryOp = spv::OpFNegate;
2445 else
2446 unaryOp = spv::OpSNegate;
2447 break;
2448
2449 case glslang::EOpLogicalNot:
2450 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002451 unaryOp = spv::OpLogicalNot;
2452 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002453 case glslang::EOpBitwiseNot:
2454 unaryOp = spv::OpNot;
2455 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002456
John Kessenich140f3df2015-06-26 16:58:36 -06002457 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002458 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002459 break;
2460 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002461 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002462 break;
2463 case glslang::EOpTranspose:
2464 unaryOp = spv::OpTranspose;
2465 break;
2466
2467 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002468 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002469 break;
2470 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002471 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002472 break;
2473 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002474 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002475 break;
2476 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002477 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002478 break;
2479 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002480 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002481 break;
2482 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002483 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002484 break;
2485 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002486 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002487 break;
2488 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002489 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002490 break;
2491
2492 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002493 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002494 break;
2495 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002496 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002497 break;
2498 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002499 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002500 break;
2501 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002502 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002503 break;
2504 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002505 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002506 break;
2507 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002508 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002509 break;
2510
2511 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002512 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002513 break;
2514 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002515 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002516 break;
2517
2518 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002519 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002520 break;
2521 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002522 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002523 break;
2524 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002525 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002526 break;
2527 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002528 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002529 break;
2530 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002531 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002532 break;
2533 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002534 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002535 break;
2536
2537 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002538 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002539 break;
2540 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002541 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002542 break;
2543 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002544 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002545 break;
2546 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002547 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002548 break;
2549 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002550 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002551 break;
2552 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002553 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002554 break;
2555
2556 case glslang::EOpIsNan:
2557 unaryOp = spv::OpIsNan;
2558 break;
2559 case glslang::EOpIsInf:
2560 unaryOp = spv::OpIsInf;
2561 break;
2562
Rex Xucbc426e2015-12-15 16:03:10 +08002563 case glslang::EOpFloatBitsToInt:
2564 case glslang::EOpFloatBitsToUint:
2565 case glslang::EOpIntBitsToFloat:
2566 case glslang::EOpUintBitsToFloat:
2567 unaryOp = spv::OpBitcast;
2568 break;
2569
John Kessenich140f3df2015-06-26 16:58:36 -06002570 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002571 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002572 break;
2573 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002574 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002575 break;
2576 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002577 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002578 break;
2579 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002580 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002581 break;
2582 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002583 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002584 break;
2585 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002586 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002587 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002588 case glslang::EOpPackSnorm4x8:
2589 libCall = spv::GLSLstd450PackSnorm4x8;
2590 break;
2591 case glslang::EOpUnpackSnorm4x8:
2592 libCall = spv::GLSLstd450UnpackSnorm4x8;
2593 break;
2594 case glslang::EOpPackUnorm4x8:
2595 libCall = spv::GLSLstd450PackUnorm4x8;
2596 break;
2597 case glslang::EOpUnpackUnorm4x8:
2598 libCall = spv::GLSLstd450UnpackUnorm4x8;
2599 break;
2600 case glslang::EOpPackDouble2x32:
2601 libCall = spv::GLSLstd450PackDouble2x32;
2602 break;
2603 case glslang::EOpUnpackDouble2x32:
2604 libCall = spv::GLSLstd450UnpackDouble2x32;
2605 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002606
2607 case glslang::EOpDPdx:
2608 unaryOp = spv::OpDPdx;
2609 break;
2610 case glslang::EOpDPdy:
2611 unaryOp = spv::OpDPdy;
2612 break;
2613 case glslang::EOpFwidth:
2614 unaryOp = spv::OpFwidth;
2615 break;
2616 case glslang::EOpDPdxFine:
2617 unaryOp = spv::OpDPdxFine;
2618 break;
2619 case glslang::EOpDPdyFine:
2620 unaryOp = spv::OpDPdyFine;
2621 break;
2622 case glslang::EOpFwidthFine:
2623 unaryOp = spv::OpFwidthFine;
2624 break;
2625 case glslang::EOpDPdxCoarse:
2626 unaryOp = spv::OpDPdxCoarse;
2627 break;
2628 case glslang::EOpDPdyCoarse:
2629 unaryOp = spv::OpDPdyCoarse;
2630 break;
2631 case glslang::EOpFwidthCoarse:
2632 unaryOp = spv::OpFwidthCoarse;
2633 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002634 case glslang::EOpInterpolateAtCentroid:
2635 libCall = spv::GLSLstd450InterpolateAtCentroid;
2636 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002637 case glslang::EOpAny:
2638 unaryOp = spv::OpAny;
2639 break;
2640 case glslang::EOpAll:
2641 unaryOp = spv::OpAll;
2642 break;
2643
2644 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002645 if (isFloat)
2646 libCall = spv::GLSLstd450FAbs;
2647 else
2648 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002649 break;
2650 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002651 if (isFloat)
2652 libCall = spv::GLSLstd450FSign;
2653 else
2654 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002655 break;
2656
John Kessenichfc51d282015-08-19 13:34:18 -06002657 case glslang::EOpAtomicCounterIncrement:
2658 case glslang::EOpAtomicCounterDecrement:
2659 case glslang::EOpAtomicCounter:
2660 {
2661 // Handle all of the atomics in one place, in createAtomicOperation()
2662 std::vector<spv::Id> operands;
2663 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002664 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002665 }
2666
2667 case glslang::EOpImageLoad:
2668 unaryOp = spv::OpImageRead;
2669 break;
2670
2671 case glslang::EOpBitFieldReverse:
2672 unaryOp = spv::OpBitReverse;
2673 break;
2674 case glslang::EOpBitCount:
2675 unaryOp = spv::OpBitCount;
2676 break;
2677 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002678 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002679 break;
2680 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002681 if (isUnsigned)
2682 libCall = spv::GLSLstd450FindUMsb;
2683 else
2684 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002685 break;
2686
John Kessenich140f3df2015-06-26 16:58:36 -06002687 default:
2688 return 0;
2689 }
2690
2691 spv::Id id;
2692 if (libCall >= 0) {
2693 std::vector<spv::Id> args;
2694 args.push_back(operand);
2695 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2696 } else
2697 id = builder.createUnaryOp(unaryOp, typeId, operand);
2698
2699 builder.setPrecision(id, precision);
2700
2701 return id;
2702}
2703
2704spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2705{
2706 spv::Op convOp = spv::OpNop;
2707 spv::Id zero = 0;
2708 spv::Id one = 0;
2709
2710 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2711
2712 switch (op) {
2713 case glslang::EOpConvIntToBool:
2714 case glslang::EOpConvUintToBool:
2715 zero = builder.makeUintConstant(0);
2716 zero = makeSmearedConstant(zero, vectorSize);
2717 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2718
2719 case glslang::EOpConvFloatToBool:
2720 zero = builder.makeFloatConstant(0.0F);
2721 zero = makeSmearedConstant(zero, vectorSize);
2722 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2723
2724 case glslang::EOpConvDoubleToBool:
2725 zero = builder.makeDoubleConstant(0.0);
2726 zero = makeSmearedConstant(zero, vectorSize);
2727 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2728
2729 case glslang::EOpConvBoolToFloat:
2730 convOp = spv::OpSelect;
2731 zero = builder.makeFloatConstant(0.0);
2732 one = builder.makeFloatConstant(1.0);
2733 break;
2734 case glslang::EOpConvBoolToDouble:
2735 convOp = spv::OpSelect;
2736 zero = builder.makeDoubleConstant(0.0);
2737 one = builder.makeDoubleConstant(1.0);
2738 break;
2739 case glslang::EOpConvBoolToInt:
2740 zero = builder.makeIntConstant(0);
2741 one = builder.makeIntConstant(1);
2742 convOp = spv::OpSelect;
2743 break;
2744 case glslang::EOpConvBoolToUint:
2745 zero = builder.makeUintConstant(0);
2746 one = builder.makeUintConstant(1);
2747 convOp = spv::OpSelect;
2748 break;
2749
2750 case glslang::EOpConvIntToFloat:
2751 case glslang::EOpConvIntToDouble:
2752 convOp = spv::OpConvertSToF;
2753 break;
2754
2755 case glslang::EOpConvUintToFloat:
2756 case glslang::EOpConvUintToDouble:
2757 convOp = spv::OpConvertUToF;
2758 break;
2759
2760 case glslang::EOpConvDoubleToFloat:
2761 case glslang::EOpConvFloatToDouble:
2762 convOp = spv::OpFConvert;
2763 break;
2764
2765 case glslang::EOpConvFloatToInt:
2766 case glslang::EOpConvDoubleToInt:
2767 convOp = spv::OpConvertFToS;
2768 break;
2769
2770 case glslang::EOpConvUintToInt:
2771 case glslang::EOpConvIntToUint:
2772 convOp = spv::OpBitcast;
2773 break;
2774
2775 case glslang::EOpConvFloatToUint:
2776 case glslang::EOpConvDoubleToUint:
2777 convOp = spv::OpConvertFToU;
2778 break;
2779 default:
2780 break;
2781 }
2782
2783 spv::Id result = 0;
2784 if (convOp == spv::OpNop)
2785 return result;
2786
2787 if (convOp == spv::OpSelect) {
2788 zero = makeSmearedConstant(zero, vectorSize);
2789 one = makeSmearedConstant(one, vectorSize);
2790 result = builder.createTriOp(convOp, destType, operand, one, zero);
2791 } else
2792 result = builder.createUnaryOp(convOp, destType, operand);
2793
2794 builder.setPrecision(result, precision);
2795
2796 return result;
2797}
2798
2799spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2800{
2801 if (vectorSize == 0)
2802 return constant;
2803
2804 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2805 std::vector<spv::Id> components;
2806 for (int c = 0; c < vectorSize; ++c)
2807 components.push_back(constant);
2808 return builder.makeCompositeConstant(vectorTypeId, components);
2809}
2810
John Kessenich426394d2015-07-23 10:22:48 -06002811// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002812spv::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 -06002813{
2814 spv::Op opCode = spv::OpNop;
2815
2816 switch (op) {
2817 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002818 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002819 opCode = spv::OpAtomicIAdd;
2820 break;
2821 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002822 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002823 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002824 break;
2825 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002826 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002827 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002828 break;
2829 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002830 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002831 opCode = spv::OpAtomicAnd;
2832 break;
2833 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002834 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002835 opCode = spv::OpAtomicOr;
2836 break;
2837 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002838 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002839 opCode = spv::OpAtomicXor;
2840 break;
2841 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002842 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002843 opCode = spv::OpAtomicExchange;
2844 break;
2845 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002846 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002847 opCode = spv::OpAtomicCompareExchange;
2848 break;
2849 case glslang::EOpAtomicCounterIncrement:
2850 opCode = spv::OpAtomicIIncrement;
2851 break;
2852 case glslang::EOpAtomicCounterDecrement:
2853 opCode = spv::OpAtomicIDecrement;
2854 break;
2855 case glslang::EOpAtomicCounter:
2856 opCode = spv::OpAtomicLoad;
2857 break;
2858 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002859 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06002860 break;
2861 }
2862
2863 // Sort out the operands
2864 // - mapping from glslang -> SPV
2865 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002866 // - compare-exchange swaps the value and comparator
2867 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002868 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2869 auto opIt = operands.begin(); // walk the glslang operands
2870 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002871 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2872 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2873 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002874 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2875 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002876 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002877 spvAtomicOperands.push_back(*(opIt + 1));
2878 spvAtomicOperands.push_back(*opIt);
2879 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002880 }
John Kessenich426394d2015-07-23 10:22:48 -06002881
John Kessenich3e60a6f2015-09-14 22:45:16 -06002882 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002883 for (; opIt != operands.end(); ++opIt)
2884 spvAtomicOperands.push_back(*opIt);
2885
2886 return builder.createOp(opCode, typeId, spvAtomicOperands);
2887}
2888
John Kessenich5e4b1242015-08-06 22:53:06 -06002889spv::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 -06002890{
John Kessenich5e4b1242015-08-06 22:53:06 -06002891 bool isUnsigned = typeProxy == glslang::EbtUint;
2892 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2893
John Kessenich140f3df2015-06-26 16:58:36 -06002894 spv::Op opCode = spv::OpNop;
2895 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002896 int consumedOperands = operands.size();
2897 spv::Id typeId0 = 0;
2898 if (consumedOperands > 0)
2899 typeId0 = builder.getTypeId(operands[0]);
2900 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002901
2902 switch (op) {
2903 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002904 if (isFloat)
2905 libCall = spv::GLSLstd450FMin;
2906 else if (isUnsigned)
2907 libCall = spv::GLSLstd450UMin;
2908 else
2909 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002910 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002911 break;
2912 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002913 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002914 break;
2915 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002916 if (isFloat)
2917 libCall = spv::GLSLstd450FMax;
2918 else if (isUnsigned)
2919 libCall = spv::GLSLstd450UMax;
2920 else
2921 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002922 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002923 break;
2924 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002925 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002926 break;
2927 case glslang::EOpDot:
2928 opCode = spv::OpDot;
2929 break;
2930 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002931 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002932 break;
2933
2934 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002935 if (isFloat)
2936 libCall = spv::GLSLstd450FClamp;
2937 else if (isUnsigned)
2938 libCall = spv::GLSLstd450UClamp;
2939 else
2940 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002941 builder.promoteScalar(precision, operands.front(), operands[1]);
2942 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002943 break;
2944 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07002945 if (isFloat)
2946 libCall = spv::GLSLstd450FMix;
2947 else
2948 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002949 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002950 break;
2951 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002952 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002953 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002954 break;
2955 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002956 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002957 builder.promoteScalar(precision, operands[0], operands[2]);
2958 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002959 break;
2960
2961 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002962 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002963 break;
2964 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002965 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002966 break;
2967 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002968 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002969 break;
2970 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002971 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002972 break;
2973 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002974 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002975 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002976 case glslang::EOpInterpolateAtSample:
2977 libCall = spv::GLSLstd450InterpolateAtSample;
2978 break;
2979 case glslang::EOpInterpolateAtOffset:
2980 libCall = spv::GLSLstd450InterpolateAtOffset;
2981 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002982 case glslang::EOpAddCarry:
2983 opCode = spv::OpIAddCarry;
2984 typeId = builder.makeStructResultType(typeId0, typeId0);
2985 consumedOperands = 2;
2986 break;
2987 case glslang::EOpSubBorrow:
2988 opCode = spv::OpISubBorrow;
2989 typeId = builder.makeStructResultType(typeId0, typeId0);
2990 consumedOperands = 2;
2991 break;
2992 case glslang::EOpUMulExtended:
2993 opCode = spv::OpUMulExtended;
2994 typeId = builder.makeStructResultType(typeId0, typeId0);
2995 consumedOperands = 2;
2996 break;
2997 case glslang::EOpIMulExtended:
2998 opCode = spv::OpSMulExtended;
2999 typeId = builder.makeStructResultType(typeId0, typeId0);
3000 consumedOperands = 2;
3001 break;
3002 case glslang::EOpBitfieldExtract:
3003 if (isUnsigned)
3004 opCode = spv::OpBitFieldUExtract;
3005 else
3006 opCode = spv::OpBitFieldSExtract;
3007 break;
3008 case glslang::EOpBitfieldInsert:
3009 opCode = spv::OpBitFieldInsert;
3010 break;
3011
3012 case glslang::EOpFma:
3013 libCall = spv::GLSLstd450Fma;
3014 break;
3015 case glslang::EOpFrexp:
3016 libCall = spv::GLSLstd450FrexpStruct;
3017 if (builder.getNumComponents(operands[0]) == 1)
3018 frexpIntType = builder.makeIntegerType(32, true);
3019 else
3020 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3021 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3022 consumedOperands = 1;
3023 break;
3024 case glslang::EOpLdexp:
3025 libCall = spv::GLSLstd450Ldexp;
3026 break;
3027
John Kessenich140f3df2015-06-26 16:58:36 -06003028 default:
3029 return 0;
3030 }
3031
3032 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003033 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003034 // Use an extended instruction from the standard library.
3035 // Construct the call arguments, without modifying the original operands vector.
3036 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3037 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
3038 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003039 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003040 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003041 case 0:
3042 // should all be handled by visitAggregate and createNoArgOperation
3043 assert(0);
3044 return 0;
3045 case 1:
3046 // should all be handled by createUnaryOperation
3047 assert(0);
3048 return 0;
3049 case 2:
3050 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3051 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003052 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003053 // anything 3 or over doesn't have l-value operands, so all should be consumed
3054 assert(consumedOperands == operands.size());
3055 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003056 break;
3057 }
3058 }
3059
John Kessenich55e7d112015-11-15 21:33:39 -07003060 // Decode the return types that were structures
3061 switch (op) {
3062 case glslang::EOpAddCarry:
3063 case glslang::EOpSubBorrow:
3064 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3065 id = builder.createCompositeExtract(id, typeId0, 0);
3066 break;
3067 case glslang::EOpUMulExtended:
3068 case glslang::EOpIMulExtended:
3069 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3070 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3071 break;
3072 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003073 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003074 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3075 id = builder.createCompositeExtract(id, typeId0, 0);
3076 break;
3077 default:
3078 break;
3079 }
3080
John Kessenich140f3df2015-06-26 16:58:36 -06003081 builder.setPrecision(id, precision);
3082
3083 return id;
3084}
3085
3086// Intrinsics with no arguments, no return value, and no precision.
3087spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3088{
3089 // TODO: get the barrier operands correct
3090
3091 switch (op) {
3092 case glslang::EOpEmitVertex:
3093 builder.createNoResultOp(spv::OpEmitVertex);
3094 return 0;
3095 case glslang::EOpEndPrimitive:
3096 builder.createNoResultOp(spv::OpEndPrimitive);
3097 return 0;
3098 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003099 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3100 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003101 return 0;
3102 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003103 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003104 return 0;
3105 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003106 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003107 return 0;
3108 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003109 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003110 return 0;
3111 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003112 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003113 return 0;
3114 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003115 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003116 return 0;
3117 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003118 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003119 return 0;
3120 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003121 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003122 return 0;
3123 }
3124}
3125
3126spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3127{
John Kessenich2f273362015-07-18 22:34:27 -06003128 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003129 spv::Id id;
3130 if (symbolValues.end() != iter) {
3131 id = iter->second;
3132 return id;
3133 }
3134
3135 // it was not found, create it
3136 id = createSpvVariable(symbol);
3137 symbolValues[symbol->getId()] = id;
3138
3139 if (! symbol->getType().isStruct()) {
3140 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
3141 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
3142 if (symbol->getQualifier().hasLocation())
3143 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3144 if (symbol->getQualifier().hasIndex())
3145 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3146 if (symbol->getQualifier().hasComponent())
3147 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3148 if (glslangIntermediate->getXfbMode()) {
3149 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003150 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003151 if (symbol->getQualifier().hasXfbBuffer())
3152 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3153 if (symbol->getQualifier().hasXfbOffset())
3154 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3155 }
3156 }
3157
3158 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
3159 if (symbol->getQualifier().hasStream())
3160 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3161 if (symbol->getQualifier().hasSet())
3162 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3163 if (symbol->getQualifier().hasBinding())
3164 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3165 if (glslangIntermediate->getXfbMode()) {
3166 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003167 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003168 if (symbol->getQualifier().hasXfbBuffer())
3169 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3170 }
3171
3172 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003173 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003174 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003175 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003176
John Kessenich140f3df2015-06-26 16:58:36 -06003177 return id;
3178}
3179
John Kessenich55e7d112015-11-15 21:33:39 -07003180// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003181void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3182{
3183 if (dec != spv::BadValue)
3184 builder.addDecoration(id, dec);
3185}
3186
John Kessenich55e7d112015-11-15 21:33:39 -07003187// If 'dec' is valid, add a one-operand decoration to an object
3188void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3189{
3190 if (dec != spv::BadValue)
3191 builder.addDecoration(id, dec, value);
3192}
3193
3194// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003195void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3196{
3197 if (dec != spv::BadValue)
3198 builder.addMemberDecoration(id, (unsigned)member, dec);
3199}
3200
John Kessenich55e7d112015-11-15 21:33:39 -07003201// Make a full tree of instructions to build a SPIR-V specialization constant,
3202// or regularly constant if possible.
3203//
3204// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3205//
3206// Recursively walk the nodes. The nodes form a tree whose leaves are
3207// regular constants, which themselves are trees that createSpvConstant()
3208// recursively walks. So, this function walks the "top" of the tree:
3209// - emit specialization constant-building instructions for specConstant
3210// - when running into a non-spec-constant, switch to createSpvConstant()
3211spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3212{
3213 assert(node.getQualifier().storage == glslang::EvqConst);
3214
3215 // hand off to the non-spec-constant path
3216 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3217 int nextConst = 0;
3218 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3219}
3220
John Kessenich140f3df2015-06-26 16:58:36 -06003221// Use 'consts' as the flattened glslang source of scalar constants to recursively
3222// build the aggregate SPIR-V constant.
3223//
3224// If there are not enough elements present in 'consts', 0 will be substituted;
3225// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3226//
John Kessenich55e7d112015-11-15 21:33:39 -07003227spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003228{
3229 // vector of constants for SPIR-V
3230 std::vector<spv::Id> spvConsts;
3231
3232 // Type is used for struct and array constants
3233 spv::Id typeId = convertGlslangToSpvType(glslangType);
3234
3235 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003236 glslang::TType elementType(glslangType, 0);
3237 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003238 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003239 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003240 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003241 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003242 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003243 } else if (glslangType.getStruct()) {
3244 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3245 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003246 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003247 } else if (glslangType.isVector()) {
3248 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3249 bool zero = nextConst >= consts.size();
3250 switch (glslangType.getBasicType()) {
3251 case glslang::EbtInt:
3252 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3253 break;
3254 case glslang::EbtUint:
3255 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3256 break;
3257 case glslang::EbtFloat:
3258 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3259 break;
3260 case glslang::EbtDouble:
3261 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3262 break;
3263 case glslang::EbtBool:
3264 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3265 break;
3266 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003267 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003268 break;
3269 }
3270 ++nextConst;
3271 }
3272 } else {
3273 // we have a non-aggregate (scalar) constant
3274 bool zero = nextConst >= consts.size();
3275 spv::Id scalar = 0;
3276 switch (glslangType.getBasicType()) {
3277 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003278 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003279 break;
3280 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003281 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003282 break;
3283 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003284 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003285 break;
3286 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003287 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003288 break;
3289 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003290 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003291 break;
3292 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003294 break;
3295 }
3296 ++nextConst;
3297 return scalar;
3298 }
3299
3300 return builder.makeCompositeConstant(typeId, spvConsts);
3301}
3302
John Kessenich7c1aa102015-10-15 13:29:11 -06003303// Return true if the node is a constant or symbol whose reading has no
3304// non-trivial observable cost or effect.
3305bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3306{
3307 // don't know what this is
3308 if (node == nullptr)
3309 return false;
3310
3311 // a constant is safe
3312 if (node->getAsConstantUnion() != nullptr)
3313 return true;
3314
3315 // not a symbol means non-trivial
3316 if (node->getAsSymbolNode() == nullptr)
3317 return false;
3318
3319 // a symbol, depends on what's being read
3320 switch (node->getType().getQualifier().storage) {
3321 case glslang::EvqTemporary:
3322 case glslang::EvqGlobal:
3323 case glslang::EvqIn:
3324 case glslang::EvqInOut:
3325 case glslang::EvqConst:
3326 case glslang::EvqConstReadOnly:
3327 case glslang::EvqUniform:
3328 return true;
3329 default:
3330 return false;
3331 }
3332}
3333
3334// A node is trivial if it is a single operation with no side effects.
3335// Error on the side of saying non-trivial.
3336// Return true if trivial.
3337bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3338{
3339 if (node == nullptr)
3340 return false;
3341
3342 // symbols and constants are trivial
3343 if (isTrivialLeaf(node))
3344 return true;
3345
3346 // otherwise, it needs to be a simple operation or one or two leaf nodes
3347
3348 // not a simple operation
3349 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3350 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3351 if (binaryNode == nullptr && unaryNode == nullptr)
3352 return false;
3353
3354 // not on leaf nodes
3355 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3356 return false;
3357
3358 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3359 return false;
3360 }
3361
3362 switch (node->getAsOperator()->getOp()) {
3363 case glslang::EOpLogicalNot:
3364 case glslang::EOpConvIntToBool:
3365 case glslang::EOpConvUintToBool:
3366 case glslang::EOpConvFloatToBool:
3367 case glslang::EOpConvDoubleToBool:
3368 case glslang::EOpEqual:
3369 case glslang::EOpNotEqual:
3370 case glslang::EOpLessThan:
3371 case glslang::EOpGreaterThan:
3372 case glslang::EOpLessThanEqual:
3373 case glslang::EOpGreaterThanEqual:
3374 case glslang::EOpIndexDirect:
3375 case glslang::EOpIndexDirectStruct:
3376 case glslang::EOpLogicalXor:
3377 case glslang::EOpAny:
3378 case glslang::EOpAll:
3379 return true;
3380 default:
3381 return false;
3382 }
3383}
3384
3385// Emit short-circuiting code, where 'right' is never evaluated unless
3386// the left side is true (for &&) or false (for ||).
3387spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3388{
3389 spv::Id boolTypeId = builder.makeBoolType();
3390
3391 // emit left operand
3392 builder.clearAccessChain();
3393 left.traverse(this);
3394 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3395
3396 // Operands to accumulate OpPhi operands
3397 std::vector<spv::Id> phiOperands;
3398 // accumulate left operand's phi information
3399 phiOperands.push_back(leftId);
3400 phiOperands.push_back(builder.getBuildPoint()->getId());
3401
3402 // Make the two kinds of operation symmetric with a "!"
3403 // || => emit "if (! left) result = right"
3404 // && => emit "if ( left) result = right"
3405 //
3406 // TODO: this runtime "not" for || could be avoided by adding functionality
3407 // to 'builder' to have an "else" without an "then"
3408 if (op == glslang::EOpLogicalOr)
3409 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3410
3411 // make an "if" based on the left value
3412 spv::Builder::If ifBuilder(leftId, builder);
3413
3414 // emit right operand as the "then" part of the "if"
3415 builder.clearAccessChain();
3416 right.traverse(this);
3417 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3418
3419 // accumulate left operand's phi information
3420 phiOperands.push_back(rightId);
3421 phiOperands.push_back(builder.getBuildPoint()->getId());
3422
3423 // finish the "if"
3424 ifBuilder.makeEndIf();
3425
3426 // phi together the two results
3427 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3428}
3429
John Kessenich140f3df2015-06-26 16:58:36 -06003430}; // end anonymous namespace
3431
3432namespace glslang {
3433
John Kessenich68d78fd2015-07-12 19:28:10 -06003434void GetSpirvVersion(std::string& version)
3435{
John Kessenich9e55f632015-07-15 10:03:39 -06003436 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003437 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003438 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003439 version = buf;
3440}
3441
John Kessenich140f3df2015-06-26 16:58:36 -06003442// Write SPIR-V out to a binary file
3443void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3444{
3445 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003446 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003447 for (int i = 0; i < (int)spirv.size(); ++i) {
3448 unsigned int word = spirv[i];
3449 out.write((const char*)&word, 4);
3450 }
3451 out.close();
3452}
3453
3454//
3455// Set up the glslang traversal
3456//
3457void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3458{
3459 TIntermNode* root = intermediate.getTreeRoot();
3460
3461 if (root == 0)
3462 return;
3463
3464 glslang::GetThreadPoolAllocator().push();
3465
3466 TGlslangToSpvTraverser it(&intermediate);
3467
3468 root->traverse(&it);
3469
3470 it.dumpSpv(spirv);
3471
3472 glslang::GetThreadPoolAllocator().pop();
3473}
3474
3475}; // end namespace glslang