blob: 4ed3af770d65dbd07247bb457fa72a96f3026857 [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 Kessenich31ed4832015-09-09 17:51:38 -060094 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout);
95 bool requiresExplicitLayout(const glslang::TType& type) const;
Jason Ekstrand54aedf12015-09-05 09:50:58 -070096 int getArrayStride(const glslang::TType& arrayType);
97 int getMatrixStride(const glslang::TType& matrixType);
John Kessenich5e4b1242015-08-06 22:53:06 -060098 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
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);
Rex Xu04db3f52015-09-16 11:44:02 +0800111 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 -0600112 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
113 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800114 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 -0600115 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 -0600116 spv::Id createNoArgOperation(glslang::TOperator op);
117 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
118 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700119 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600120 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700121 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
122 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600123 bool isTrivialLeaf(const glslang::TIntermTyped* node);
124 bool isTrivial(const glslang::TIntermTyped* node);
125 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600126
127 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700128 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600129 int sequenceDepth;
130
131 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
132 spv::Builder builder;
133 bool inMain;
134 bool mainTerminated;
135 bool linkageOnly;
136 const glslang::TIntermediate* glslangIntermediate;
137 spv::Id stdBuiltins;
138
John Kessenich2f273362015-07-18 22:34:27 -0600139 std::unordered_map<int, spv::Id> symbolValues;
140 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
141 std::unordered_map<std::string, spv::Function*> functionMap;
142 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
143 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 -0600144 std::stack<bool> breakForLoop; // false means break for switch
145 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
146};
147
148//
149// Helper functions for translating glslang representations to SPIR-V enumerants.
150//
151
152// Translate glslang profile to SPIR-V source language.
153spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
154{
155 switch (profile) {
156 case ENoProfile:
157 case ECoreProfile:
158 case ECompatibilityProfile:
159 return spv::SourceLanguageGLSL;
160 case EEsProfile:
161 return spv::SourceLanguageESSL;
162 default:
163 return spv::SourceLanguageUnknown;
164 }
165}
166
167// Translate glslang language (stage) to SPIR-V execution model.
168spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
169{
170 switch (stage) {
171 case EShLangVertex: return spv::ExecutionModelVertex;
172 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
173 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
174 case EShLangGeometry: return spv::ExecutionModelGeometry;
175 case EShLangFragment: return spv::ExecutionModelFragment;
176 case EShLangCompute: return spv::ExecutionModelGLCompute;
177 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700178 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600179 return spv::ExecutionModelFragment;
180 }
181}
182
183// Translate glslang type to SPIR-V storage class.
184spv::StorageClass TranslateStorageClass(const glslang::TType& type)
185{
186 if (type.getQualifier().isPipeInput())
187 return spv::StorageClassInput;
188 else if (type.getQualifier().isPipeOutput())
189 return spv::StorageClassOutput;
190 else if (type.getQualifier().isUniformOrBuffer()) {
191 if (type.getBasicType() == glslang::EbtBlock)
192 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800193 else if (type.getBasicType() == glslang::EbtAtomicUint)
194 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600195 else
196 return spv::StorageClassUniformConstant;
197 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
198 } else {
199 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700200 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
201 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
203 case glslang::EvqTemporary: return spv::StorageClassFunction;
204 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700205 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600206 return spv::StorageClassFunction;
207 }
208 }
209}
210
211// Translate glslang sampler type to SPIR-V dimensionality.
212spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
213{
214 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700215 case glslang::Esd1D: return spv::Dim1D;
216 case glslang::Esd2D: return spv::Dim2D;
217 case glslang::Esd3D: return spv::Dim3D;
218 case glslang::EsdCube: return spv::DimCube;
219 case glslang::EsdRect: return spv::DimRect;
220 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600221 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700222 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600223 return spv::Dim2D;
224 }
225}
226
227// Translate glslang type to SPIR-V precision decorations.
228spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
229{
230 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600231 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
232 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
233 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 default:
235 return spv::NoPrecision;
236 }
237}
238
239// Translate glslang type to SPIR-V block decorations.
240spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
241{
242 if (type.getBasicType() == glslang::EbtBlock) {
243 switch (type.getQualifier().storage) {
244 case glslang::EvqUniform: return spv::DecorationBlock;
245 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
246 case glslang::EvqVaryingIn: return spv::DecorationBlock;
247 case glslang::EvqVaryingOut: return spv::DecorationBlock;
248 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700249 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600250 break;
251 }
252 }
253
254 return (spv::Decoration)spv::BadValue;
255}
256
257// Translate glslang type to SPIR-V layout decorations.
258spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
259{
260 if (type.isMatrix()) {
261 switch (type.getQualifier().layoutMatrix) {
262 case glslang::ElmRowMajor:
263 return spv::DecorationRowMajor;
264 default:
265 return spv::DecorationColMajor;
266 }
267 } else {
268 switch (type.getBasicType()) {
269 default:
270 return (spv::Decoration)spv::BadValue;
271 break;
272 case glslang::EbtBlock:
273 switch (type.getQualifier().storage) {
274 case glslang::EvqUniform:
275 case glslang::EvqBuffer:
276 switch (type.getQualifier().layoutPacking) {
277 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600278 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
279 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600280 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600281 }
282 case glslang::EvqVaryingIn:
283 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700284 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600285 return (spv::Decoration)spv::BadValue;
286 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700287 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600288 return (spv::Decoration)spv::BadValue;
289 }
290 }
291 }
292}
293
294// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700295// Returns spv::Decoration(spv::BadValue) when no decoration
296// should be applied.
John Kessenich140f3df2015-06-26 16:58:36 -0600297spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
298{
John Kessenich55e7d112015-11-15 21:33:39 -0700299 if (type.getQualifier().smooth) {
300 // Smooth decoration doesn't exist in SPIR-V 1.0
301 return (spv::Decoration)spv::BadValue;
302 }
John Kessenich140f3df2015-06-26 16:58:36 -0600303 if (type.getQualifier().nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700304 return spv::DecorationNoPerspective;
John Kessenich140f3df2015-06-26 16:58:36 -0600305 else if (type.getQualifier().patch)
306 return spv::DecorationPatch;
307 else if (type.getQualifier().flat)
308 return spv::DecorationFlat;
309 else if (type.getQualifier().centroid)
310 return spv::DecorationCentroid;
311 else if (type.getQualifier().sample)
312 return spv::DecorationSample;
313 else
314 return (spv::Decoration)spv::BadValue;
315}
316
317// If glslang type is invaraiant, return SPIR-V invariant decoration.
318spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
319{
320 if (type.getQualifier().invariant)
321 return spv::DecorationInvariant;
322 else
323 return (spv::Decoration)spv::BadValue;
324}
325
326// Translate glslang built-in variable to SPIR-V built in decoration.
327spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
328{
329 switch (builtIn) {
330 case glslang::EbvPosition: return spv::BuiltInPosition;
331 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600332 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
333 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
334 case glslang::EbvVertexId: return spv::BuiltInVertexId;
335 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600336 case glslang::EbvBaseVertex:
337 case glslang::EbvBaseInstance:
338 case glslang::EbvDrawId:
339 // TODO: Add SPIR-V builtin ID.
340 spv::MissingFunctionality("Draw parameters");
341 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
343 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
344 case glslang::EbvLayer: return spv::BuiltInLayer;
345 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
346 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
347 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
348 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
349 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
350 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
351 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
352 case glslang::EbvFace: return spv::BuiltInFrontFacing;
353 case glslang::EbvSampleId: return spv::BuiltInSampleId;
354 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
355 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600356 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
357 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
358 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
359 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
360 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
361 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
362 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
363 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
364 default: return (spv::BuiltIn)spv::BadValue;
365 }
366}
367
Rex Xufc618912015-09-09 16:42:49 +0800368// Translate glslang image layout format to SPIR-V image format.
369spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
370{
371 assert(type.getBasicType() == glslang::EbtSampler);
372
373 switch (type.getQualifier().layoutFormat) {
374 case glslang::ElfNone: return spv::ImageFormatUnknown;
375 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
376 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
377 case glslang::ElfR32f: return spv::ImageFormatR32f;
378 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
379 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
380 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
381 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
382 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
383 case glslang::ElfR16f: return spv::ImageFormatR16f;
384 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
385 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
386 case glslang::ElfRg16: return spv::ImageFormatRg16;
387 case glslang::ElfRg8: return spv::ImageFormatRg8;
388 case glslang::ElfR16: return spv::ImageFormatR16;
389 case glslang::ElfR8: return spv::ImageFormatR8;
390 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
391 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
392 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
393 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
394 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
395 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
396 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
397 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
398 case glslang::ElfR32i: return spv::ImageFormatR32i;
399 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
400 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
401 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
402 case glslang::ElfR16i: return spv::ImageFormatR16i;
403 case glslang::ElfR8i: return spv::ImageFormatR8i;
404 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
405 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
406 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
407 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
408 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
409 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
410 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
411 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
412 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
413 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
414 default: return (spv::ImageFormat)spv::BadValue;
415 }
416}
417
John Kessenich140f3df2015-06-26 16:58:36 -0600418//
419// Implement the TGlslangToSpvTraverser class.
420//
421
422TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
423 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700424 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600425 inMain(false), mainTerminated(false), linkageOnly(false),
426 glslangIntermediate(glslangIntermediate)
427{
428 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
429
430 builder.clearAccessChain();
431 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
432 stdBuiltins = builder.import("GLSL.std.450");
433 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
434 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700435 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600436
437 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600438 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
439 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600440 builder.addSourceExtension(it->c_str());
441
442 // Add the top-level modes for this shader.
443
444 if (glslangIntermediate->getXfbMode())
445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
446
447 unsigned int mode;
448 switch (glslangIntermediate->getStage()) {
449 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600450 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600451 break;
452
453 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600454 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600455 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
456 break;
457
458 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600459 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600460 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700461 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
462 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
463 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600464 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600465 }
466 if (mode != spv::BadValue)
467 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
468
John Kesseniche6903322015-10-13 16:29:02 -0600469 switch (glslangIntermediate->getVertexSpacing()) {
470 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
471 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
472 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
473 default: mode = spv::BadValue; break;
474 }
475 if (mode != spv::BadValue)
476 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
477
478 switch (glslangIntermediate->getVertexOrder()) {
479 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
480 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
481 default: mode = spv::BadValue; break;
482 }
483 if (mode != spv::BadValue)
484 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
485
486 if (glslangIntermediate->getPointMode())
487 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600488 break;
489
490 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600491 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600492 switch (glslangIntermediate->getInputPrimitive()) {
493 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
494 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
495 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700496 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
498 default: mode = spv::BadValue; break;
499 }
500 if (mode != spv::BadValue)
501 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600502
John Kessenich140f3df2015-06-26 16:58:36 -0600503 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
504
505 switch (glslangIntermediate->getOutputPrimitive()) {
506 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
507 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
508 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
509 default: mode = spv::BadValue; break;
510 }
511 if (mode != spv::BadValue)
512 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
513 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
514 break;
515
516 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600517 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600518 if (glslangIntermediate->getPixelCenterInteger())
519 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600520
John Kessenich140f3df2015-06-26 16:58:36 -0600521 if (glslangIntermediate->getOriginUpperLeft())
522 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600523 else
524 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600525
526 if (glslangIntermediate->getEarlyFragmentTests())
527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
528
529 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600530 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
531 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
532 default: mode = spv::BadValue; break;
533 }
534 if (mode != spv::BadValue)
535 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
536
537 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
538 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600539 break;
540
541 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600542 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600543 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
544 glslangIntermediate->getLocalSize(1),
545 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600546 break;
547
548 default:
549 break;
550 }
551
552}
553
554TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
555{
556 if (! mainTerminated) {
557 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
558 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600559 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600560 }
561}
562
563//
564// Implement the traversal functions.
565//
566// Return true from interior nodes to have the external traversal
567// continue on to children. Return false if children were
568// already processed.
569//
570
571//
572// Symbols can turn into
573// - uniform/input reads
574// - output writes
575// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
576// - something simple that degenerates into the last bullet
577//
578void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
579{
580 // getSymbolId() will set up all the IO decorations on the first call.
581 // Formal function parameters were mapped during makeFunctions().
582 spv::Id id = getSymbolId(symbol);
583
584 if (! linkageOnly) {
585 // Prepare to generate code for the access
586
587 // L-value chains will be computed left to right. We're on the symbol now,
588 // which is the left-most part of the access chain, so now is "clear" time,
589 // followed by setting the base.
590 builder.clearAccessChain();
591
592 // For now, we consider all user variables as being in memory, so they are pointers,
593 // except for "const in" arguments to a function, which are an intermediate object.
594 // See comments in handleUserFunctionCall().
595 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
596 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
597 builder.setAccessChainRValue(id);
598 else
599 builder.setAccessChainLValue(id);
John Kessenich55e7d112015-11-15 21:33:39 -0700600 } else {
601 // finish off the entry-point SPV instruction by adding the Input/Output <id>
602 spv::StorageClass sc = builder.getStorageClass(id);
603 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
604 entryPoint->addIdOperand(id);
John Kessenich140f3df2015-06-26 16:58:36 -0600605 }
606}
607
608bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
609{
610 // First, handle special cases
611 switch (node->getOp()) {
612 case glslang::EOpAssign:
613 case glslang::EOpAddAssign:
614 case glslang::EOpSubAssign:
615 case glslang::EOpMulAssign:
616 case glslang::EOpVectorTimesMatrixAssign:
617 case glslang::EOpVectorTimesScalarAssign:
618 case glslang::EOpMatrixTimesScalarAssign:
619 case glslang::EOpMatrixTimesMatrixAssign:
620 case glslang::EOpDivAssign:
621 case glslang::EOpModAssign:
622 case glslang::EOpAndAssign:
623 case glslang::EOpInclusiveOrAssign:
624 case glslang::EOpExclusiveOrAssign:
625 case glslang::EOpLeftShiftAssign:
626 case glslang::EOpRightShiftAssign:
627 // A bin-op assign "a += b" means the same thing as "a = a + b"
628 // where a is evaluated before b. For a simple assignment, GLSL
629 // says to evaluate the left before the right. So, always, left
630 // node then right node.
631 {
632 // get the left l-value, save it away
633 builder.clearAccessChain();
634 node->getLeft()->traverse(this);
635 spv::Builder::AccessChain lValue = builder.getAccessChain();
636
637 // evaluate the right
638 builder.clearAccessChain();
639 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600640 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600641
642 if (node->getOp() != glslang::EOpAssign) {
643 // the left is also an r-value
644 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600645 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600646
647 // do the operation
648 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
649 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
650 node->getType().getBasicType());
651
652 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700653 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600654 }
655
656 // store the result
657 builder.setAccessChain(lValue);
658 builder.accessChainStore(rValue);
659
660 // assignments are expressions having an rValue after they are evaluated...
661 builder.clearAccessChain();
662 builder.setAccessChainRValue(rValue);
663 }
664 return false;
665 case glslang::EOpIndexDirect:
666 case glslang::EOpIndexDirectStruct:
667 {
668 // Get the left part of the access chain.
669 node->getLeft()->traverse(this);
670
671 // Add the next element in the chain
672
John Kessenich55e7d112015-11-15 21:33:39 -0700673 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600674 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
675 // This may be, e.g., an anonymous block-member selection, which generally need
676 // index remapping due to hidden members in anonymous blocks.
677 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700678 assert(remapper.size() > 0);
679 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600680 }
681
682 if (! node->getLeft()->getType().isArray() &&
683 node->getLeft()->getType().isVector() &&
684 node->getOp() == glslang::EOpIndexDirect) {
685 // This is essentially a hard-coded vector swizzle of size 1,
686 // so short circuit the access-chain stuff with a swizzle.
687 std::vector<unsigned> swizzle;
688 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600689 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600690 } else {
691 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600692 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600693 }
694 }
695 return false;
696 case glslang::EOpIndexIndirect:
697 {
698 // Structure or array or vector indirection.
699 // Will use native SPIR-V access-chain for struct and array indirection;
700 // matrices are arrays of vectors, so will also work for a matrix.
701 // Will use the access chain's 'component' for variable index into a vector.
702
703 // This adapter is building access chains left to right.
704 // Set up the access chain to the left.
705 node->getLeft()->traverse(this);
706
707 // save it so that computing the right side doesn't trash it
708 spv::Builder::AccessChain partial = builder.getAccessChain();
709
710 // compute the next index in the chain
711 builder.clearAccessChain();
712 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600713 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600714
715 // restore the saved access chain
716 builder.setAccessChain(partial);
717
718 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600719 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600720 else
John Kessenichfa668da2015-09-13 14:46:30 -0600721 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600722 }
723 return false;
724 case glslang::EOpVectorSwizzle:
725 {
726 node->getLeft()->traverse(this);
727 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
728 std::vector<unsigned> swizzle;
729 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
730 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600731 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600732 }
733 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600734 case glslang::EOpLogicalOr:
735 case glslang::EOpLogicalAnd:
736 {
737
738 // These may require short circuiting, but can sometimes be done as straight
739 // binary operations. The right operand must be short circuited if it has
740 // side effects, and should probably be if it is complex.
741 if (isTrivial(node->getRight()->getAsTyped()))
742 break; // handle below as a normal binary operation
743 // otherwise, we need to do dynamic short circuiting on the right operand
744 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
745 builder.clearAccessChain();
746 builder.setAccessChainRValue(result);
747 }
748 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600749 default:
750 break;
751 }
752
753 // Assume generic binary op...
754
755 // Get the operands
756 builder.clearAccessChain();
757 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600758 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600759
760 builder.clearAccessChain();
761 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600762 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600763
764 spv::Id result;
765 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
766
767 result = createBinaryOperation(node->getOp(), precision,
768 convertGlslangToSpvType(node->getType()), left, right,
769 node->getLeft()->getType().getBasicType());
770
771 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700772 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich140f3df2015-06-26 16:58:36 -0600773 } else {
774 builder.clearAccessChain();
775 builder.setAccessChainRValue(result);
776
777 return false;
778 }
779
780 return true;
781}
782
783bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
784{
John Kessenichfc51d282015-08-19 13:34:18 -0600785 spv::Id result = spv::NoResult;
786
787 // try texturing first
788 result = createImageTextureFunctionCall(node);
789 if (result != spv::NoResult) {
790 builder.clearAccessChain();
791 builder.setAccessChainRValue(result);
792
793 return false; // done with this node
794 }
795
796 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600797
798 if (node->getOp() == glslang::EOpArrayLength) {
799 // Quite special; won't want to evaluate the operand.
800
801 // Normal .length() would have been constant folded by the front-end.
802 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600803 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600804 assert(node->getOperand()->getType().isRuntimeSizedArray());
805 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
806 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600807 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
808 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600809
810 builder.clearAccessChain();
811 builder.setAccessChainRValue(length);
812
813 return false;
814 }
815
John Kessenichfc51d282015-08-19 13:34:18 -0600816 // Start by evaluating the operand
817
John Kessenich140f3df2015-06-26 16:58:36 -0600818 builder.clearAccessChain();
819 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800820
Rex Xufc618912015-09-09 16:42:49 +0800821 spv::Id operand = spv::NoResult;
822
823 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
824 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800825 node->getOp() == glslang::EOpAtomicCounter ||
826 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800827 operand = builder.accessChainGetLValue(); // Special case l-value operands
828 else
Rex Xu30f92582015-09-14 10:38:56 +0800829 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600830
831 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
832
833 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600834 if (! result)
835 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600836
837 // if not, then possibly an operation
838 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700839 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600840
841 if (result) {
842 builder.clearAccessChain();
843 builder.setAccessChainRValue(result);
844
845 return false; // done with this node
846 }
847
848 // it must be a special case, check...
849 switch (node->getOp()) {
850 case glslang::EOpPostIncrement:
851 case glslang::EOpPostDecrement:
852 case glslang::EOpPreIncrement:
853 case glslang::EOpPreDecrement:
854 {
855 // we need the integer value "1" or the floating point "1.0" to add/subtract
856 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
857 builder.makeFloatConstant(1.0F) :
858 builder.makeIntConstant(1);
859 glslang::TOperator op;
860 if (node->getOp() == glslang::EOpPreIncrement ||
861 node->getOp() == glslang::EOpPostIncrement)
862 op = glslang::EOpAdd;
863 else
864 op = glslang::EOpSub;
865
866 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
867 convertGlslangToSpvType(node->getType()), operand, one,
868 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700869 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600870
871 // The result of operation is always stored, but conditionally the
872 // consumed result. The consumed result is always an r-value.
873 builder.accessChainStore(result);
874 builder.clearAccessChain();
875 if (node->getOp() == glslang::EOpPreIncrement ||
876 node->getOp() == glslang::EOpPreDecrement)
877 builder.setAccessChainRValue(result);
878 else
879 builder.setAccessChainRValue(operand);
880 }
881
882 return false;
883
884 case glslang::EOpEmitStreamVertex:
885 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
886 return false;
887 case glslang::EOpEndStreamPrimitive:
888 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
889 return false;
890
891 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700892 spv::MissingFunctionality("unknown glslang unary");
John Kessenich140f3df2015-06-26 16:58:36 -0600893 break;
894 }
895
896 return true;
897}
898
899bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
900{
John Kessenichfc51d282015-08-19 13:34:18 -0600901 spv::Id result = spv::NoResult;
902
903 // try texturing
904 result = createImageTextureFunctionCall(node);
905 if (result != spv::NoResult) {
906 builder.clearAccessChain();
907 builder.setAccessChainRValue(result);
908
909 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600910 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800911 // "imageStore" is a special case, which has no result
912 return false;
913 }
John Kessenichfc51d282015-08-19 13:34:18 -0600914
John Kessenich140f3df2015-06-26 16:58:36 -0600915 glslang::TOperator binOp = glslang::EOpNull;
916 bool reduceComparison = true;
917 bool isMatrix = false;
918 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600919 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600920
921 assert(node->getOp());
922
923 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
924
925 switch (node->getOp()) {
926 case glslang::EOpSequence:
927 {
928 if (preVisit)
929 ++sequenceDepth;
930 else
931 --sequenceDepth;
932
933 if (sequenceDepth == 1) {
934 // If this is the parent node of all the functions, we want to see them
935 // early, so all call points have actual SPIR-V functions to reference.
936 // In all cases, still let the traverser visit the children for us.
937 makeFunctions(node->getAsAggregate()->getSequence());
938
939 // Also, we want all globals initializers to go into the entry of main(), before
940 // anything else gets there, so visit out of order, doing them all now.
941 makeGlobalInitializers(node->getAsAggregate()->getSequence());
942
943 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
944 // so do them manually.
945 visitFunctions(node->getAsAggregate()->getSequence());
946
947 return false;
948 }
949
950 return true;
951 }
952 case glslang::EOpLinkerObjects:
953 {
954 if (visit == glslang::EvPreVisit)
955 linkageOnly = true;
956 else
957 linkageOnly = false;
958
959 return true;
960 }
961 case glslang::EOpComma:
962 {
963 // processing from left to right naturally leaves the right-most
964 // lying around in the access chain
965 glslang::TIntermSequence& glslangOperands = node->getSequence();
966 for (int i = 0; i < (int)glslangOperands.size(); ++i)
967 glslangOperands[i]->traverse(this);
968
969 return false;
970 }
971 case glslang::EOpFunction:
972 if (visit == glslang::EvPreVisit) {
973 if (isShaderEntrypoint(node)) {
974 inMain = true;
975 builder.setBuildPoint(shaderEntry->getLastBlock());
976 } else {
977 handleFunctionEntry(node);
978 }
979 } else {
980 if (inMain)
981 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600982 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600983 inMain = false;
984 }
985
986 return true;
987 case glslang::EOpParameters:
988 // Parameters will have been consumed by EOpFunction processing, but not
989 // the body, so we still visited the function node's children, making this
990 // child redundant.
991 return false;
992 case glslang::EOpFunctionCall:
993 {
994 if (node->isUserDefined())
995 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -0700996 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600997 builder.clearAccessChain();
998 builder.setAccessChainRValue(result);
999
1000 return false;
1001 }
1002 case glslang::EOpConstructMat2x2:
1003 case glslang::EOpConstructMat2x3:
1004 case glslang::EOpConstructMat2x4:
1005 case glslang::EOpConstructMat3x2:
1006 case glslang::EOpConstructMat3x3:
1007 case glslang::EOpConstructMat3x4:
1008 case glslang::EOpConstructMat4x2:
1009 case glslang::EOpConstructMat4x3:
1010 case glslang::EOpConstructMat4x4:
1011 case glslang::EOpConstructDMat2x2:
1012 case glslang::EOpConstructDMat2x3:
1013 case glslang::EOpConstructDMat2x4:
1014 case glslang::EOpConstructDMat3x2:
1015 case glslang::EOpConstructDMat3x3:
1016 case glslang::EOpConstructDMat3x4:
1017 case glslang::EOpConstructDMat4x2:
1018 case glslang::EOpConstructDMat4x3:
1019 case glslang::EOpConstructDMat4x4:
1020 isMatrix = true;
1021 // fall through
1022 case glslang::EOpConstructFloat:
1023 case glslang::EOpConstructVec2:
1024 case glslang::EOpConstructVec3:
1025 case glslang::EOpConstructVec4:
1026 case glslang::EOpConstructDouble:
1027 case glslang::EOpConstructDVec2:
1028 case glslang::EOpConstructDVec3:
1029 case glslang::EOpConstructDVec4:
1030 case glslang::EOpConstructBool:
1031 case glslang::EOpConstructBVec2:
1032 case glslang::EOpConstructBVec3:
1033 case glslang::EOpConstructBVec4:
1034 case glslang::EOpConstructInt:
1035 case glslang::EOpConstructIVec2:
1036 case glslang::EOpConstructIVec3:
1037 case glslang::EOpConstructIVec4:
1038 case glslang::EOpConstructUint:
1039 case glslang::EOpConstructUVec2:
1040 case glslang::EOpConstructUVec3:
1041 case glslang::EOpConstructUVec4:
1042 case glslang::EOpConstructStruct:
1043 {
1044 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001045 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001046 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1047 spv::Id constructed;
1048 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1049 std::vector<spv::Id> constituents;
1050 for (int c = 0; c < (int)arguments.size(); ++c)
1051 constituents.push_back(arguments[c]);
1052 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001053 } else if (isMatrix)
1054 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1055 else
1056 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001057
1058 builder.clearAccessChain();
1059 builder.setAccessChainRValue(constructed);
1060
1061 return false;
1062 }
1063
1064 // These six are component-wise compares with component-wise results.
1065 // Forward on to createBinaryOperation(), requesting a vector result.
1066 case glslang::EOpLessThan:
1067 case glslang::EOpGreaterThan:
1068 case glslang::EOpLessThanEqual:
1069 case glslang::EOpGreaterThanEqual:
1070 case glslang::EOpVectorEqual:
1071 case glslang::EOpVectorNotEqual:
1072 {
1073 // Map the operation to a binary
1074 binOp = node->getOp();
1075 reduceComparison = false;
1076 switch (node->getOp()) {
1077 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1078 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1079 default: binOp = node->getOp(); break;
1080 }
1081
1082 break;
1083 }
1084 case glslang::EOpMul:
1085 // compontent-wise matrix multiply
1086 binOp = glslang::EOpMul;
1087 break;
1088 case glslang::EOpOuterProduct:
1089 // two vectors multiplied to make a matrix
1090 binOp = glslang::EOpOuterProduct;
1091 break;
1092 case glslang::EOpDot:
1093 {
1094 // for scalar dot product, use multiply
1095 glslang::TIntermSequence& glslangOperands = node->getSequence();
1096 if (! glslangOperands[0]->getAsTyped()->isVector())
1097 binOp = glslang::EOpMul;
1098 break;
1099 }
1100 case glslang::EOpMod:
1101 // when an aggregate, this is the floating-point mod built-in function,
1102 // which can be emitted by the one in createBinaryOperation()
1103 binOp = glslang::EOpMod;
1104 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001105 case glslang::EOpEmitVertex:
1106 case glslang::EOpEndPrimitive:
1107 case glslang::EOpBarrier:
1108 case glslang::EOpMemoryBarrier:
1109 case glslang::EOpMemoryBarrierAtomicCounter:
1110 case glslang::EOpMemoryBarrierBuffer:
1111 case glslang::EOpMemoryBarrierImage:
1112 case glslang::EOpMemoryBarrierShared:
1113 case glslang::EOpGroupMemoryBarrier:
1114 noReturnValue = true;
1115 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1116 break;
1117
John Kessenich426394d2015-07-23 10:22:48 -06001118 case glslang::EOpAtomicAdd:
1119 case glslang::EOpAtomicMin:
1120 case glslang::EOpAtomicMax:
1121 case glslang::EOpAtomicAnd:
1122 case glslang::EOpAtomicOr:
1123 case glslang::EOpAtomicXor:
1124 case glslang::EOpAtomicExchange:
1125 case glslang::EOpAtomicCompSwap:
1126 atomic = true;
1127 break;
1128
John Kessenich140f3df2015-06-26 16:58:36 -06001129 default:
1130 break;
1131 }
1132
1133 //
1134 // See if it maps to a regular operation.
1135 //
John Kessenich140f3df2015-06-26 16:58:36 -06001136 if (binOp != glslang::EOpNull) {
1137 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1138 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1139 assert(left && right);
1140
1141 builder.clearAccessChain();
1142 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001143 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 builder.clearAccessChain();
1146 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001147 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001148
1149 result = createBinaryOperation(binOp, precision,
1150 convertGlslangToSpvType(node->getType()), leftId, rightId,
1151 left->getType().getBasicType(), reduceComparison);
1152
1153 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001154 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001155 builder.clearAccessChain();
1156 builder.setAccessChainRValue(result);
1157
1158 return false;
1159 }
1160
John Kessenich426394d2015-07-23 10:22:48 -06001161 //
1162 // Create the list of operands.
1163 //
John Kessenich140f3df2015-06-26 16:58:36 -06001164 glslang::TIntermSequence& glslangOperands = node->getSequence();
1165 std::vector<spv::Id> operands;
1166 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1167 builder.clearAccessChain();
1168 glslangOperands[arg]->traverse(this);
1169
1170 // special case l-value operands; there are just a few
1171 bool lvalue = false;
1172 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001173 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001174 case glslang::EOpModf:
1175 if (arg == 1)
1176 lvalue = true;
1177 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001178 case glslang::EOpInterpolateAtSample:
1179 case glslang::EOpInterpolateAtOffset:
1180 if (arg == 0)
1181 lvalue = true;
1182 break;
Rex Xud4782c12015-09-06 16:30:11 +08001183 case glslang::EOpAtomicAdd:
1184 case glslang::EOpAtomicMin:
1185 case glslang::EOpAtomicMax:
1186 case glslang::EOpAtomicAnd:
1187 case glslang::EOpAtomicOr:
1188 case glslang::EOpAtomicXor:
1189 case glslang::EOpAtomicExchange:
1190 case glslang::EOpAtomicCompSwap:
1191 if (arg == 0)
1192 lvalue = true;
1193 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001194 case glslang::EOpAddCarry:
1195 case glslang::EOpSubBorrow:
1196 if (arg == 2)
1197 lvalue = true;
1198 break;
1199 case glslang::EOpUMulExtended:
1200 case glslang::EOpIMulExtended:
1201 if (arg >= 2)
1202 lvalue = true;
1203 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001204 default:
1205 break;
1206 }
1207 if (lvalue)
1208 operands.push_back(builder.accessChainGetLValue());
1209 else
John Kessenichfa668da2015-09-13 14:46:30 -06001210 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001211 }
John Kessenich426394d2015-07-23 10:22:48 -06001212
1213 if (atomic) {
1214 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001215 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001216 } else {
1217 // Pass through to generic operations.
1218 switch (glslangOperands.size()) {
1219 case 0:
1220 result = createNoArgOperation(node->getOp());
1221 break;
1222 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001223 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001224 break;
1225 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001226 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001227 break;
1228 }
John Kessenich140f3df2015-06-26 16:58:36 -06001229 }
1230
1231 if (noReturnValue)
1232 return false;
1233
1234 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001235 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich140f3df2015-06-26 16:58:36 -06001236 return true;
1237 } else {
1238 builder.clearAccessChain();
1239 builder.setAccessChainRValue(result);
1240 return false;
1241 }
1242}
1243
1244bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1245{
1246 // This path handles both if-then-else and ?:
1247 // The if-then-else has a node type of void, while
1248 // ?: has a non-void node type
1249 spv::Id result = 0;
1250 if (node->getBasicType() != glslang::EbtVoid) {
1251 // don't handle this as just on-the-fly temporaries, because there will be two names
1252 // and better to leave SSA to later passes
1253 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1254 }
1255
1256 // emit the condition before doing anything with selection
1257 node->getCondition()->traverse(this);
1258
1259 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001260 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001261
1262 if (node->getTrueBlock()) {
1263 // emit the "then" statement
1264 node->getTrueBlock()->traverse(this);
1265 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001266 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001267 }
1268
1269 if (node->getFalseBlock()) {
1270 ifBuilder.makeBeginElse();
1271 // emit the "else" statement
1272 node->getFalseBlock()->traverse(this);
1273 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001274 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001275 }
1276
1277 ifBuilder.makeEndIf();
1278
1279 if (result) {
1280 // GLSL only has r-values as the result of a :?, but
1281 // if we have an l-value, that can be more efficient if it will
1282 // become the base of a complex r-value expression, because the
1283 // next layer copies r-values into memory to use the access-chain mechanism
1284 builder.clearAccessChain();
1285 builder.setAccessChainLValue(result);
1286 }
1287
1288 return false;
1289}
1290
1291bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1292{
1293 // emit and get the condition before doing anything with switch
1294 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001295 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001296
1297 // browse the children to sort out code segments
1298 int defaultSegment = -1;
1299 std::vector<TIntermNode*> codeSegments;
1300 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1301 std::vector<int> caseValues;
1302 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1303 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1304 TIntermNode* child = *c;
1305 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001306 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001307 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001308 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001309 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1310 } else
1311 codeSegments.push_back(child);
1312 }
1313
1314 // handle the case where the last code segment is missing, due to no code
1315 // statements between the last case and the end of the switch statement
1316 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1317 (int)codeSegments.size() == defaultSegment)
1318 codeSegments.push_back(nullptr);
1319
1320 // make the switch statement
1321 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001322 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001323
1324 // emit all the code in the segments
1325 breakForLoop.push(false);
1326 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1327 builder.nextSwitchSegment(segmentBlocks, s);
1328 if (codeSegments[s])
1329 codeSegments[s]->traverse(this);
1330 else
1331 builder.addSwitchBreak();
1332 }
1333 breakForLoop.pop();
1334
1335 builder.endSwitch(segmentBlocks);
1336
1337 return false;
1338}
1339
1340void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1341{
1342 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001343 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001344
1345 builder.clearAccessChain();
1346 builder.setAccessChainRValue(constant);
1347}
1348
1349bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1350{
1351 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1352 loopTerminal.push(node->getTerminal());
1353
David Netoc22f37c2015-07-15 16:21:26 -04001354 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001355
1356 if (node->getTest()) {
1357 node->getTest()->traverse(this);
1358 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001359 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001360 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001361 } else {
1362 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001363 }
1364
David Netoc22f37c2015-07-15 16:21:26 -04001365 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001366 breakForLoop.push(true);
1367 node->getBody()->traverse(this);
1368 breakForLoop.pop();
1369 }
1370
1371 if (loopTerminal.top())
1372 loopTerminal.top()->traverse(this);
1373
1374 builder.closeLoop();
1375
1376 loopTerminal.pop();
1377
1378 return false;
1379}
1380
1381bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1382{
1383 if (node->getExpression())
1384 node->getExpression()->traverse(this);
1385
1386 switch (node->getFlowOp()) {
1387 case glslang::EOpKill:
1388 builder.makeDiscard();
1389 break;
1390 case glslang::EOpBreak:
1391 if (breakForLoop.top())
1392 builder.createLoopExit();
1393 else
1394 builder.addSwitchBreak();
1395 break;
1396 case glslang::EOpContinue:
1397 if (loopTerminal.top())
1398 loopTerminal.top()->traverse(this);
1399 builder.createLoopContinue();
1400 break;
1401 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001402 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001403 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001404 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001405 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001406
1407 builder.clearAccessChain();
1408 break;
1409
1410 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001411 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001412 break;
1413 }
1414
1415 return false;
1416}
1417
1418spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1419{
1420 // First, steer off constants, which are not SPIR-V variables, but
1421 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001422 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001423 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001424 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001425 }
1426
1427 // Now, handle actual variables
1428 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1429 spv::Id spvType = convertGlslangToSpvType(node->getType());
1430
1431 const char* name = node->getName().c_str();
1432 if (glslang::IsAnonymous(name))
1433 name = "";
1434
1435 return builder.createVariable(storageClass, spvType, name);
1436}
1437
1438// Return type Id of the sampled type.
1439spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1440{
1441 switch (sampler.type) {
1442 case glslang::EbtFloat: return builder.makeFloatType(32);
1443 case glslang::EbtInt: return builder.makeIntType(32);
1444 case glslang::EbtUint: return builder.makeUintType(32);
1445 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001446 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001447 return builder.makeFloatType(32);
1448 }
1449}
1450
John Kessenich31ed4832015-09-09 17:51:38 -06001451// Convert from a glslang type to an SPV type, by calling into
1452// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001453spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1454{
John Kessenich31ed4832015-09-09 17:51:38 -06001455 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1456}
1457
1458// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1459// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1460spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1461{
John Kessenich140f3df2015-06-26 16:58:36 -06001462 spv::Id spvType = 0;
1463
1464 switch (type.getBasicType()) {
1465 case glslang::EbtVoid:
1466 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001467 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001468 break;
1469 case glslang::EbtFloat:
1470 spvType = builder.makeFloatType(32);
1471 break;
1472 case glslang::EbtDouble:
1473 spvType = builder.makeFloatType(64);
1474 break;
1475 case glslang::EbtBool:
1476 spvType = builder.makeBoolType();
1477 break;
1478 case glslang::EbtInt:
1479 spvType = builder.makeIntType(32);
1480 break;
1481 case glslang::EbtUint:
1482 spvType = builder.makeUintType(32);
1483 break;
John Kessenich426394d2015-07-23 10:22:48 -06001484 case glslang::EbtAtomicUint:
1485 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1486 spvType = builder.makeUintType(32);
1487 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001488 case glslang::EbtSampler:
1489 {
1490 const glslang::TSampler& sampler = type.getSampler();
John Kessenich55e7d112015-11-15 21:33:39 -07001491 // an image is present, make its type
1492 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1493 sampler.image ? 2 : 1, TranslateImageFormat(type));
1494 if (! sampler.image) {
1495 spvType = builder.makeSampledImageType(spvType);
1496 }
1497 }
John Kessenich140f3df2015-06-26 16:58:36 -06001498 break;
1499 case glslang::EbtStruct:
1500 case glslang::EbtBlock:
1501 {
1502 // If we've seen this struct type, return it
1503 const glslang::TTypeList* glslangStruct = type.getStruct();
1504 std::vector<spv::Id> structFields;
1505 spvType = structMap[glslangStruct];
1506 if (spvType)
1507 break;
1508
1509 // else, we haven't seen it...
1510
1511 // Create a vector of struct types for SPIR-V to consume
1512 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1513 if (type.getBasicType() == glslang::EbtBlock)
1514 memberRemapper[glslangStruct].resize(glslangStruct->size());
1515 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1516 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1517 if (glslangType.hiddenMember()) {
1518 ++memberDelta;
1519 if (type.getBasicType() == glslang::EbtBlock)
1520 memberRemapper[glslangStruct][i] = -1;
1521 } else {
1522 if (type.getBasicType() == glslang::EbtBlock)
1523 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001524 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001525 }
1526 }
1527
1528 // Make the SPIR-V type
1529 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1530 structMap[glslangStruct] = spvType;
1531
1532 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001533 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001534 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1535 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1536 int member = i;
1537 if (type.getBasicType() == glslang::EbtBlock)
1538 member = memberRemapper[glslangStruct][i];
1539 // using -1 above to indicate a hidden member
1540 if (member >= 0) {
1541 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1542 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1543 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1544 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1545 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1546 if (glslangType.getQualifier().hasLocation())
1547 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1548 if (glslangType.getQualifier().hasComponent())
1549 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1550 if (glslangType.getQualifier().hasXfbOffset())
1551 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001552 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001553 // figure out what to do with offset, which is accumulating
1554 int nextOffset;
1555 updateMemberOffset(type, glslangType, offset, nextOffset);
1556 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001557 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001558 offset = nextOffset;
1559 }
John Kessenich140f3df2015-06-26 16:58:36 -06001560
John Kessenich31ed4832015-09-09 17:51:38 -06001561 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001562 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1563 }
1564
John Kessenich140f3df2015-06-26 16:58:36 -06001565 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001566 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1567 if (builtIn != spv::BadValue)
1568 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001569 }
1570 }
1571
1572 // Decorate the structure
1573 addDecoration(spvType, TranslateLayoutDecoration(type));
1574 addDecoration(spvType, TranslateBlockDecoration(type));
1575 if (type.getQualifier().hasStream())
1576 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1577 if (glslangIntermediate->getXfbMode()) {
1578 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001579 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001580 if (type.getQualifier().hasXfbBuffer())
1581 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1582 }
1583 }
1584 break;
1585 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001586 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001587 break;
1588 }
1589
1590 if (type.isMatrix())
1591 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1592 else {
1593 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1594 if (type.getVectorSize() > 1)
1595 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1596 }
1597
1598 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001599 // Do all but the outer dimension
1600 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1601 assert(type.getArraySizes()->getDimSize(dim) > 0);
1602 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1603 }
John Kessenich31ed4832015-09-09 17:51:38 -06001604
John Kessenichc9a80832015-09-12 12:17:44 -06001605 // Do the outer dimension, which might not be known for a runtime-sized array
1606 if (type.isRuntimeSizedArray()) {
1607 spvType = builder.makeRuntimeArray(spvType);
1608 } else {
1609 assert(type.getOuterArraySize() > 0);
1610 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1611 }
1612
John Kessenich55e7d112015-11-15 21:33:39 -07001613 // TODO: explicit layout still needs to be done hierarchically for arrays of arrays, which
John Kessenichc9a80832015-09-12 12:17:44 -06001614 // may still require additional "link time" support from the front-end
1615 // for arrays of arrays
John Kessenich55e7d112015-11-15 21:33:39 -07001616
1617 // We need to decorate array strides for types needing explicit layout,
1618 // except for the very top if it is an array of blocks; that array is
1619 // not laid out in memory in a way needing a stride.
1620 if (explicitLayout && type.getBasicType() != glslang::EbtBlock)
John Kessenich31ed4832015-09-09 17:51:38 -06001621 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001622 }
1623
1624 return spvType;
1625}
1626
John Kessenich31ed4832015-09-09 17:51:38 -06001627bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1628{
1629 return type.getBasicType() == glslang::EbtBlock &&
1630 type.getQualifier().layoutPacking != glslang::ElpShared &&
1631 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1632 (type.getQualifier().storage == glslang::EvqUniform ||
1633 type.getQualifier().storage == glslang::EvqBuffer);
1634}
1635
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001636// Given an array type, returns the integer stride required for that array
1637int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1638{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001639 int size;
John Kesseniche721f492015-12-06 19:17:49 -07001640 int stride = glslangIntermediate->getBaseAlignment(arrayType, size, arrayType.getQualifier().layoutPacking == glslang::ElpStd140);
1641 if (arrayType.isMatrix()) {
1642 // GLSL strides are set to alignments of the matrix flattened to individual rows/cols,
1643 // but SPV needs an array stride for the whole matrix, not the rows/cols
1644 if (arrayType.getQualifier().layoutMatrix == glslang::ElmRowMajor)
1645 stride *= arrayType.getMatrixRows();
1646 else
1647 stride *= arrayType.getMatrixCols();
1648 }
1649
1650 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001651}
1652
1653// Given a matrix type, returns the integer stride required for that matrix
1654// when used as a member of an interface block
1655int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1656{
1657 int size;
John Kesseniche721f492015-12-06 19:17:49 -07001658 return glslangIntermediate->getBaseAlignment(matrixType, size, matrixType.getQualifier().layoutPacking == glslang::ElpStd140);
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001659}
1660
John Kessenich5e4b1242015-08-06 22:53:06 -06001661// Given a member type of a struct, realign the current offset for it, and compute
1662// the next (not yet aligned) offset for the next member, which will get aligned
1663// on the next call.
1664// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1665// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1666// -1 means a non-forced member offset (no decoration needed).
1667void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1668{
1669 // this will get a positive value when deemed necessary
1670 nextOffset = -1;
1671
1672 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1673 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1674
1675 // override anything in currentOffset with user-set offset
1676 if (memberType.getQualifier().hasOffset())
1677 currentOffset = memberType.getQualifier().layoutOffset;
1678
1679 // It could be that current linker usage in glslang updated all the layoutOffset,
1680 // in which case the following code does not matter. But, that's not quite right
1681 // once cross-compilation unit GLSL validation is done, as the original user
1682 // settings are needed in layoutOffset, and then the following will come into play.
1683
1684 if (! forceOffset) {
1685 if (! memberType.getQualifier().hasOffset())
1686 currentOffset = -1;
1687
1688 return;
1689 }
1690
1691 // Getting this far means we are forcing offsets
1692 if (currentOffset < 0)
1693 currentOffset = 0;
1694
1695 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1696 // but possibly not yet correctly aligned.
1697
1698 int memberSize;
1699 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1700 glslang::RoundToPow2(currentOffset, memberAlignment);
1701 nextOffset = currentOffset + memberSize;
1702}
1703
John Kessenich140f3df2015-06-26 16:58:36 -06001704bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1705{
1706 return node->getName() == "main(";
1707}
1708
1709// Make all the functions, skeletally, without actually visiting their bodies.
1710void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1711{
1712 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1713 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1714 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1715 continue;
1716
1717 // We're on a user function. Set up the basic interface for the function now,
1718 // so that it's available to call.
1719 // Translating the body will happen later.
1720 //
1721 // Typically (except for a "const in" parameter), an address will be passed to the
1722 // function. What it is an address of varies:
1723 //
1724 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1725 // so that write needs to be to a copy, hence the address of a copy works.
1726 //
1727 // - "const in" parameters can just be the r-value, as no writes need occur.
1728 //
1729 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1730 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1731
1732 std::vector<spv::Id> paramTypes;
1733 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1734
1735 for (int p = 0; p < (int)parameters.size(); ++p) {
1736 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1737 spv::Id typeId = convertGlslangToSpvType(paramType);
1738 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1739 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1740 else
1741 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1742 paramTypes.push_back(typeId);
1743 }
1744
1745 spv::Block* functionBlock;
1746 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1747 paramTypes, &functionBlock);
1748
1749 // Track function to emit/call later
1750 functionMap[glslFunction->getName().c_str()] = function;
1751
1752 // Set the parameter id's
1753 for (int p = 0; p < (int)parameters.size(); ++p) {
1754 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1755 // give a name too
1756 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1757 }
1758 }
1759}
1760
1761// Process all the initializers, while skipping the functions and link objects
1762void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1763{
1764 builder.setBuildPoint(shaderEntry->getLastBlock());
1765 for (int i = 0; i < (int)initializers.size(); ++i) {
1766 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1767 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1768
1769 // We're on a top-level node that's not a function. Treat as an initializer, whose
1770 // code goes into the beginning of main.
1771 initializer->traverse(this);
1772 }
1773 }
1774}
1775
1776// Process all the functions, while skipping initializers.
1777void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1778{
1779 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1780 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1781 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1782 node->traverse(this);
1783 }
1784}
1785
1786void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1787{
1788 // SPIR-V functions should already be in the functionMap from the prepass
1789 // that called makeFunctions().
1790 spv::Function* function = functionMap[node->getName().c_str()];
1791 spv::Block* functionBlock = function->getEntryBlock();
1792 builder.setBuildPoint(functionBlock);
1793}
1794
Rex Xu04db3f52015-09-16 11:44:02 +08001795void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001796{
Rex Xufc618912015-09-09 16:42:49 +08001797 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001798 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1799 builder.clearAccessChain();
1800 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001801
1802 // Special case l-value operands
1803 bool lvalue = false;
1804 switch (node.getOp()) {
1805 case glslang::EOpImageAtomicAdd:
1806 case glslang::EOpImageAtomicMin:
1807 case glslang::EOpImageAtomicMax:
1808 case glslang::EOpImageAtomicAnd:
1809 case glslang::EOpImageAtomicOr:
1810 case glslang::EOpImageAtomicXor:
1811 case glslang::EOpImageAtomicExchange:
1812 case glslang::EOpImageAtomicCompSwap:
1813 if (i == 0)
1814 lvalue = true;
1815 break;
1816 default:
1817 break;
1818 }
1819
Rex Xu6b86d492015-09-16 17:48:22 +08001820 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001821 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001822 else
Rex Xu30f92582015-09-14 10:38:56 +08001823 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001824 }
1825}
1826
John Kessenichfc51d282015-08-19 13:34:18 -06001827void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001828{
John Kessenichfc51d282015-08-19 13:34:18 -06001829 builder.clearAccessChain();
1830 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001831 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001832}
John Kessenich140f3df2015-06-26 16:58:36 -06001833
John Kessenichfc51d282015-08-19 13:34:18 -06001834spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1835{
Rex Xufc618912015-09-09 16:42:49 +08001836 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001837 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001838 }
1839
John Kessenichfc51d282015-08-19 13:34:18 -06001840 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001841 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1842 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1843 std::vector<spv::Id> arguments;
1844 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001845 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001846 else
1847 translateArguments(*node->getAsUnaryNode(), arguments);
1848 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1849
1850 spv::Builder::TextureParameters params = { };
1851 params.sampler = arguments[0];
1852
Rex Xu04db3f52015-09-16 11:44:02 +08001853 glslang::TCrackedTextureOp cracked;
1854 node->crackTexture(sampler, cracked);
1855
John Kessenichfc51d282015-08-19 13:34:18 -06001856 // Check for queries
1857 if (cracked.query) {
1858 switch (node->getOp()) {
1859 case glslang::EOpImageQuerySize:
1860 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001861 if (arguments.size() > 1) {
1862 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001863 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001864 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001865 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001866 case glslang::EOpImageQuerySamples:
1867 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001868 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001869 case glslang::EOpTextureQueryLod:
1870 params.coords = arguments[1];
1871 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1872 case glslang::EOpTextureQueryLevels:
1873 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1874 default:
1875 assert(0);
1876 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001877 }
John Kessenich140f3df2015-06-26 16:58:36 -06001878 }
1879
Rex Xufc618912015-09-09 16:42:49 +08001880 // Check for image functions other than queries
1881 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001882 std::vector<spv::Id> operands;
1883 auto opIt = arguments.begin();
1884 operands.push_back(*(opIt++));
1885 operands.push_back(*(opIt++));
1886 if (node->getOp() == glslang::EOpImageStore)
Rex Xu6b86d492015-09-16 17:48:22 +08001887 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001888 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07001889 if (sampler.ms) {
1890 operands.push_back(spv::ImageOperandsSampleMask);
1891 operands.push_back(*(opIt++));
1892 }
John Kessenich56bab042015-09-16 10:54:31 -06001893 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1894 } else if (node->getOp() == glslang::EOpImageStore) {
1895 builder.createNoResultOp(spv::OpImageWrite, operands);
1896 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001897 } else {
1898 // Process image atomic operations
1899
1900 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1901 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001902 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001903
Rex Xufc618912015-09-09 16:42:49 +08001904 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001905 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001906
1907 std::vector<spv::Id> operands;
1908 operands.push_back(pointer);
1909 for (; opIt != arguments.end(); ++opIt)
1910 operands.push_back(*opIt);
1911
Rex Xu04db3f52015-09-16 11:44:02 +08001912 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001913 }
1914 }
1915
1916 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001917
Rex Xu71519fe2015-11-11 15:35:47 +08001918 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1919
John Kessenichfc51d282015-08-19 13:34:18 -06001920 // check for bias argument
1921 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08001922 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06001923 int nonBiasArgCount = 2;
1924 if (cracked.offset)
1925 ++nonBiasArgCount;
1926 if (cracked.grad)
1927 nonBiasArgCount += 2;
1928
1929 if ((int)arguments.size() > nonBiasArgCount)
1930 bias = true;
1931 }
1932
John Kessenichfc51d282015-08-19 13:34:18 -06001933 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07001934
John Kessenichfc51d282015-08-19 13:34:18 -06001935 params.coords = arguments[1];
1936 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001937
1938 // sort out where Dref is coming from
1939 if (sampler.shadow && sampler.dim == glslang::EsdCube && sampler.arrayed)
John Kessenichfc51d282015-08-19 13:34:18 -06001940 params.Dref = arguments[2];
John Kessenich55e7d112015-11-15 21:33:39 -07001941 else if (sampler.shadow && cracked.gather) {
1942 params.Dref = arguments[2];
1943 ++extraArgs;
1944 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06001945 std::vector<spv::Id> indexes;
1946 int comp;
1947 if (cracked.proj)
1948 comp = 3;
1949 else
1950 comp = builder.getNumComponents(params.coords) - 1;
1951 indexes.push_back(comp);
1952 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1953 }
1954 if (cracked.lod) {
1955 params.lod = arguments[2];
1956 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08001957 } else if (sampler.ms) {
1958 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08001959 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001960 }
1961 if (cracked.grad) {
1962 params.gradX = arguments[2 + extraArgs];
1963 params.gradY = arguments[3 + extraArgs];
1964 extraArgs += 2;
1965 }
John Kessenich55e7d112015-11-15 21:33:39 -07001966 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06001967 params.offset = arguments[2 + extraArgs];
1968 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07001969 } else if (cracked.offsets) {
1970 params.offsets = arguments[2 + extraArgs];
1971 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001972 }
1973 if (bias) {
1974 params.bias = arguments[2 + extraArgs];
1975 ++extraArgs;
1976 }
John Kessenich55e7d112015-11-15 21:33:39 -07001977 if (cracked.gather && ! sampler.shadow) {
1978 // default component is 0, if missing, otherwise an argument
1979 if (2 + extraArgs < (int)arguments.size()) {
1980 params.comp = arguments[2 + extraArgs];
1981 ++extraArgs;
1982 } else {
1983 params.comp = builder.makeIntConstant(0);
1984 }
1985 }
John Kessenichfc51d282015-08-19 13:34:18 -06001986
John Kessenich55e7d112015-11-15 21:33:39 -07001987 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001988}
1989
1990spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1991{
1992 // Grab the function's pointer from the previously created function
1993 spv::Function* function = functionMap[node->getName().c_str()];
1994 if (! function)
1995 return 0;
1996
1997 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1998 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1999
2000 // See comments in makeFunctions() for details about the semantics for parameter passing.
2001 //
2002 // These imply we need a four step process:
2003 // 1. Evaluate the arguments
2004 // 2. Allocate and make copies of in, out, and inout arguments
2005 // 3. Make the call
2006 // 4. Copy back the results
2007
2008 // 1. Evaluate the arguments
2009 std::vector<spv::Builder::AccessChain> lValues;
2010 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002011 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002012 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2013 // build l-value
2014 builder.clearAccessChain();
2015 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002016 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002017 // keep outputs as l-values, evaluate input-only as r-values
2018 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2019 // save l-value
2020 lValues.push_back(builder.getAccessChain());
2021 } else {
2022 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002023 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002024 }
2025 }
2026
2027 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2028 // copy the original into that space.
2029 //
2030 // Also, build up the list of actual arguments to pass in for the call
2031 int lValueCount = 0;
2032 int rValueCount = 0;
2033 std::vector<spv::Id> spvArgs;
2034 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2035 spv::Id arg;
2036 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2037 // need space to hold the copy
2038 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2039 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2040 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2041 // need to copy the input into output space
2042 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002043 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002044 builder.createStore(copy, arg);
2045 }
2046 ++lValueCount;
2047 } else {
2048 arg = rValues[rValueCount];
2049 ++rValueCount;
2050 }
2051 spvArgs.push_back(arg);
2052 }
2053
2054 // 3. Make the call.
2055 spv::Id result = builder.createFunctionCall(function, spvArgs);
2056
2057 // 4. Copy back out an "out" arguments.
2058 lValueCount = 0;
2059 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2060 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2061 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2062 spv::Id copy = builder.createLoad(spvArgs[a]);
2063 builder.setAccessChain(lValues[lValueCount]);
2064 builder.accessChainStore(copy);
2065 }
2066 ++lValueCount;
2067 }
2068 }
2069
2070 return result;
2071}
2072
2073// Translate AST operation to SPV operation, already having SPV-based operands/types.
2074spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2075 spv::Id typeId, spv::Id left, spv::Id right,
2076 glslang::TBasicType typeProxy, bool reduceComparison)
2077{
2078 bool isUnsigned = typeProxy == glslang::EbtUint;
2079 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2080
2081 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002082 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002083 bool comparison = false;
2084
2085 switch (op) {
2086 case glslang::EOpAdd:
2087 case glslang::EOpAddAssign:
2088 if (isFloat)
2089 binOp = spv::OpFAdd;
2090 else
2091 binOp = spv::OpIAdd;
2092 break;
2093 case glslang::EOpSub:
2094 case glslang::EOpSubAssign:
2095 if (isFloat)
2096 binOp = spv::OpFSub;
2097 else
2098 binOp = spv::OpISub;
2099 break;
2100 case glslang::EOpMul:
2101 case glslang::EOpMulAssign:
2102 if (isFloat)
2103 binOp = spv::OpFMul;
2104 else
2105 binOp = spv::OpIMul;
2106 break;
2107 case glslang::EOpVectorTimesScalar:
2108 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002109 if (isFloat) {
2110 if (builder.isVector(right))
2111 std::swap(left, right);
2112 assert(builder.isScalar(right));
2113 needMatchingVectors = false;
2114 binOp = spv::OpVectorTimesScalar;
2115 } else
2116 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002117 break;
2118 case glslang::EOpVectorTimesMatrix:
2119 case glslang::EOpVectorTimesMatrixAssign:
2120 assert(builder.isVector(left));
2121 assert(builder.isMatrix(right));
2122 binOp = spv::OpVectorTimesMatrix;
2123 break;
2124 case glslang::EOpMatrixTimesVector:
2125 assert(builder.isMatrix(left));
2126 assert(builder.isVector(right));
2127 binOp = spv::OpMatrixTimesVector;
2128 break;
2129 case glslang::EOpMatrixTimesScalar:
2130 case glslang::EOpMatrixTimesScalarAssign:
2131 if (builder.isMatrix(right))
2132 std::swap(left, right);
2133 assert(builder.isScalar(right));
2134 binOp = spv::OpMatrixTimesScalar;
2135 break;
2136 case glslang::EOpMatrixTimesMatrix:
2137 case glslang::EOpMatrixTimesMatrixAssign:
2138 assert(builder.isMatrix(left));
2139 assert(builder.isMatrix(right));
2140 binOp = spv::OpMatrixTimesMatrix;
2141 break;
2142 case glslang::EOpOuterProduct:
2143 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002144 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002145 break;
2146
2147 case glslang::EOpDiv:
2148 case glslang::EOpDivAssign:
2149 if (isFloat)
2150 binOp = spv::OpFDiv;
2151 else if (isUnsigned)
2152 binOp = spv::OpUDiv;
2153 else
2154 binOp = spv::OpSDiv;
2155 break;
2156 case glslang::EOpMod:
2157 case glslang::EOpModAssign:
2158 if (isFloat)
2159 binOp = spv::OpFMod;
2160 else if (isUnsigned)
2161 binOp = spv::OpUMod;
2162 else
2163 binOp = spv::OpSMod;
2164 break;
2165 case glslang::EOpRightShift:
2166 case glslang::EOpRightShiftAssign:
2167 if (isUnsigned)
2168 binOp = spv::OpShiftRightLogical;
2169 else
2170 binOp = spv::OpShiftRightArithmetic;
2171 break;
2172 case glslang::EOpLeftShift:
2173 case glslang::EOpLeftShiftAssign:
2174 binOp = spv::OpShiftLeftLogical;
2175 break;
2176 case glslang::EOpAnd:
2177 case glslang::EOpAndAssign:
2178 binOp = spv::OpBitwiseAnd;
2179 break;
2180 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002181 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002182 binOp = spv::OpLogicalAnd;
2183 break;
2184 case glslang::EOpInclusiveOr:
2185 case glslang::EOpInclusiveOrAssign:
2186 binOp = spv::OpBitwiseOr;
2187 break;
2188 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002189 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002190 binOp = spv::OpLogicalOr;
2191 break;
2192 case glslang::EOpExclusiveOr:
2193 case glslang::EOpExclusiveOrAssign:
2194 binOp = spv::OpBitwiseXor;
2195 break;
2196 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002197 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002198 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002199 break;
2200
2201 case glslang::EOpLessThan:
2202 case glslang::EOpGreaterThan:
2203 case glslang::EOpLessThanEqual:
2204 case glslang::EOpGreaterThanEqual:
2205 case glslang::EOpEqual:
2206 case glslang::EOpNotEqual:
2207 case glslang::EOpVectorEqual:
2208 case glslang::EOpVectorNotEqual:
2209 comparison = true;
2210 break;
2211 default:
2212 break;
2213 }
2214
John Kessenich7c1aa102015-10-15 13:29:11 -06002215 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002216 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002217 assert(comparison == false);
John Kessenich140f3df2015-06-26 16:58:36 -06002218 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2219 switch (binOp) {
2220 case spv::OpMatrixTimesScalar:
2221 case spv::OpVectorTimesMatrix:
2222 case spv::OpMatrixTimesVector:
2223 case spv::OpMatrixTimesMatrix:
2224 break;
2225 case spv::OpFDiv:
2226 // turn it into a multiply...
2227 assert(builder.isMatrix(left) && builder.isScalar(right));
2228 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2229 binOp = spv::OpFMul;
2230 break;
2231 default:
2232 spv::MissingFunctionality("binary operation on matrix");
2233 break;
2234 }
2235
2236 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2237 builder.setPrecision(id, precision);
2238
2239 return id;
2240 }
2241
2242 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002243 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002244 builder.promoteScalar(precision, left, right);
2245
2246 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2247 builder.setPrecision(id, precision);
2248
2249 return id;
2250 }
2251
2252 if (! comparison)
2253 return 0;
2254
John Kessenich7c1aa102015-10-15 13:29:11 -06002255 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002256
2257 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2258 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2259
2260 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2261 }
2262
2263 switch (op) {
2264 case glslang::EOpLessThan:
2265 if (isFloat)
2266 binOp = spv::OpFOrdLessThan;
2267 else if (isUnsigned)
2268 binOp = spv::OpULessThan;
2269 else
2270 binOp = spv::OpSLessThan;
2271 break;
2272 case glslang::EOpGreaterThan:
2273 if (isFloat)
2274 binOp = spv::OpFOrdGreaterThan;
2275 else if (isUnsigned)
2276 binOp = spv::OpUGreaterThan;
2277 else
2278 binOp = spv::OpSGreaterThan;
2279 break;
2280 case glslang::EOpLessThanEqual:
2281 if (isFloat)
2282 binOp = spv::OpFOrdLessThanEqual;
2283 else if (isUnsigned)
2284 binOp = spv::OpULessThanEqual;
2285 else
2286 binOp = spv::OpSLessThanEqual;
2287 break;
2288 case glslang::EOpGreaterThanEqual:
2289 if (isFloat)
2290 binOp = spv::OpFOrdGreaterThanEqual;
2291 else if (isUnsigned)
2292 binOp = spv::OpUGreaterThanEqual;
2293 else
2294 binOp = spv::OpSGreaterThanEqual;
2295 break;
2296 case glslang::EOpEqual:
2297 case glslang::EOpVectorEqual:
2298 if (isFloat)
2299 binOp = spv::OpFOrdEqual;
2300 else
2301 binOp = spv::OpIEqual;
2302 break;
2303 case glslang::EOpNotEqual:
2304 case glslang::EOpVectorNotEqual:
2305 if (isFloat)
2306 binOp = spv::OpFOrdNotEqual;
2307 else
2308 binOp = spv::OpINotEqual;
2309 break;
2310 default:
2311 break;
2312 }
2313
2314 if (binOp != spv::OpNop) {
2315 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2316 builder.setPrecision(id, precision);
2317
2318 return id;
2319 }
2320
2321 return 0;
2322}
2323
Rex Xu04db3f52015-09-16 11:44:02 +08002324spv::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 -06002325{
2326 spv::Op unaryOp = spv::OpNop;
2327 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002328 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002329 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002330
2331 switch (op) {
2332 case glslang::EOpNegative:
2333 if (isFloat)
2334 unaryOp = spv::OpFNegate;
2335 else
2336 unaryOp = spv::OpSNegate;
2337 break;
2338
2339 case glslang::EOpLogicalNot:
2340 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002341 unaryOp = spv::OpLogicalNot;
2342 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002343 case glslang::EOpBitwiseNot:
2344 unaryOp = spv::OpNot;
2345 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002346
John Kessenich140f3df2015-06-26 16:58:36 -06002347 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002348 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002349 break;
2350 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002351 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002352 break;
2353 case glslang::EOpTranspose:
2354 unaryOp = spv::OpTranspose;
2355 break;
2356
2357 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002358 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002359 break;
2360 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002361 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002362 break;
2363 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002364 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002365 break;
2366 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002367 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002368 break;
2369 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002370 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002371 break;
2372 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002373 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002374 break;
2375 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002376 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002377 break;
2378 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002379 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002380 break;
2381
2382 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002383 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002384 break;
2385 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002386 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002387 break;
2388 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002389 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002390 break;
2391 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002392 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002393 break;
2394 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002395 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002396 break;
2397 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002398 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002399 break;
2400
2401 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002402 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002403 break;
2404 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002405 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002406 break;
2407
2408 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002409 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002410 break;
2411 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002412 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002413 break;
2414 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002415 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002416 break;
2417 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002418 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002419 break;
2420 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002421 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002422 break;
2423 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002424 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002425 break;
2426
2427 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002428 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002429 break;
2430 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002431 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002432 break;
2433 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002434 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002435 break;
2436 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002437 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002438 break;
2439 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002440 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002441 break;
2442 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002443 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002444 break;
2445
2446 case glslang::EOpIsNan:
2447 unaryOp = spv::OpIsNan;
2448 break;
2449 case glslang::EOpIsInf:
2450 unaryOp = spv::OpIsInf;
2451 break;
2452
John Kessenich140f3df2015-06-26 16:58:36 -06002453 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002454 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002455 break;
2456 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002457 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002458 break;
2459 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002460 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002461 break;
2462 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002463 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002464 break;
2465 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002466 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002467 break;
2468 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002469 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002470 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002471 case glslang::EOpPackSnorm4x8:
2472 libCall = spv::GLSLstd450PackSnorm4x8;
2473 break;
2474 case glslang::EOpUnpackSnorm4x8:
2475 libCall = spv::GLSLstd450UnpackSnorm4x8;
2476 break;
2477 case glslang::EOpPackUnorm4x8:
2478 libCall = spv::GLSLstd450PackUnorm4x8;
2479 break;
2480 case glslang::EOpUnpackUnorm4x8:
2481 libCall = spv::GLSLstd450UnpackUnorm4x8;
2482 break;
2483 case glslang::EOpPackDouble2x32:
2484 libCall = spv::GLSLstd450PackDouble2x32;
2485 break;
2486 case glslang::EOpUnpackDouble2x32:
2487 libCall = spv::GLSLstd450UnpackDouble2x32;
2488 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002489
2490 case glslang::EOpDPdx:
2491 unaryOp = spv::OpDPdx;
2492 break;
2493 case glslang::EOpDPdy:
2494 unaryOp = spv::OpDPdy;
2495 break;
2496 case glslang::EOpFwidth:
2497 unaryOp = spv::OpFwidth;
2498 break;
2499 case glslang::EOpDPdxFine:
2500 unaryOp = spv::OpDPdxFine;
2501 break;
2502 case glslang::EOpDPdyFine:
2503 unaryOp = spv::OpDPdyFine;
2504 break;
2505 case glslang::EOpFwidthFine:
2506 unaryOp = spv::OpFwidthFine;
2507 break;
2508 case glslang::EOpDPdxCoarse:
2509 unaryOp = spv::OpDPdxCoarse;
2510 break;
2511 case glslang::EOpDPdyCoarse:
2512 unaryOp = spv::OpDPdyCoarse;
2513 break;
2514 case glslang::EOpFwidthCoarse:
2515 unaryOp = spv::OpFwidthCoarse;
2516 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002517 case glslang::EOpInterpolateAtCentroid:
2518 libCall = spv::GLSLstd450InterpolateAtCentroid;
2519 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002520 case glslang::EOpAny:
2521 unaryOp = spv::OpAny;
2522 break;
2523 case glslang::EOpAll:
2524 unaryOp = spv::OpAll;
2525 break;
2526
2527 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002528 if (isFloat)
2529 libCall = spv::GLSLstd450FAbs;
2530 else
2531 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002532 break;
2533 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002534 if (isFloat)
2535 libCall = spv::GLSLstd450FSign;
2536 else
2537 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002538 break;
2539
John Kessenichfc51d282015-08-19 13:34:18 -06002540 case glslang::EOpAtomicCounterIncrement:
2541 case glslang::EOpAtomicCounterDecrement:
2542 case glslang::EOpAtomicCounter:
2543 {
2544 // Handle all of the atomics in one place, in createAtomicOperation()
2545 std::vector<spv::Id> operands;
2546 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002547 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002548 }
2549
2550 case glslang::EOpImageLoad:
2551 unaryOp = spv::OpImageRead;
2552 break;
2553
2554 case glslang::EOpBitFieldReverse:
2555 unaryOp = spv::OpBitReverse;
2556 break;
2557 case glslang::EOpBitCount:
2558 unaryOp = spv::OpBitCount;
2559 break;
2560 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002561 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002562 break;
2563 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002564 if (isUnsigned)
2565 libCall = spv::GLSLstd450FindUMsb;
2566 else
2567 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002568 break;
2569
John Kessenich140f3df2015-06-26 16:58:36 -06002570 default:
2571 return 0;
2572 }
2573
2574 spv::Id id;
2575 if (libCall >= 0) {
2576 std::vector<spv::Id> args;
2577 args.push_back(operand);
2578 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2579 } else
2580 id = builder.createUnaryOp(unaryOp, typeId, operand);
2581
2582 builder.setPrecision(id, precision);
2583
2584 return id;
2585}
2586
2587spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2588{
2589 spv::Op convOp = spv::OpNop;
2590 spv::Id zero = 0;
2591 spv::Id one = 0;
2592
2593 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2594
2595 switch (op) {
2596 case glslang::EOpConvIntToBool:
2597 case glslang::EOpConvUintToBool:
2598 zero = builder.makeUintConstant(0);
2599 zero = makeSmearedConstant(zero, vectorSize);
2600 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2601
2602 case glslang::EOpConvFloatToBool:
2603 zero = builder.makeFloatConstant(0.0F);
2604 zero = makeSmearedConstant(zero, vectorSize);
2605 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2606
2607 case glslang::EOpConvDoubleToBool:
2608 zero = builder.makeDoubleConstant(0.0);
2609 zero = makeSmearedConstant(zero, vectorSize);
2610 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2611
2612 case glslang::EOpConvBoolToFloat:
2613 convOp = spv::OpSelect;
2614 zero = builder.makeFloatConstant(0.0);
2615 one = builder.makeFloatConstant(1.0);
2616 break;
2617 case glslang::EOpConvBoolToDouble:
2618 convOp = spv::OpSelect;
2619 zero = builder.makeDoubleConstant(0.0);
2620 one = builder.makeDoubleConstant(1.0);
2621 break;
2622 case glslang::EOpConvBoolToInt:
2623 zero = builder.makeIntConstant(0);
2624 one = builder.makeIntConstant(1);
2625 convOp = spv::OpSelect;
2626 break;
2627 case glslang::EOpConvBoolToUint:
2628 zero = builder.makeUintConstant(0);
2629 one = builder.makeUintConstant(1);
2630 convOp = spv::OpSelect;
2631 break;
2632
2633 case glslang::EOpConvIntToFloat:
2634 case glslang::EOpConvIntToDouble:
2635 convOp = spv::OpConvertSToF;
2636 break;
2637
2638 case glslang::EOpConvUintToFloat:
2639 case glslang::EOpConvUintToDouble:
2640 convOp = spv::OpConvertUToF;
2641 break;
2642
2643 case glslang::EOpConvDoubleToFloat:
2644 case glslang::EOpConvFloatToDouble:
2645 convOp = spv::OpFConvert;
2646 break;
2647
2648 case glslang::EOpConvFloatToInt:
2649 case glslang::EOpConvDoubleToInt:
2650 convOp = spv::OpConvertFToS;
2651 break;
2652
2653 case glslang::EOpConvUintToInt:
2654 case glslang::EOpConvIntToUint:
2655 convOp = spv::OpBitcast;
2656 break;
2657
2658 case glslang::EOpConvFloatToUint:
2659 case glslang::EOpConvDoubleToUint:
2660 convOp = spv::OpConvertFToU;
2661 break;
2662 default:
2663 break;
2664 }
2665
2666 spv::Id result = 0;
2667 if (convOp == spv::OpNop)
2668 return result;
2669
2670 if (convOp == spv::OpSelect) {
2671 zero = makeSmearedConstant(zero, vectorSize);
2672 one = makeSmearedConstant(one, vectorSize);
2673 result = builder.createTriOp(convOp, destType, operand, one, zero);
2674 } else
2675 result = builder.createUnaryOp(convOp, destType, operand);
2676
2677 builder.setPrecision(result, precision);
2678
2679 return result;
2680}
2681
2682spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2683{
2684 if (vectorSize == 0)
2685 return constant;
2686
2687 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2688 std::vector<spv::Id> components;
2689 for (int c = 0; c < vectorSize; ++c)
2690 components.push_back(constant);
2691 return builder.makeCompositeConstant(vectorTypeId, components);
2692}
2693
John Kessenich426394d2015-07-23 10:22:48 -06002694// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002695spv::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 -06002696{
2697 spv::Op opCode = spv::OpNop;
2698
2699 switch (op) {
2700 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002701 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002702 opCode = spv::OpAtomicIAdd;
2703 break;
2704 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002705 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002706 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002707 break;
2708 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002709 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002710 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002711 break;
2712 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002713 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002714 opCode = spv::OpAtomicAnd;
2715 break;
2716 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002717 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002718 opCode = spv::OpAtomicOr;
2719 break;
2720 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002721 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002722 opCode = spv::OpAtomicXor;
2723 break;
2724 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002725 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002726 opCode = spv::OpAtomicExchange;
2727 break;
2728 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002729 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002730 opCode = spv::OpAtomicCompareExchange;
2731 break;
2732 case glslang::EOpAtomicCounterIncrement:
2733 opCode = spv::OpAtomicIIncrement;
2734 break;
2735 case glslang::EOpAtomicCounterDecrement:
2736 opCode = spv::OpAtomicIDecrement;
2737 break;
2738 case glslang::EOpAtomicCounter:
2739 opCode = spv::OpAtomicLoad;
2740 break;
2741 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002742 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06002743 break;
2744 }
2745
2746 // Sort out the operands
2747 // - mapping from glslang -> SPV
2748 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002749 // - compare-exchange swaps the value and comparator
2750 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002751 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2752 auto opIt = operands.begin(); // walk the glslang operands
2753 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002754 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2755 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2756 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002757 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2758 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002759 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002760 spvAtomicOperands.push_back(*(opIt + 1));
2761 spvAtomicOperands.push_back(*opIt);
2762 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002763 }
John Kessenich426394d2015-07-23 10:22:48 -06002764
John Kessenich3e60a6f2015-09-14 22:45:16 -06002765 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002766 for (; opIt != operands.end(); ++opIt)
2767 spvAtomicOperands.push_back(*opIt);
2768
2769 return builder.createOp(opCode, typeId, spvAtomicOperands);
2770}
2771
John Kessenich5e4b1242015-08-06 22:53:06 -06002772spv::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 -06002773{
John Kessenich5e4b1242015-08-06 22:53:06 -06002774 bool isUnsigned = typeProxy == glslang::EbtUint;
2775 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2776
John Kessenich140f3df2015-06-26 16:58:36 -06002777 spv::Op opCode = spv::OpNop;
2778 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002779 int consumedOperands = operands.size();
2780 spv::Id typeId0 = 0;
2781 if (consumedOperands > 0)
2782 typeId0 = builder.getTypeId(operands[0]);
2783 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002784
2785 switch (op) {
2786 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002787 if (isFloat)
2788 libCall = spv::GLSLstd450FMin;
2789 else if (isUnsigned)
2790 libCall = spv::GLSLstd450UMin;
2791 else
2792 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002793 break;
2794 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002795 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002796 break;
2797 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002798 if (isFloat)
2799 libCall = spv::GLSLstd450FMax;
2800 else if (isUnsigned)
2801 libCall = spv::GLSLstd450UMax;
2802 else
2803 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002804 break;
2805 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002806 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002807 break;
2808 case glslang::EOpDot:
2809 opCode = spv::OpDot;
2810 break;
2811 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002812 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002813 break;
2814
2815 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002816 if (isFloat)
2817 libCall = spv::GLSLstd450FClamp;
2818 else if (isUnsigned)
2819 libCall = spv::GLSLstd450UClamp;
2820 else
2821 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002822 break;
2823 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07002824 if (isFloat)
2825 libCall = spv::GLSLstd450FMix;
2826 else
2827 libCall = spv::GLSLstd450IMix;
John Kessenich140f3df2015-06-26 16:58:36 -06002828 break;
2829 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002830 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002831 break;
2832 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002833 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002834 break;
2835
2836 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002837 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002838 break;
2839 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002840 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002841 break;
2842 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002843 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002844 break;
2845 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002846 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002847 break;
2848 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002849 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002850 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002851 case glslang::EOpInterpolateAtSample:
2852 libCall = spv::GLSLstd450InterpolateAtSample;
2853 break;
2854 case glslang::EOpInterpolateAtOffset:
2855 libCall = spv::GLSLstd450InterpolateAtOffset;
2856 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002857 case glslang::EOpAddCarry:
2858 opCode = spv::OpIAddCarry;
2859 typeId = builder.makeStructResultType(typeId0, typeId0);
2860 consumedOperands = 2;
2861 break;
2862 case glslang::EOpSubBorrow:
2863 opCode = spv::OpISubBorrow;
2864 typeId = builder.makeStructResultType(typeId0, typeId0);
2865 consumedOperands = 2;
2866 break;
2867 case glslang::EOpUMulExtended:
2868 opCode = spv::OpUMulExtended;
2869 typeId = builder.makeStructResultType(typeId0, typeId0);
2870 consumedOperands = 2;
2871 break;
2872 case glslang::EOpIMulExtended:
2873 opCode = spv::OpSMulExtended;
2874 typeId = builder.makeStructResultType(typeId0, typeId0);
2875 consumedOperands = 2;
2876 break;
2877 case glslang::EOpBitfieldExtract:
2878 if (isUnsigned)
2879 opCode = spv::OpBitFieldUExtract;
2880 else
2881 opCode = spv::OpBitFieldSExtract;
2882 break;
2883 case glslang::EOpBitfieldInsert:
2884 opCode = spv::OpBitFieldInsert;
2885 break;
2886
2887 case glslang::EOpFma:
2888 libCall = spv::GLSLstd450Fma;
2889 break;
2890 case glslang::EOpFrexp:
2891 libCall = spv::GLSLstd450FrexpStruct;
2892 if (builder.getNumComponents(operands[0]) == 1)
2893 frexpIntType = builder.makeIntegerType(32, true);
2894 else
2895 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
2896 typeId = builder.makeStructResultType(typeId0, frexpIntType);
2897 consumedOperands = 1;
2898 break;
2899 case glslang::EOpLdexp:
2900 libCall = spv::GLSLstd450Ldexp;
2901 break;
2902
John Kessenich140f3df2015-06-26 16:58:36 -06002903 default:
2904 return 0;
2905 }
2906
2907 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07002908 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05002909 // Use an extended instruction from the standard library.
2910 // Construct the call arguments, without modifying the original operands vector.
2911 // We might need the remaining arguments, e.g. in the EOpFrexp case.
2912 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
2913 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07002914 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07002915 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06002916 case 0:
2917 // should all be handled by visitAggregate and createNoArgOperation
2918 assert(0);
2919 return 0;
2920 case 1:
2921 // should all be handled by createUnaryOperation
2922 assert(0);
2923 return 0;
2924 case 2:
2925 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2926 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002927 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002928 // anything 3 or over doesn't have l-value operands, so all should be consumed
2929 assert(consumedOperands == operands.size());
2930 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06002931 break;
2932 }
2933 }
2934
John Kessenich55e7d112015-11-15 21:33:39 -07002935 // Decode the return types that were structures
2936 switch (op) {
2937 case glslang::EOpAddCarry:
2938 case glslang::EOpSubBorrow:
2939 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
2940 id = builder.createCompositeExtract(id, typeId0, 0);
2941 break;
2942 case glslang::EOpUMulExtended:
2943 case glslang::EOpIMulExtended:
2944 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
2945 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
2946 break;
2947 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05002948 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07002949 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
2950 id = builder.createCompositeExtract(id, typeId0, 0);
2951 break;
2952 default:
2953 break;
2954 }
2955
John Kessenich140f3df2015-06-26 16:58:36 -06002956 builder.setPrecision(id, precision);
2957
2958 return id;
2959}
2960
2961// Intrinsics with no arguments, no return value, and no precision.
2962spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2963{
2964 // TODO: get the barrier operands correct
2965
2966 switch (op) {
2967 case glslang::EOpEmitVertex:
2968 builder.createNoResultOp(spv::OpEmitVertex);
2969 return 0;
2970 case glslang::EOpEndPrimitive:
2971 builder.createNoResultOp(spv::OpEndPrimitive);
2972 return 0;
2973 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002974 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2975 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002976 return 0;
2977 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002978 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002979 return 0;
2980 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002981 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002982 return 0;
2983 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002984 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002985 return 0;
2986 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002987 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002988 return 0;
2989 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07002990 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002991 return 0;
2992 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07002993 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002994 return 0;
2995 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002996 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06002997 return 0;
2998 }
2999}
3000
3001spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3002{
John Kessenich2f273362015-07-18 22:34:27 -06003003 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003004 spv::Id id;
3005 if (symbolValues.end() != iter) {
3006 id = iter->second;
3007 return id;
3008 }
3009
3010 // it was not found, create it
3011 id = createSpvVariable(symbol);
3012 symbolValues[symbol->getId()] = id;
3013
3014 if (! symbol->getType().isStruct()) {
3015 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
3016 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
3017 if (symbol->getQualifier().hasLocation())
3018 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3019 if (symbol->getQualifier().hasIndex())
3020 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3021 if (symbol->getQualifier().hasComponent())
3022 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3023 if (glslangIntermediate->getXfbMode()) {
3024 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003025 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003026 if (symbol->getQualifier().hasXfbBuffer())
3027 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3028 if (symbol->getQualifier().hasXfbOffset())
3029 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3030 }
3031 }
3032
3033 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
3034 if (symbol->getQualifier().hasStream())
3035 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3036 if (symbol->getQualifier().hasSet())
3037 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3038 if (symbol->getQualifier().hasBinding())
3039 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3040 if (glslangIntermediate->getXfbMode()) {
3041 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003042 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003043 if (symbol->getQualifier().hasXfbBuffer())
3044 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3045 }
3046
3047 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003048 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003049 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003050 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003051
John Kessenich140f3df2015-06-26 16:58:36 -06003052 return id;
3053}
3054
John Kessenich55e7d112015-11-15 21:33:39 -07003055// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003056void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3057{
3058 if (dec != spv::BadValue)
3059 builder.addDecoration(id, dec);
3060}
3061
John Kessenich55e7d112015-11-15 21:33:39 -07003062// If 'dec' is valid, add a one-operand decoration to an object
3063void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3064{
3065 if (dec != spv::BadValue)
3066 builder.addDecoration(id, dec, value);
3067}
3068
3069// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003070void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3071{
3072 if (dec != spv::BadValue)
3073 builder.addMemberDecoration(id, (unsigned)member, dec);
3074}
3075
John Kessenich55e7d112015-11-15 21:33:39 -07003076// Make a full tree of instructions to build a SPIR-V specialization constant,
3077// or regularly constant if possible.
3078//
3079// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3080//
3081// Recursively walk the nodes. The nodes form a tree whose leaves are
3082// regular constants, which themselves are trees that createSpvConstant()
3083// recursively walks. So, this function walks the "top" of the tree:
3084// - emit specialization constant-building instructions for specConstant
3085// - when running into a non-spec-constant, switch to createSpvConstant()
3086spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3087{
3088 assert(node.getQualifier().storage == glslang::EvqConst);
3089
3090 // hand off to the non-spec-constant path
3091 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3092 int nextConst = 0;
3093 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3094}
3095
John Kessenich140f3df2015-06-26 16:58:36 -06003096// Use 'consts' as the flattened glslang source of scalar constants to recursively
3097// build the aggregate SPIR-V constant.
3098//
3099// If there are not enough elements present in 'consts', 0 will be substituted;
3100// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3101//
John Kessenich55e7d112015-11-15 21:33:39 -07003102spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003103{
3104 // vector of constants for SPIR-V
3105 std::vector<spv::Id> spvConsts;
3106
3107 // Type is used for struct and array constants
3108 spv::Id typeId = convertGlslangToSpvType(glslangType);
3109
3110 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003111 glslang::TType elementType(glslangType, 0);
3112 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003113 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003114 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003115 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003116 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003117 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003118 } else if (glslangType.getStruct()) {
3119 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3120 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003121 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003122 } else if (glslangType.isVector()) {
3123 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3124 bool zero = nextConst >= consts.size();
3125 switch (glslangType.getBasicType()) {
3126 case glslang::EbtInt:
3127 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3128 break;
3129 case glslang::EbtUint:
3130 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3131 break;
3132 case glslang::EbtFloat:
3133 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3134 break;
3135 case glslang::EbtDouble:
3136 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3137 break;
3138 case glslang::EbtBool:
3139 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3140 break;
3141 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003142 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003143 break;
3144 }
3145 ++nextConst;
3146 }
3147 } else {
3148 // we have a non-aggregate (scalar) constant
3149 bool zero = nextConst >= consts.size();
3150 spv::Id scalar = 0;
3151 switch (glslangType.getBasicType()) {
3152 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003153 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003154 break;
3155 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003156 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003157 break;
3158 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003159 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003160 break;
3161 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003162 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003163 break;
3164 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003165 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003168 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003169 break;
3170 }
3171 ++nextConst;
3172 return scalar;
3173 }
3174
3175 return builder.makeCompositeConstant(typeId, spvConsts);
3176}
3177
John Kessenich7c1aa102015-10-15 13:29:11 -06003178// Return true if the node is a constant or symbol whose reading has no
3179// non-trivial observable cost or effect.
3180bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3181{
3182 // don't know what this is
3183 if (node == nullptr)
3184 return false;
3185
3186 // a constant is safe
3187 if (node->getAsConstantUnion() != nullptr)
3188 return true;
3189
3190 // not a symbol means non-trivial
3191 if (node->getAsSymbolNode() == nullptr)
3192 return false;
3193
3194 // a symbol, depends on what's being read
3195 switch (node->getType().getQualifier().storage) {
3196 case glslang::EvqTemporary:
3197 case glslang::EvqGlobal:
3198 case glslang::EvqIn:
3199 case glslang::EvqInOut:
3200 case glslang::EvqConst:
3201 case glslang::EvqConstReadOnly:
3202 case glslang::EvqUniform:
3203 return true;
3204 default:
3205 return false;
3206 }
3207}
3208
3209// A node is trivial if it is a single operation with no side effects.
3210// Error on the side of saying non-trivial.
3211// Return true if trivial.
3212bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3213{
3214 if (node == nullptr)
3215 return false;
3216
3217 // symbols and constants are trivial
3218 if (isTrivialLeaf(node))
3219 return true;
3220
3221 // otherwise, it needs to be a simple operation or one or two leaf nodes
3222
3223 // not a simple operation
3224 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3225 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3226 if (binaryNode == nullptr && unaryNode == nullptr)
3227 return false;
3228
3229 // not on leaf nodes
3230 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3231 return false;
3232
3233 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3234 return false;
3235 }
3236
3237 switch (node->getAsOperator()->getOp()) {
3238 case glslang::EOpLogicalNot:
3239 case glslang::EOpConvIntToBool:
3240 case glslang::EOpConvUintToBool:
3241 case glslang::EOpConvFloatToBool:
3242 case glslang::EOpConvDoubleToBool:
3243 case glslang::EOpEqual:
3244 case glslang::EOpNotEqual:
3245 case glslang::EOpLessThan:
3246 case glslang::EOpGreaterThan:
3247 case glslang::EOpLessThanEqual:
3248 case glslang::EOpGreaterThanEqual:
3249 case glslang::EOpIndexDirect:
3250 case glslang::EOpIndexDirectStruct:
3251 case glslang::EOpLogicalXor:
3252 case glslang::EOpAny:
3253 case glslang::EOpAll:
3254 return true;
3255 default:
3256 return false;
3257 }
3258}
3259
3260// Emit short-circuiting code, where 'right' is never evaluated unless
3261// the left side is true (for &&) or false (for ||).
3262spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3263{
3264 spv::Id boolTypeId = builder.makeBoolType();
3265
3266 // emit left operand
3267 builder.clearAccessChain();
3268 left.traverse(this);
3269 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3270
3271 // Operands to accumulate OpPhi operands
3272 std::vector<spv::Id> phiOperands;
3273 // accumulate left operand's phi information
3274 phiOperands.push_back(leftId);
3275 phiOperands.push_back(builder.getBuildPoint()->getId());
3276
3277 // Make the two kinds of operation symmetric with a "!"
3278 // || => emit "if (! left) result = right"
3279 // && => emit "if ( left) result = right"
3280 //
3281 // TODO: this runtime "not" for || could be avoided by adding functionality
3282 // to 'builder' to have an "else" without an "then"
3283 if (op == glslang::EOpLogicalOr)
3284 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3285
3286 // make an "if" based on the left value
3287 spv::Builder::If ifBuilder(leftId, builder);
3288
3289 // emit right operand as the "then" part of the "if"
3290 builder.clearAccessChain();
3291 right.traverse(this);
3292 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3293
3294 // accumulate left operand's phi information
3295 phiOperands.push_back(rightId);
3296 phiOperands.push_back(builder.getBuildPoint()->getId());
3297
3298 // finish the "if"
3299 ifBuilder.makeEndIf();
3300
3301 // phi together the two results
3302 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3303}
3304
John Kessenich140f3df2015-06-26 16:58:36 -06003305}; // end anonymous namespace
3306
3307namespace glslang {
3308
John Kessenich68d78fd2015-07-12 19:28:10 -06003309void GetSpirvVersion(std::string& version)
3310{
John Kessenich9e55f632015-07-15 10:03:39 -06003311 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003312 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003313 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003314 version = buf;
3315}
3316
John Kessenich140f3df2015-06-26 16:58:36 -06003317// Write SPIR-V out to a binary file
3318void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3319{
3320 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003321 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003322 for (int i = 0; i < (int)spirv.size(); ++i) {
3323 unsigned int word = spirv[i];
3324 out.write((const char*)&word, 4);
3325 }
3326 out.close();
3327}
3328
3329//
3330// Set up the glslang traversal
3331//
3332void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3333{
3334 TIntermNode* root = intermediate.getTreeRoot();
3335
3336 if (root == 0)
3337 return;
3338
3339 glslang::GetThreadPoolAllocator().push();
3340
3341 TGlslangToSpvTraverser it(&intermediate);
3342
3343 root->traverse(&it);
3344
3345 it.dumpSpv(spirv);
3346
3347 glslang::GetThreadPoolAllocator().pop();
3348}
3349
3350}; // end namespace glslang