blob: e5e2169bdd06343fecde58e5eb4efe7f951797f1 [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
John Kessenich140f3df2015-06-26 16:58:36 -0600145};
146
147//
148// Helper functions for translating glslang representations to SPIR-V enumerants.
149//
150
151// Translate glslang profile to SPIR-V source language.
152spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
153{
154 switch (profile) {
155 case ENoProfile:
156 case ECoreProfile:
157 case ECompatibilityProfile:
158 return spv::SourceLanguageGLSL;
159 case EEsProfile:
160 return spv::SourceLanguageESSL;
161 default:
162 return spv::SourceLanguageUnknown;
163 }
164}
165
166// Translate glslang language (stage) to SPIR-V execution model.
167spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
168{
169 switch (stage) {
170 case EShLangVertex: return spv::ExecutionModelVertex;
171 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
172 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
173 case EShLangGeometry: return spv::ExecutionModelGeometry;
174 case EShLangFragment: return spv::ExecutionModelFragment;
175 case EShLangCompute: return spv::ExecutionModelGLCompute;
176 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700177 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600178 return spv::ExecutionModelFragment;
179 }
180}
181
182// Translate glslang type to SPIR-V storage class.
183spv::StorageClass TranslateStorageClass(const glslang::TType& type)
184{
185 if (type.getQualifier().isPipeInput())
186 return spv::StorageClassInput;
187 else if (type.getQualifier().isPipeOutput())
188 return spv::StorageClassOutput;
189 else if (type.getQualifier().isUniformOrBuffer()) {
190 if (type.getBasicType() == glslang::EbtBlock)
191 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800192 else if (type.getBasicType() == glslang::EbtAtomicUint)
193 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600194 else
195 return spv::StorageClassUniformConstant;
196 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
197 } else {
198 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700199 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
200 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600201 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
202 case glslang::EvqTemporary: return spv::StorageClassFunction;
203 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700204 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600205 return spv::StorageClassFunction;
206 }
207 }
208}
209
210// Translate glslang sampler type to SPIR-V dimensionality.
211spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
212{
213 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700214 case glslang::Esd1D: return spv::Dim1D;
215 case glslang::Esd2D: return spv::Dim2D;
216 case glslang::Esd3D: return spv::Dim3D;
217 case glslang::EsdCube: return spv::DimCube;
218 case glslang::EsdRect: return spv::DimRect;
219 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600220 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700221 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600222 return spv::Dim2D;
223 }
224}
225
226// Translate glslang type to SPIR-V precision decorations.
227spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
228{
229 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600230 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
231 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
232 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 default:
234 return spv::NoPrecision;
235 }
236}
237
238// Translate glslang type to SPIR-V block decorations.
239spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
240{
241 if (type.getBasicType() == glslang::EbtBlock) {
242 switch (type.getQualifier().storage) {
243 case glslang::EvqUniform: return spv::DecorationBlock;
244 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
245 case glslang::EvqVaryingIn: return spv::DecorationBlock;
246 case glslang::EvqVaryingOut: return spv::DecorationBlock;
247 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700248 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600249 break;
250 }
251 }
252
253 return (spv::Decoration)spv::BadValue;
254}
255
256// Translate glslang type to SPIR-V layout decorations.
257spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
258{
259 if (type.isMatrix()) {
260 switch (type.getQualifier().layoutMatrix) {
261 case glslang::ElmRowMajor:
262 return spv::DecorationRowMajor;
263 default:
264 return spv::DecorationColMajor;
265 }
266 } else {
267 switch (type.getBasicType()) {
268 default:
269 return (spv::Decoration)spv::BadValue;
270 break;
271 case glslang::EbtBlock:
272 switch (type.getQualifier().storage) {
273 case glslang::EvqUniform:
274 case glslang::EvqBuffer:
275 switch (type.getQualifier().layoutPacking) {
276 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600277 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
278 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600279 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600280 }
281 case glslang::EvqVaryingIn:
282 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700283 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600284 return (spv::Decoration)spv::BadValue;
285 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700286 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600287 return (spv::Decoration)spv::BadValue;
288 }
289 }
290 }
291}
292
293// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700294// Returns spv::Decoration(spv::BadValue) when no decoration
295// should be applied.
John Kessenich140f3df2015-06-26 16:58:36 -0600296spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
297{
John Kessenich55e7d112015-11-15 21:33:39 -0700298 if (type.getQualifier().smooth) {
299 // Smooth decoration doesn't exist in SPIR-V 1.0
300 return (spv::Decoration)spv::BadValue;
301 }
John Kessenich140f3df2015-06-26 16:58:36 -0600302 if (type.getQualifier().nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700303 return spv::DecorationNoPerspective;
John Kessenich140f3df2015-06-26 16:58:36 -0600304 else if (type.getQualifier().patch)
305 return spv::DecorationPatch;
306 else if (type.getQualifier().flat)
307 return spv::DecorationFlat;
308 else if (type.getQualifier().centroid)
309 return spv::DecorationCentroid;
310 else if (type.getQualifier().sample)
311 return spv::DecorationSample;
312 else
313 return (spv::Decoration)spv::BadValue;
314}
315
316// If glslang type is invaraiant, return SPIR-V invariant decoration.
317spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
318{
319 if (type.getQualifier().invariant)
320 return spv::DecorationInvariant;
321 else
322 return (spv::Decoration)spv::BadValue;
323}
324
325// Translate glslang built-in variable to SPIR-V built in decoration.
326spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
327{
328 switch (builtIn) {
329 case glslang::EbvPosition: return spv::BuiltInPosition;
330 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600331 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
332 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
333 case glslang::EbvVertexId: return spv::BuiltInVertexId;
334 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600335 case glslang::EbvBaseVertex:
336 case glslang::EbvBaseInstance:
337 case glslang::EbvDrawId:
338 // TODO: Add SPIR-V builtin ID.
339 spv::MissingFunctionality("Draw parameters");
340 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
342 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
343 case glslang::EbvLayer: return spv::BuiltInLayer;
344 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
345 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
346 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
347 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
348 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
349 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
350 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
351 case glslang::EbvFace: return spv::BuiltInFrontFacing;
352 case glslang::EbvSampleId: return spv::BuiltInSampleId;
353 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
354 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600355 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
356 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
357 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
358 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
359 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
360 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
361 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
362 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
363 default: return (spv::BuiltIn)spv::BadValue;
364 }
365}
366
Rex Xufc618912015-09-09 16:42:49 +0800367// Translate glslang image layout format to SPIR-V image format.
368spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
369{
370 assert(type.getBasicType() == glslang::EbtSampler);
371
372 switch (type.getQualifier().layoutFormat) {
373 case glslang::ElfNone: return spv::ImageFormatUnknown;
374 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
375 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
376 case glslang::ElfR32f: return spv::ImageFormatR32f;
377 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
378 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
379 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
380 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
381 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
382 case glslang::ElfR16f: return spv::ImageFormatR16f;
383 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
384 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
385 case glslang::ElfRg16: return spv::ImageFormatRg16;
386 case glslang::ElfRg8: return spv::ImageFormatRg8;
387 case glslang::ElfR16: return spv::ImageFormatR16;
388 case glslang::ElfR8: return spv::ImageFormatR8;
389 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
390 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
391 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
392 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
393 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
394 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
395 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
396 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
397 case glslang::ElfR32i: return spv::ImageFormatR32i;
398 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
399 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
400 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
401 case glslang::ElfR16i: return spv::ImageFormatR16i;
402 case glslang::ElfR8i: return spv::ImageFormatR8i;
403 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
404 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
405 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
406 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
407 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
408 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
409 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
410 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
411 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
412 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
413 default: return (spv::ImageFormat)spv::BadValue;
414 }
415}
416
John Kessenich140f3df2015-06-26 16:58:36 -0600417//
418// Implement the TGlslangToSpvTraverser class.
419//
420
421TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
422 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700423 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600424 inMain(false), mainTerminated(false), linkageOnly(false),
425 glslangIntermediate(glslangIntermediate)
426{
427 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
428
429 builder.clearAccessChain();
430 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
431 stdBuiltins = builder.import("GLSL.std.450");
432 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
433 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700434 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600435
436 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600437 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
438 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600439 builder.addSourceExtension(it->c_str());
440
441 // Add the top-level modes for this shader.
442
443 if (glslangIntermediate->getXfbMode())
444 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
445
446 unsigned int mode;
447 switch (glslangIntermediate->getStage()) {
448 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600449 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600450 break;
451
452 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600453 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600454 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
455 break;
456
457 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600458 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600459 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700460 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
461 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
462 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600463 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600464 }
465 if (mode != spv::BadValue)
466 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
467
John Kesseniche6903322015-10-13 16:29:02 -0600468 switch (glslangIntermediate->getVertexSpacing()) {
469 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
470 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
471 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
472 default: mode = spv::BadValue; break;
473 }
474 if (mode != spv::BadValue)
475 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
476
477 switch (glslangIntermediate->getVertexOrder()) {
478 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
479 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
480 default: mode = spv::BadValue; break;
481 }
482 if (mode != spv::BadValue)
483 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
484
485 if (glslangIntermediate->getPointMode())
486 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600487 break;
488
489 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600490 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600491 switch (glslangIntermediate->getInputPrimitive()) {
492 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
493 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
494 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700495 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
497 default: mode = spv::BadValue; break;
498 }
499 if (mode != spv::BadValue)
500 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600501
John Kessenich140f3df2015-06-26 16:58:36 -0600502 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
503
504 switch (glslangIntermediate->getOutputPrimitive()) {
505 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
506 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
507 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
508 default: mode = spv::BadValue; break;
509 }
510 if (mode != spv::BadValue)
511 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
512 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
513 break;
514
515 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600516 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600517 if (glslangIntermediate->getPixelCenterInteger())
518 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600519
John Kessenich140f3df2015-06-26 16:58:36 -0600520 if (glslangIntermediate->getOriginUpperLeft())
521 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600522 else
523 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600524
525 if (glslangIntermediate->getEarlyFragmentTests())
526 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
527
528 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600529 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
530 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
531 default: mode = spv::BadValue; break;
532 }
533 if (mode != spv::BadValue)
534 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
535
536 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
537 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600538 break;
539
540 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600541 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600542 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
543 glslangIntermediate->getLocalSize(1),
544 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600545 break;
546
547 default:
548 break;
549 }
550
551}
552
553TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
554{
555 if (! mainTerminated) {
556 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
557 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600558 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600559 }
560}
561
562//
563// Implement the traversal functions.
564//
565// Return true from interior nodes to have the external traversal
566// continue on to children. Return false if children were
567// already processed.
568//
569
570//
571// Symbols can turn into
572// - uniform/input reads
573// - output writes
574// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
575// - something simple that degenerates into the last bullet
576//
577void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
578{
579 // getSymbolId() will set up all the IO decorations on the first call.
580 // Formal function parameters were mapped during makeFunctions().
581 spv::Id id = getSymbolId(symbol);
582
583 if (! linkageOnly) {
584 // Prepare to generate code for the access
585
586 // L-value chains will be computed left to right. We're on the symbol now,
587 // which is the left-most part of the access chain, so now is "clear" time,
588 // followed by setting the base.
589 builder.clearAccessChain();
590
591 // For now, we consider all user variables as being in memory, so they are pointers,
592 // except for "const in" arguments to a function, which are an intermediate object.
593 // See comments in handleUserFunctionCall().
594 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
595 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
596 builder.setAccessChainRValue(id);
597 else
598 builder.setAccessChainLValue(id);
John Kessenich55e7d112015-11-15 21:33:39 -0700599 } else {
600 // finish off the entry-point SPV instruction by adding the Input/Output <id>
601 spv::StorageClass sc = builder.getStorageClass(id);
602 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
603 entryPoint->addIdOperand(id);
John Kessenich140f3df2015-06-26 16:58:36 -0600604 }
605}
606
607bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
608{
609 // First, handle special cases
610 switch (node->getOp()) {
611 case glslang::EOpAssign:
612 case glslang::EOpAddAssign:
613 case glslang::EOpSubAssign:
614 case glslang::EOpMulAssign:
615 case glslang::EOpVectorTimesMatrixAssign:
616 case glslang::EOpVectorTimesScalarAssign:
617 case glslang::EOpMatrixTimesScalarAssign:
618 case glslang::EOpMatrixTimesMatrixAssign:
619 case glslang::EOpDivAssign:
620 case glslang::EOpModAssign:
621 case glslang::EOpAndAssign:
622 case glslang::EOpInclusiveOrAssign:
623 case glslang::EOpExclusiveOrAssign:
624 case glslang::EOpLeftShiftAssign:
625 case glslang::EOpRightShiftAssign:
626 // A bin-op assign "a += b" means the same thing as "a = a + b"
627 // where a is evaluated before b. For a simple assignment, GLSL
628 // says to evaluate the left before the right. So, always, left
629 // node then right node.
630 {
631 // get the left l-value, save it away
632 builder.clearAccessChain();
633 node->getLeft()->traverse(this);
634 spv::Builder::AccessChain lValue = builder.getAccessChain();
635
636 // evaluate the right
637 builder.clearAccessChain();
638 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600639 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600640
641 if (node->getOp() != glslang::EOpAssign) {
642 // the left is also an r-value
643 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600644 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600645
646 // do the operation
647 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
648 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
649 node->getType().getBasicType());
650
651 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700652 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600653 }
654
655 // store the result
656 builder.setAccessChain(lValue);
657 builder.accessChainStore(rValue);
658
659 // assignments are expressions having an rValue after they are evaluated...
660 builder.clearAccessChain();
661 builder.setAccessChainRValue(rValue);
662 }
663 return false;
664 case glslang::EOpIndexDirect:
665 case glslang::EOpIndexDirectStruct:
666 {
667 // Get the left part of the access chain.
668 node->getLeft()->traverse(this);
669
670 // Add the next element in the chain
671
John Kessenich55e7d112015-11-15 21:33:39 -0700672 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600673 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
674 // This may be, e.g., an anonymous block-member selection, which generally need
675 // index remapping due to hidden members in anonymous blocks.
676 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700677 assert(remapper.size() > 0);
678 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600679 }
680
681 if (! node->getLeft()->getType().isArray() &&
682 node->getLeft()->getType().isVector() &&
683 node->getOp() == glslang::EOpIndexDirect) {
684 // This is essentially a hard-coded vector swizzle of size 1,
685 // so short circuit the access-chain stuff with a swizzle.
686 std::vector<unsigned> swizzle;
687 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600688 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600689 } else {
690 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600691 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600692 }
693 }
694 return false;
695 case glslang::EOpIndexIndirect:
696 {
697 // Structure or array or vector indirection.
698 // Will use native SPIR-V access-chain for struct and array indirection;
699 // matrices are arrays of vectors, so will also work for a matrix.
700 // Will use the access chain's 'component' for variable index into a vector.
701
702 // This adapter is building access chains left to right.
703 // Set up the access chain to the left.
704 node->getLeft()->traverse(this);
705
706 // save it so that computing the right side doesn't trash it
707 spv::Builder::AccessChain partial = builder.getAccessChain();
708
709 // compute the next index in the chain
710 builder.clearAccessChain();
711 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600712 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600713
714 // restore the saved access chain
715 builder.setAccessChain(partial);
716
717 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600718 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600719 else
John Kessenichfa668da2015-09-13 14:46:30 -0600720 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600721 }
722 return false;
723 case glslang::EOpVectorSwizzle:
724 {
725 node->getLeft()->traverse(this);
726 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
727 std::vector<unsigned> swizzle;
728 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
729 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600730 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600731 }
732 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600733 case glslang::EOpLogicalOr:
734 case glslang::EOpLogicalAnd:
735 {
736
737 // These may require short circuiting, but can sometimes be done as straight
738 // binary operations. The right operand must be short circuited if it has
739 // side effects, and should probably be if it is complex.
740 if (isTrivial(node->getRight()->getAsTyped()))
741 break; // handle below as a normal binary operation
742 // otherwise, we need to do dynamic short circuiting on the right operand
743 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
744 builder.clearAccessChain();
745 builder.setAccessChainRValue(result);
746 }
747 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600748 default:
749 break;
750 }
751
752 // Assume generic binary op...
753
754 // Get the operands
755 builder.clearAccessChain();
756 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600757 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600758
759 builder.clearAccessChain();
760 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600761 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600762
763 spv::Id result;
764 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
765
766 result = createBinaryOperation(node->getOp(), precision,
767 convertGlslangToSpvType(node->getType()), left, right,
768 node->getLeft()->getType().getBasicType());
769
770 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700771 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich140f3df2015-06-26 16:58:36 -0600772 } else {
773 builder.clearAccessChain();
774 builder.setAccessChainRValue(result);
775
776 return false;
777 }
778
779 return true;
780}
781
782bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
783{
John Kessenichfc51d282015-08-19 13:34:18 -0600784 spv::Id result = spv::NoResult;
785
786 // try texturing first
787 result = createImageTextureFunctionCall(node);
788 if (result != spv::NoResult) {
789 builder.clearAccessChain();
790 builder.setAccessChainRValue(result);
791
792 return false; // done with this node
793 }
794
795 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600796
797 if (node->getOp() == glslang::EOpArrayLength) {
798 // Quite special; won't want to evaluate the operand.
799
800 // Normal .length() would have been constant folded by the front-end.
801 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600802 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600803 assert(node->getOperand()->getType().isRuntimeSizedArray());
804 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
805 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600806 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
807 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600808
809 builder.clearAccessChain();
810 builder.setAccessChainRValue(length);
811
812 return false;
813 }
814
John Kessenichfc51d282015-08-19 13:34:18 -0600815 // Start by evaluating the operand
816
John Kessenich140f3df2015-06-26 16:58:36 -0600817 builder.clearAccessChain();
818 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800819
Rex Xufc618912015-09-09 16:42:49 +0800820 spv::Id operand = spv::NoResult;
821
822 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
823 node->getOp() == glslang::EOpAtomicCounterDecrement ||
824 node->getOp() == glslang::EOpAtomicCounter)
825 operand = builder.accessChainGetLValue(); // Special case l-value operands
826 else
Rex Xu30f92582015-09-14 10:38:56 +0800827 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600828
829 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
830
831 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600832 if (! result)
833 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600834
835 // if not, then possibly an operation
836 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700837 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600838
839 if (result) {
840 builder.clearAccessChain();
841 builder.setAccessChainRValue(result);
842
843 return false; // done with this node
844 }
845
846 // it must be a special case, check...
847 switch (node->getOp()) {
848 case glslang::EOpPostIncrement:
849 case glslang::EOpPostDecrement:
850 case glslang::EOpPreIncrement:
851 case glslang::EOpPreDecrement:
852 {
853 // we need the integer value "1" or the floating point "1.0" to add/subtract
854 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
855 builder.makeFloatConstant(1.0F) :
856 builder.makeIntConstant(1);
857 glslang::TOperator op;
858 if (node->getOp() == glslang::EOpPreIncrement ||
859 node->getOp() == glslang::EOpPostIncrement)
860 op = glslang::EOpAdd;
861 else
862 op = glslang::EOpSub;
863
864 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
865 convertGlslangToSpvType(node->getType()), operand, one,
866 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700867 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600868
869 // The result of operation is always stored, but conditionally the
870 // consumed result. The consumed result is always an r-value.
871 builder.accessChainStore(result);
872 builder.clearAccessChain();
873 if (node->getOp() == glslang::EOpPreIncrement ||
874 node->getOp() == glslang::EOpPreDecrement)
875 builder.setAccessChainRValue(result);
876 else
877 builder.setAccessChainRValue(operand);
878 }
879
880 return false;
881
882 case glslang::EOpEmitStreamVertex:
883 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
884 return false;
885 case glslang::EOpEndStreamPrimitive:
886 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
887 return false;
888
889 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700890 spv::MissingFunctionality("unknown glslang unary");
John Kessenich140f3df2015-06-26 16:58:36 -0600891 break;
892 }
893
894 return true;
895}
896
897bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
898{
John Kessenichfc51d282015-08-19 13:34:18 -0600899 spv::Id result = spv::NoResult;
900
901 // try texturing
902 result = createImageTextureFunctionCall(node);
903 if (result != spv::NoResult) {
904 builder.clearAccessChain();
905 builder.setAccessChainRValue(result);
906
907 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600908 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800909 // "imageStore" is a special case, which has no result
910 return false;
911 }
John Kessenichfc51d282015-08-19 13:34:18 -0600912
John Kessenich140f3df2015-06-26 16:58:36 -0600913 glslang::TOperator binOp = glslang::EOpNull;
914 bool reduceComparison = true;
915 bool isMatrix = false;
916 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600917 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600918
919 assert(node->getOp());
920
921 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
922
923 switch (node->getOp()) {
924 case glslang::EOpSequence:
925 {
926 if (preVisit)
927 ++sequenceDepth;
928 else
929 --sequenceDepth;
930
931 if (sequenceDepth == 1) {
932 // If this is the parent node of all the functions, we want to see them
933 // early, so all call points have actual SPIR-V functions to reference.
934 // In all cases, still let the traverser visit the children for us.
935 makeFunctions(node->getAsAggregate()->getSequence());
936
937 // Also, we want all globals initializers to go into the entry of main(), before
938 // anything else gets there, so visit out of order, doing them all now.
939 makeGlobalInitializers(node->getAsAggregate()->getSequence());
940
941 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
942 // so do them manually.
943 visitFunctions(node->getAsAggregate()->getSequence());
944
945 return false;
946 }
947
948 return true;
949 }
950 case glslang::EOpLinkerObjects:
951 {
952 if (visit == glslang::EvPreVisit)
953 linkageOnly = true;
954 else
955 linkageOnly = false;
956
957 return true;
958 }
959 case glslang::EOpComma:
960 {
961 // processing from left to right naturally leaves the right-most
962 // lying around in the access chain
963 glslang::TIntermSequence& glslangOperands = node->getSequence();
964 for (int i = 0; i < (int)glslangOperands.size(); ++i)
965 glslangOperands[i]->traverse(this);
966
967 return false;
968 }
969 case glslang::EOpFunction:
970 if (visit == glslang::EvPreVisit) {
971 if (isShaderEntrypoint(node)) {
972 inMain = true;
973 builder.setBuildPoint(shaderEntry->getLastBlock());
974 } else {
975 handleFunctionEntry(node);
976 }
977 } else {
978 if (inMain)
979 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600980 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600981 inMain = false;
982 }
983
984 return true;
985 case glslang::EOpParameters:
986 // Parameters will have been consumed by EOpFunction processing, but not
987 // the body, so we still visited the function node's children, making this
988 // child redundant.
989 return false;
990 case glslang::EOpFunctionCall:
991 {
992 if (node->isUserDefined())
993 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -0700994 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600995 builder.clearAccessChain();
996 builder.setAccessChainRValue(result);
997
998 return false;
999 }
1000 case glslang::EOpConstructMat2x2:
1001 case glslang::EOpConstructMat2x3:
1002 case glslang::EOpConstructMat2x4:
1003 case glslang::EOpConstructMat3x2:
1004 case glslang::EOpConstructMat3x3:
1005 case glslang::EOpConstructMat3x4:
1006 case glslang::EOpConstructMat4x2:
1007 case glslang::EOpConstructMat4x3:
1008 case glslang::EOpConstructMat4x4:
1009 case glslang::EOpConstructDMat2x2:
1010 case glslang::EOpConstructDMat2x3:
1011 case glslang::EOpConstructDMat2x4:
1012 case glslang::EOpConstructDMat3x2:
1013 case glslang::EOpConstructDMat3x3:
1014 case glslang::EOpConstructDMat3x4:
1015 case glslang::EOpConstructDMat4x2:
1016 case glslang::EOpConstructDMat4x3:
1017 case glslang::EOpConstructDMat4x4:
1018 isMatrix = true;
1019 // fall through
1020 case glslang::EOpConstructFloat:
1021 case glslang::EOpConstructVec2:
1022 case glslang::EOpConstructVec3:
1023 case glslang::EOpConstructVec4:
1024 case glslang::EOpConstructDouble:
1025 case glslang::EOpConstructDVec2:
1026 case glslang::EOpConstructDVec3:
1027 case glslang::EOpConstructDVec4:
1028 case glslang::EOpConstructBool:
1029 case glslang::EOpConstructBVec2:
1030 case glslang::EOpConstructBVec3:
1031 case glslang::EOpConstructBVec4:
1032 case glslang::EOpConstructInt:
1033 case glslang::EOpConstructIVec2:
1034 case glslang::EOpConstructIVec3:
1035 case glslang::EOpConstructIVec4:
1036 case glslang::EOpConstructUint:
1037 case glslang::EOpConstructUVec2:
1038 case glslang::EOpConstructUVec3:
1039 case glslang::EOpConstructUVec4:
1040 case glslang::EOpConstructStruct:
1041 {
1042 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001043 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001044 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1045 spv::Id constructed;
1046 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1047 std::vector<spv::Id> constituents;
1048 for (int c = 0; c < (int)arguments.size(); ++c)
1049 constituents.push_back(arguments[c]);
1050 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001051 } else if (isMatrix)
1052 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1053 else
1054 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001055
1056 builder.clearAccessChain();
1057 builder.setAccessChainRValue(constructed);
1058
1059 return false;
1060 }
1061
1062 // These six are component-wise compares with component-wise results.
1063 // Forward on to createBinaryOperation(), requesting a vector result.
1064 case glslang::EOpLessThan:
1065 case glslang::EOpGreaterThan:
1066 case glslang::EOpLessThanEqual:
1067 case glslang::EOpGreaterThanEqual:
1068 case glslang::EOpVectorEqual:
1069 case glslang::EOpVectorNotEqual:
1070 {
1071 // Map the operation to a binary
1072 binOp = node->getOp();
1073 reduceComparison = false;
1074 switch (node->getOp()) {
1075 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1076 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1077 default: binOp = node->getOp(); break;
1078 }
1079
1080 break;
1081 }
1082 case glslang::EOpMul:
1083 // compontent-wise matrix multiply
1084 binOp = glslang::EOpMul;
1085 break;
1086 case glslang::EOpOuterProduct:
1087 // two vectors multiplied to make a matrix
1088 binOp = glslang::EOpOuterProduct;
1089 break;
1090 case glslang::EOpDot:
1091 {
1092 // for scalar dot product, use multiply
1093 glslang::TIntermSequence& glslangOperands = node->getSequence();
1094 if (! glslangOperands[0]->getAsTyped()->isVector())
1095 binOp = glslang::EOpMul;
1096 break;
1097 }
1098 case glslang::EOpMod:
1099 // when an aggregate, this is the floating-point mod built-in function,
1100 // which can be emitted by the one in createBinaryOperation()
1101 binOp = glslang::EOpMod;
1102 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001103 case glslang::EOpEmitVertex:
1104 case glslang::EOpEndPrimitive:
1105 case glslang::EOpBarrier:
1106 case glslang::EOpMemoryBarrier:
1107 case glslang::EOpMemoryBarrierAtomicCounter:
1108 case glslang::EOpMemoryBarrierBuffer:
1109 case glslang::EOpMemoryBarrierImage:
1110 case glslang::EOpMemoryBarrierShared:
1111 case glslang::EOpGroupMemoryBarrier:
1112 noReturnValue = true;
1113 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1114 break;
1115
John Kessenich426394d2015-07-23 10:22:48 -06001116 case glslang::EOpAtomicAdd:
1117 case glslang::EOpAtomicMin:
1118 case glslang::EOpAtomicMax:
1119 case glslang::EOpAtomicAnd:
1120 case glslang::EOpAtomicOr:
1121 case glslang::EOpAtomicXor:
1122 case glslang::EOpAtomicExchange:
1123 case glslang::EOpAtomicCompSwap:
1124 atomic = true;
1125 break;
1126
John Kessenich140f3df2015-06-26 16:58:36 -06001127 default:
1128 break;
1129 }
1130
1131 //
1132 // See if it maps to a regular operation.
1133 //
John Kessenich140f3df2015-06-26 16:58:36 -06001134 if (binOp != glslang::EOpNull) {
1135 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1136 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1137 assert(left && right);
1138
1139 builder.clearAccessChain();
1140 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001141 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001142
1143 builder.clearAccessChain();
1144 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001145 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001146
1147 result = createBinaryOperation(binOp, precision,
1148 convertGlslangToSpvType(node->getType()), leftId, rightId,
1149 left->getType().getBasicType(), reduceComparison);
1150
1151 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001152 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001153 builder.clearAccessChain();
1154 builder.setAccessChainRValue(result);
1155
1156 return false;
1157 }
1158
John Kessenich426394d2015-07-23 10:22:48 -06001159 //
1160 // Create the list of operands.
1161 //
John Kessenich140f3df2015-06-26 16:58:36 -06001162 glslang::TIntermSequence& glslangOperands = node->getSequence();
1163 std::vector<spv::Id> operands;
1164 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1165 builder.clearAccessChain();
1166 glslangOperands[arg]->traverse(this);
1167
1168 // special case l-value operands; there are just a few
1169 bool lvalue = false;
1170 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001171 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001172 case glslang::EOpModf:
1173 if (arg == 1)
1174 lvalue = true;
1175 break;
Rex Xud4782c12015-09-06 16:30:11 +08001176 case glslang::EOpAtomicAdd:
1177 case glslang::EOpAtomicMin:
1178 case glslang::EOpAtomicMax:
1179 case glslang::EOpAtomicAnd:
1180 case glslang::EOpAtomicOr:
1181 case glslang::EOpAtomicXor:
1182 case glslang::EOpAtomicExchange:
1183 case glslang::EOpAtomicCompSwap:
1184 if (arg == 0)
1185 lvalue = true;
1186 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001187 case glslang::EOpAddCarry:
1188 case glslang::EOpSubBorrow:
1189 if (arg == 2)
1190 lvalue = true;
1191 break;
1192 case glslang::EOpUMulExtended:
1193 case glslang::EOpIMulExtended:
1194 if (arg >= 2)
1195 lvalue = true;
1196 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001197 default:
1198 break;
1199 }
1200 if (lvalue)
1201 operands.push_back(builder.accessChainGetLValue());
1202 else
John Kessenichfa668da2015-09-13 14:46:30 -06001203 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001204 }
John Kessenich426394d2015-07-23 10:22:48 -06001205
1206 if (atomic) {
1207 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001208 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001209 } else {
1210 // Pass through to generic operations.
1211 switch (glslangOperands.size()) {
1212 case 0:
1213 result = createNoArgOperation(node->getOp());
1214 break;
1215 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001216 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001217 break;
1218 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001219 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001220 break;
1221 }
John Kessenich140f3df2015-06-26 16:58:36 -06001222 }
1223
1224 if (noReturnValue)
1225 return false;
1226
1227 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001228 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich140f3df2015-06-26 16:58:36 -06001229 return true;
1230 } else {
1231 builder.clearAccessChain();
1232 builder.setAccessChainRValue(result);
1233 return false;
1234 }
1235}
1236
1237bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1238{
1239 // This path handles both if-then-else and ?:
1240 // The if-then-else has a node type of void, while
1241 // ?: has a non-void node type
1242 spv::Id result = 0;
1243 if (node->getBasicType() != glslang::EbtVoid) {
1244 // don't handle this as just on-the-fly temporaries, because there will be two names
1245 // and better to leave SSA to later passes
1246 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1247 }
1248
1249 // emit the condition before doing anything with selection
1250 node->getCondition()->traverse(this);
1251
1252 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001253 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001254
1255 if (node->getTrueBlock()) {
1256 // emit the "then" statement
1257 node->getTrueBlock()->traverse(this);
1258 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001259 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001260 }
1261
1262 if (node->getFalseBlock()) {
1263 ifBuilder.makeBeginElse();
1264 // emit the "else" statement
1265 node->getFalseBlock()->traverse(this);
1266 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001267 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001268 }
1269
1270 ifBuilder.makeEndIf();
1271
1272 if (result) {
1273 // GLSL only has r-values as the result of a :?, but
1274 // if we have an l-value, that can be more efficient if it will
1275 // become the base of a complex r-value expression, because the
1276 // next layer copies r-values into memory to use the access-chain mechanism
1277 builder.clearAccessChain();
1278 builder.setAccessChainLValue(result);
1279 }
1280
1281 return false;
1282}
1283
1284bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1285{
1286 // emit and get the condition before doing anything with switch
1287 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001288 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001289
1290 // browse the children to sort out code segments
1291 int defaultSegment = -1;
1292 std::vector<TIntermNode*> codeSegments;
1293 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1294 std::vector<int> caseValues;
1295 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1296 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1297 TIntermNode* child = *c;
1298 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001299 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001300 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001301 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001302 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1303 } else
1304 codeSegments.push_back(child);
1305 }
1306
1307 // handle the case where the last code segment is missing, due to no code
1308 // statements between the last case and the end of the switch statement
1309 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1310 (int)codeSegments.size() == defaultSegment)
1311 codeSegments.push_back(nullptr);
1312
1313 // make the switch statement
1314 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001315 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001316
1317 // emit all the code in the segments
1318 breakForLoop.push(false);
1319 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1320 builder.nextSwitchSegment(segmentBlocks, s);
1321 if (codeSegments[s])
1322 codeSegments[s]->traverse(this);
1323 else
1324 builder.addSwitchBreak();
1325 }
1326 breakForLoop.pop();
1327
1328 builder.endSwitch(segmentBlocks);
1329
1330 return false;
1331}
1332
1333void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1334{
1335 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001336 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001337
1338 builder.clearAccessChain();
1339 builder.setAccessChainRValue(constant);
1340}
1341
1342bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1343{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001344 auto blocks = builder.makeNewLoop();
1345 if (node->testFirst() && node->getTest()) {
1346 spv::Block& head = builder.makeNewBlock();
1347 builder.createBranch(&head);
John Kessenich140f3df2015-06-26 16:58:36 -06001348
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001349 builder.setBuildPoint(&head);
John Kessenich140f3df2015-06-26 16:58:36 -06001350 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001351 spv::Id condition =
1352 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
1353 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
1354 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1355
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001356 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001357 builder.setBuildPoint(&blocks.body);
1358 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001359 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001360 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001361 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001362
1363 builder.setBuildPoint(&blocks.continue_target);
1364 if (node->getTerminal())
1365 node->getTerminal()->traverse(this);
1366 builder.createBranch(&head);
David Netoc22f37c2015-07-15 16:21:26 -04001367 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001368 builder.createBranch(&blocks.body);
1369
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001370 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001371 builder.setBuildPoint(&blocks.body);
1372 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001373 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001374 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001375 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001376
1377 builder.setBuildPoint(&blocks.continue_target);
1378 if (node->getTerminal())
1379 node->getTerminal()->traverse(this);
1380 if (node->getTest()) {
1381 node->getTest()->traverse(this);
1382 spv::Id condition =
1383 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
1384 builder.createLoopMerge(&blocks.merge, &blocks.continue_target,
1385 spv::LoopControlMaskNone);
1386 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1387 } else {
1388 builder.createBranch(&blocks.body);
1389 }
John Kessenich140f3df2015-06-26 16:58:36 -06001390 }
1391
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001392 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001393 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001394 return false;
1395}
1396
1397bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1398{
1399 if (node->getExpression())
1400 node->getExpression()->traverse(this);
1401
1402 switch (node->getFlowOp()) {
1403 case glslang::EOpKill:
1404 builder.makeDiscard();
1405 break;
1406 case glslang::EOpBreak:
1407 if (breakForLoop.top())
1408 builder.createLoopExit();
1409 else
1410 builder.addSwitchBreak();
1411 break;
1412 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001413 builder.createLoopContinue();
1414 break;
1415 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001416 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001417 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001418 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001419 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001420
1421 builder.clearAccessChain();
1422 break;
1423
1424 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001425 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001426 break;
1427 }
1428
1429 return false;
1430}
1431
1432spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1433{
1434 // First, steer off constants, which are not SPIR-V variables, but
1435 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001436 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001437 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001438 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001439 }
1440
1441 // Now, handle actual variables
1442 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1443 spv::Id spvType = convertGlslangToSpvType(node->getType());
1444
1445 const char* name = node->getName().c_str();
1446 if (glslang::IsAnonymous(name))
1447 name = "";
1448
1449 return builder.createVariable(storageClass, spvType, name);
1450}
1451
1452// Return type Id of the sampled type.
1453spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1454{
1455 switch (sampler.type) {
1456 case glslang::EbtFloat: return builder.makeFloatType(32);
1457 case glslang::EbtInt: return builder.makeIntType(32);
1458 case glslang::EbtUint: return builder.makeUintType(32);
1459 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001460 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001461 return builder.makeFloatType(32);
1462 }
1463}
1464
John Kessenich31ed4832015-09-09 17:51:38 -06001465// Convert from a glslang type to an SPV type, by calling into
1466// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001467spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1468{
John Kessenich31ed4832015-09-09 17:51:38 -06001469 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1470}
1471
1472// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1473// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1474spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1475{
John Kessenich140f3df2015-06-26 16:58:36 -06001476 spv::Id spvType = 0;
1477
1478 switch (type.getBasicType()) {
1479 case glslang::EbtVoid:
1480 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001481 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001482 break;
1483 case glslang::EbtFloat:
1484 spvType = builder.makeFloatType(32);
1485 break;
1486 case glslang::EbtDouble:
1487 spvType = builder.makeFloatType(64);
1488 break;
1489 case glslang::EbtBool:
1490 spvType = builder.makeBoolType();
1491 break;
1492 case glslang::EbtInt:
1493 spvType = builder.makeIntType(32);
1494 break;
1495 case glslang::EbtUint:
1496 spvType = builder.makeUintType(32);
1497 break;
John Kessenich426394d2015-07-23 10:22:48 -06001498 case glslang::EbtAtomicUint:
1499 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1500 spvType = builder.makeUintType(32);
1501 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001502 case glslang::EbtSampler:
1503 {
1504 const glslang::TSampler& sampler = type.getSampler();
John Kessenich55e7d112015-11-15 21:33:39 -07001505 // an image is present, make its type
1506 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1507 sampler.image ? 2 : 1, TranslateImageFormat(type));
1508 if (! sampler.image) {
1509 spvType = builder.makeSampledImageType(spvType);
1510 }
1511 }
John Kessenich140f3df2015-06-26 16:58:36 -06001512 break;
1513 case glslang::EbtStruct:
1514 case glslang::EbtBlock:
1515 {
1516 // If we've seen this struct type, return it
1517 const glslang::TTypeList* glslangStruct = type.getStruct();
1518 std::vector<spv::Id> structFields;
1519 spvType = structMap[glslangStruct];
1520 if (spvType)
1521 break;
1522
1523 // else, we haven't seen it...
1524
1525 // Create a vector of struct types for SPIR-V to consume
1526 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1527 if (type.getBasicType() == glslang::EbtBlock)
1528 memberRemapper[glslangStruct].resize(glslangStruct->size());
1529 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1530 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1531 if (glslangType.hiddenMember()) {
1532 ++memberDelta;
1533 if (type.getBasicType() == glslang::EbtBlock)
1534 memberRemapper[glslangStruct][i] = -1;
1535 } else {
1536 if (type.getBasicType() == glslang::EbtBlock)
1537 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001538 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001539 }
1540 }
1541
1542 // Make the SPIR-V type
1543 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1544 structMap[glslangStruct] = spvType;
1545
1546 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001547 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001548 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1549 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1550 int member = i;
1551 if (type.getBasicType() == glslang::EbtBlock)
1552 member = memberRemapper[glslangStruct][i];
1553 // using -1 above to indicate a hidden member
1554 if (member >= 0) {
1555 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1556 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1557 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1558 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1559 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1560 if (glslangType.getQualifier().hasLocation())
1561 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1562 if (glslangType.getQualifier().hasComponent())
1563 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1564 if (glslangType.getQualifier().hasXfbOffset())
1565 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001566 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001567 // figure out what to do with offset, which is accumulating
1568 int nextOffset;
1569 updateMemberOffset(type, glslangType, offset, nextOffset);
1570 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001571 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001572 offset = nextOffset;
1573 }
John Kessenich140f3df2015-06-26 16:58:36 -06001574
John Kessenich31ed4832015-09-09 17:51:38 -06001575 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001576 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1577 }
1578
John Kessenich140f3df2015-06-26 16:58:36 -06001579 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001580 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1581 if (builtIn != spv::BadValue)
1582 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001583 }
1584 }
1585
1586 // Decorate the structure
1587 addDecoration(spvType, TranslateLayoutDecoration(type));
1588 addDecoration(spvType, TranslateBlockDecoration(type));
1589 if (type.getQualifier().hasStream())
1590 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1591 if (glslangIntermediate->getXfbMode()) {
1592 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001593 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001594 if (type.getQualifier().hasXfbBuffer())
1595 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1596 }
1597 }
1598 break;
1599 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001600 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001601 break;
1602 }
1603
1604 if (type.isMatrix())
1605 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1606 else {
1607 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1608 if (type.getVectorSize() > 1)
1609 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1610 }
1611
1612 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001613 // Do all but the outer dimension
1614 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1615 assert(type.getArraySizes()->getDimSize(dim) > 0);
1616 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1617 }
John Kessenich31ed4832015-09-09 17:51:38 -06001618
John Kessenichc9a80832015-09-12 12:17:44 -06001619 // Do the outer dimension, which might not be known for a runtime-sized array
1620 if (type.isRuntimeSizedArray()) {
1621 spvType = builder.makeRuntimeArray(spvType);
1622 } else {
1623 assert(type.getOuterArraySize() > 0);
1624 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1625 }
1626
John Kessenich55e7d112015-11-15 21:33:39 -07001627 // TODO: explicit layout still needs to be done hierarchically for arrays of arrays, which
John Kessenichc9a80832015-09-12 12:17:44 -06001628 // may still require additional "link time" support from the front-end
1629 // for arrays of arrays
John Kessenich55e7d112015-11-15 21:33:39 -07001630
1631 // We need to decorate array strides for types needing explicit layout,
1632 // except for the very top if it is an array of blocks; that array is
1633 // not laid out in memory in a way needing a stride.
1634 if (explicitLayout && type.getBasicType() != glslang::EbtBlock)
John Kessenich31ed4832015-09-09 17:51:38 -06001635 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001636 }
1637
1638 return spvType;
1639}
1640
John Kessenich31ed4832015-09-09 17:51:38 -06001641bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1642{
1643 return type.getBasicType() == glslang::EbtBlock &&
1644 type.getQualifier().layoutPacking != glslang::ElpShared &&
1645 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1646 (type.getQualifier().storage == glslang::EvqUniform ||
1647 type.getQualifier().storage == glslang::EvqBuffer);
1648}
1649
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001650// Given an array type, returns the integer stride required for that array
1651int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1652{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001653 int size;
John Kesseniche721f492015-12-06 19:17:49 -07001654 int stride = glslangIntermediate->getBaseAlignment(arrayType, size, arrayType.getQualifier().layoutPacking == glslang::ElpStd140);
1655 if (arrayType.isMatrix()) {
1656 // GLSL strides are set to alignments of the matrix flattened to individual rows/cols,
1657 // but SPV needs an array stride for the whole matrix, not the rows/cols
1658 if (arrayType.getQualifier().layoutMatrix == glslang::ElmRowMajor)
1659 stride *= arrayType.getMatrixRows();
1660 else
1661 stride *= arrayType.getMatrixCols();
1662 }
1663
1664 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001665}
1666
1667// Given a matrix type, returns the integer stride required for that matrix
1668// when used as a member of an interface block
1669int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1670{
1671 int size;
John Kesseniche721f492015-12-06 19:17:49 -07001672 return glslangIntermediate->getBaseAlignment(matrixType, size, matrixType.getQualifier().layoutPacking == glslang::ElpStd140);
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001673}
1674
John Kessenich5e4b1242015-08-06 22:53:06 -06001675// Given a member type of a struct, realign the current offset for it, and compute
1676// the next (not yet aligned) offset for the next member, which will get aligned
1677// on the next call.
1678// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1679// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1680// -1 means a non-forced member offset (no decoration needed).
1681void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1682{
1683 // this will get a positive value when deemed necessary
1684 nextOffset = -1;
1685
1686 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1687 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1688
1689 // override anything in currentOffset with user-set offset
1690 if (memberType.getQualifier().hasOffset())
1691 currentOffset = memberType.getQualifier().layoutOffset;
1692
1693 // It could be that current linker usage in glslang updated all the layoutOffset,
1694 // in which case the following code does not matter. But, that's not quite right
1695 // once cross-compilation unit GLSL validation is done, as the original user
1696 // settings are needed in layoutOffset, and then the following will come into play.
1697
1698 if (! forceOffset) {
1699 if (! memberType.getQualifier().hasOffset())
1700 currentOffset = -1;
1701
1702 return;
1703 }
1704
1705 // Getting this far means we are forcing offsets
1706 if (currentOffset < 0)
1707 currentOffset = 0;
1708
1709 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1710 // but possibly not yet correctly aligned.
1711
1712 int memberSize;
1713 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1714 glslang::RoundToPow2(currentOffset, memberAlignment);
1715 nextOffset = currentOffset + memberSize;
1716}
1717
John Kessenich140f3df2015-06-26 16:58:36 -06001718bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1719{
1720 return node->getName() == "main(";
1721}
1722
1723// Make all the functions, skeletally, without actually visiting their bodies.
1724void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1725{
1726 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1727 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1728 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1729 continue;
1730
1731 // We're on a user function. Set up the basic interface for the function now,
1732 // so that it's available to call.
1733 // Translating the body will happen later.
1734 //
1735 // Typically (except for a "const in" parameter), an address will be passed to the
1736 // function. What it is an address of varies:
1737 //
1738 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1739 // so that write needs to be to a copy, hence the address of a copy works.
1740 //
1741 // - "const in" parameters can just be the r-value, as no writes need occur.
1742 //
1743 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1744 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1745
1746 std::vector<spv::Id> paramTypes;
1747 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1748
1749 for (int p = 0; p < (int)parameters.size(); ++p) {
1750 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1751 spv::Id typeId = convertGlslangToSpvType(paramType);
1752 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1753 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1754 else
1755 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1756 paramTypes.push_back(typeId);
1757 }
1758
1759 spv::Block* functionBlock;
1760 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1761 paramTypes, &functionBlock);
1762
1763 // Track function to emit/call later
1764 functionMap[glslFunction->getName().c_str()] = function;
1765
1766 // Set the parameter id's
1767 for (int p = 0; p < (int)parameters.size(); ++p) {
1768 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1769 // give a name too
1770 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1771 }
1772 }
1773}
1774
1775// Process all the initializers, while skipping the functions and link objects
1776void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1777{
1778 builder.setBuildPoint(shaderEntry->getLastBlock());
1779 for (int i = 0; i < (int)initializers.size(); ++i) {
1780 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1781 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1782
1783 // We're on a top-level node that's not a function. Treat as an initializer, whose
1784 // code goes into the beginning of main.
1785 initializer->traverse(this);
1786 }
1787 }
1788}
1789
1790// Process all the functions, while skipping initializers.
1791void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1792{
1793 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1794 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1795 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1796 node->traverse(this);
1797 }
1798}
1799
1800void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1801{
1802 // SPIR-V functions should already be in the functionMap from the prepass
1803 // that called makeFunctions().
1804 spv::Function* function = functionMap[node->getName().c_str()];
1805 spv::Block* functionBlock = function->getEntryBlock();
1806 builder.setBuildPoint(functionBlock);
1807}
1808
Rex Xu04db3f52015-09-16 11:44:02 +08001809void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001810{
Rex Xufc618912015-09-09 16:42:49 +08001811 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001812 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1813 builder.clearAccessChain();
1814 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001815
1816 // Special case l-value operands
1817 bool lvalue = false;
1818 switch (node.getOp()) {
1819 case glslang::EOpImageAtomicAdd:
1820 case glslang::EOpImageAtomicMin:
1821 case glslang::EOpImageAtomicMax:
1822 case glslang::EOpImageAtomicAnd:
1823 case glslang::EOpImageAtomicOr:
1824 case glslang::EOpImageAtomicXor:
1825 case glslang::EOpImageAtomicExchange:
1826 case glslang::EOpImageAtomicCompSwap:
1827 if (i == 0)
1828 lvalue = true;
1829 break;
1830 default:
1831 break;
1832 }
1833
Rex Xu6b86d492015-09-16 17:48:22 +08001834 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001835 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001836 else
Rex Xu30f92582015-09-14 10:38:56 +08001837 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001838 }
1839}
1840
John Kessenichfc51d282015-08-19 13:34:18 -06001841void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001842{
John Kessenichfc51d282015-08-19 13:34:18 -06001843 builder.clearAccessChain();
1844 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001845 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001846}
John Kessenich140f3df2015-06-26 16:58:36 -06001847
John Kessenichfc51d282015-08-19 13:34:18 -06001848spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1849{
Rex Xufc618912015-09-09 16:42:49 +08001850 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001851 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001852 }
1853
John Kessenichfc51d282015-08-19 13:34:18 -06001854 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001855 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1856 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1857 std::vector<spv::Id> arguments;
1858 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001859 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001860 else
1861 translateArguments(*node->getAsUnaryNode(), arguments);
1862 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1863
1864 spv::Builder::TextureParameters params = { };
1865 params.sampler = arguments[0];
1866
Rex Xu04db3f52015-09-16 11:44:02 +08001867 glslang::TCrackedTextureOp cracked;
1868 node->crackTexture(sampler, cracked);
1869
John Kessenichfc51d282015-08-19 13:34:18 -06001870 // Check for queries
1871 if (cracked.query) {
1872 switch (node->getOp()) {
1873 case glslang::EOpImageQuerySize:
1874 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001875 if (arguments.size() > 1) {
1876 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001877 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001878 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001879 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001880 case glslang::EOpImageQuerySamples:
1881 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001882 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001883 case glslang::EOpTextureQueryLod:
1884 params.coords = arguments[1];
1885 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1886 case glslang::EOpTextureQueryLevels:
1887 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1888 default:
1889 assert(0);
1890 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001891 }
John Kessenich140f3df2015-06-26 16:58:36 -06001892 }
1893
Rex Xufc618912015-09-09 16:42:49 +08001894 // Check for image functions other than queries
1895 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001896 std::vector<spv::Id> operands;
1897 auto opIt = arguments.begin();
1898 operands.push_back(*(opIt++));
1899 operands.push_back(*(opIt++));
1900 if (node->getOp() == glslang::EOpImageStore)
Rex Xu6b86d492015-09-16 17:48:22 +08001901 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001902 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07001903 if (sampler.ms) {
1904 operands.push_back(spv::ImageOperandsSampleMask);
1905 operands.push_back(*(opIt++));
1906 }
John Kessenich56bab042015-09-16 10:54:31 -06001907 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1908 } else if (node->getOp() == glslang::EOpImageStore) {
1909 builder.createNoResultOp(spv::OpImageWrite, operands);
1910 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001911 } else {
1912 // Process image atomic operations
1913
1914 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1915 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001916 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001917
Rex Xufc618912015-09-09 16:42:49 +08001918 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001919 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001920
1921 std::vector<spv::Id> operands;
1922 operands.push_back(pointer);
1923 for (; opIt != arguments.end(); ++opIt)
1924 operands.push_back(*opIt);
1925
Rex Xu04db3f52015-09-16 11:44:02 +08001926 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001927 }
1928 }
1929
1930 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001931
Rex Xu71519fe2015-11-11 15:35:47 +08001932 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1933
John Kessenichfc51d282015-08-19 13:34:18 -06001934 // check for bias argument
1935 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08001936 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06001937 int nonBiasArgCount = 2;
1938 if (cracked.offset)
1939 ++nonBiasArgCount;
1940 if (cracked.grad)
1941 nonBiasArgCount += 2;
1942
1943 if ((int)arguments.size() > nonBiasArgCount)
1944 bias = true;
1945 }
1946
John Kessenichfc51d282015-08-19 13:34:18 -06001947 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07001948
John Kessenichfc51d282015-08-19 13:34:18 -06001949 params.coords = arguments[1];
1950 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001951
1952 // sort out where Dref is coming from
1953 if (sampler.shadow && sampler.dim == glslang::EsdCube && sampler.arrayed)
John Kessenichfc51d282015-08-19 13:34:18 -06001954 params.Dref = arguments[2];
John Kessenich55e7d112015-11-15 21:33:39 -07001955 else if (sampler.shadow && cracked.gather) {
1956 params.Dref = arguments[2];
1957 ++extraArgs;
1958 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06001959 std::vector<spv::Id> indexes;
1960 int comp;
1961 if (cracked.proj)
1962 comp = 3;
1963 else
1964 comp = builder.getNumComponents(params.coords) - 1;
1965 indexes.push_back(comp);
1966 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1967 }
1968 if (cracked.lod) {
1969 params.lod = arguments[2];
1970 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08001971 } else if (sampler.ms) {
1972 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08001973 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001974 }
1975 if (cracked.grad) {
1976 params.gradX = arguments[2 + extraArgs];
1977 params.gradY = arguments[3 + extraArgs];
1978 extraArgs += 2;
1979 }
John Kessenich55e7d112015-11-15 21:33:39 -07001980 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06001981 params.offset = arguments[2 + extraArgs];
1982 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07001983 } else if (cracked.offsets) {
1984 params.offsets = arguments[2 + extraArgs];
1985 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001986 }
1987 if (bias) {
1988 params.bias = arguments[2 + extraArgs];
1989 ++extraArgs;
1990 }
John Kessenich55e7d112015-11-15 21:33:39 -07001991 if (cracked.gather && ! sampler.shadow) {
1992 // default component is 0, if missing, otherwise an argument
1993 if (2 + extraArgs < (int)arguments.size()) {
1994 params.comp = arguments[2 + extraArgs];
1995 ++extraArgs;
1996 } else {
1997 params.comp = builder.makeIntConstant(0);
1998 }
1999 }
John Kessenichfc51d282015-08-19 13:34:18 -06002000
John Kessenich55e7d112015-11-15 21:33:39 -07002001 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002002}
2003
2004spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2005{
2006 // Grab the function's pointer from the previously created function
2007 spv::Function* function = functionMap[node->getName().c_str()];
2008 if (! function)
2009 return 0;
2010
2011 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2012 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2013
2014 // See comments in makeFunctions() for details about the semantics for parameter passing.
2015 //
2016 // These imply we need a four step process:
2017 // 1. Evaluate the arguments
2018 // 2. Allocate and make copies of in, out, and inout arguments
2019 // 3. Make the call
2020 // 4. Copy back the results
2021
2022 // 1. Evaluate the arguments
2023 std::vector<spv::Builder::AccessChain> lValues;
2024 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002025 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002026 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2027 // build l-value
2028 builder.clearAccessChain();
2029 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002030 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002031 // keep outputs as l-values, evaluate input-only as r-values
2032 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2033 // save l-value
2034 lValues.push_back(builder.getAccessChain());
2035 } else {
2036 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002037 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002038 }
2039 }
2040
2041 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2042 // copy the original into that space.
2043 //
2044 // Also, build up the list of actual arguments to pass in for the call
2045 int lValueCount = 0;
2046 int rValueCount = 0;
2047 std::vector<spv::Id> spvArgs;
2048 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2049 spv::Id arg;
2050 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2051 // need space to hold the copy
2052 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2053 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2054 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2055 // need to copy the input into output space
2056 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002057 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002058 builder.createStore(copy, arg);
2059 }
2060 ++lValueCount;
2061 } else {
2062 arg = rValues[rValueCount];
2063 ++rValueCount;
2064 }
2065 spvArgs.push_back(arg);
2066 }
2067
2068 // 3. Make the call.
2069 spv::Id result = builder.createFunctionCall(function, spvArgs);
2070
2071 // 4. Copy back out an "out" arguments.
2072 lValueCount = 0;
2073 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2074 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2075 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2076 spv::Id copy = builder.createLoad(spvArgs[a]);
2077 builder.setAccessChain(lValues[lValueCount]);
2078 builder.accessChainStore(copy);
2079 }
2080 ++lValueCount;
2081 }
2082 }
2083
2084 return result;
2085}
2086
2087// Translate AST operation to SPV operation, already having SPV-based operands/types.
2088spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2089 spv::Id typeId, spv::Id left, spv::Id right,
2090 glslang::TBasicType typeProxy, bool reduceComparison)
2091{
2092 bool isUnsigned = typeProxy == glslang::EbtUint;
2093 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2094
2095 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002096 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002097 bool comparison = false;
2098
2099 switch (op) {
2100 case glslang::EOpAdd:
2101 case glslang::EOpAddAssign:
2102 if (isFloat)
2103 binOp = spv::OpFAdd;
2104 else
2105 binOp = spv::OpIAdd;
2106 break;
2107 case glslang::EOpSub:
2108 case glslang::EOpSubAssign:
2109 if (isFloat)
2110 binOp = spv::OpFSub;
2111 else
2112 binOp = spv::OpISub;
2113 break;
2114 case glslang::EOpMul:
2115 case glslang::EOpMulAssign:
2116 if (isFloat)
2117 binOp = spv::OpFMul;
2118 else
2119 binOp = spv::OpIMul;
2120 break;
2121 case glslang::EOpVectorTimesScalar:
2122 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002123 if (isFloat) {
2124 if (builder.isVector(right))
2125 std::swap(left, right);
2126 assert(builder.isScalar(right));
2127 needMatchingVectors = false;
2128 binOp = spv::OpVectorTimesScalar;
2129 } else
2130 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002131 break;
2132 case glslang::EOpVectorTimesMatrix:
2133 case glslang::EOpVectorTimesMatrixAssign:
2134 assert(builder.isVector(left));
2135 assert(builder.isMatrix(right));
2136 binOp = spv::OpVectorTimesMatrix;
2137 break;
2138 case glslang::EOpMatrixTimesVector:
2139 assert(builder.isMatrix(left));
2140 assert(builder.isVector(right));
2141 binOp = spv::OpMatrixTimesVector;
2142 break;
2143 case glslang::EOpMatrixTimesScalar:
2144 case glslang::EOpMatrixTimesScalarAssign:
2145 if (builder.isMatrix(right))
2146 std::swap(left, right);
2147 assert(builder.isScalar(right));
2148 binOp = spv::OpMatrixTimesScalar;
2149 break;
2150 case glslang::EOpMatrixTimesMatrix:
2151 case glslang::EOpMatrixTimesMatrixAssign:
2152 assert(builder.isMatrix(left));
2153 assert(builder.isMatrix(right));
2154 binOp = spv::OpMatrixTimesMatrix;
2155 break;
2156 case glslang::EOpOuterProduct:
2157 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002158 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002159 break;
2160
2161 case glslang::EOpDiv:
2162 case glslang::EOpDivAssign:
2163 if (isFloat)
2164 binOp = spv::OpFDiv;
2165 else if (isUnsigned)
2166 binOp = spv::OpUDiv;
2167 else
2168 binOp = spv::OpSDiv;
2169 break;
2170 case glslang::EOpMod:
2171 case glslang::EOpModAssign:
2172 if (isFloat)
2173 binOp = spv::OpFMod;
2174 else if (isUnsigned)
2175 binOp = spv::OpUMod;
2176 else
2177 binOp = spv::OpSMod;
2178 break;
2179 case glslang::EOpRightShift:
2180 case glslang::EOpRightShiftAssign:
2181 if (isUnsigned)
2182 binOp = spv::OpShiftRightLogical;
2183 else
2184 binOp = spv::OpShiftRightArithmetic;
2185 break;
2186 case glslang::EOpLeftShift:
2187 case glslang::EOpLeftShiftAssign:
2188 binOp = spv::OpShiftLeftLogical;
2189 break;
2190 case glslang::EOpAnd:
2191 case glslang::EOpAndAssign:
2192 binOp = spv::OpBitwiseAnd;
2193 break;
2194 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002195 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002196 binOp = spv::OpLogicalAnd;
2197 break;
2198 case glslang::EOpInclusiveOr:
2199 case glslang::EOpInclusiveOrAssign:
2200 binOp = spv::OpBitwiseOr;
2201 break;
2202 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002203 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002204 binOp = spv::OpLogicalOr;
2205 break;
2206 case glslang::EOpExclusiveOr:
2207 case glslang::EOpExclusiveOrAssign:
2208 binOp = spv::OpBitwiseXor;
2209 break;
2210 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002211 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002212 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002213 break;
2214
2215 case glslang::EOpLessThan:
2216 case glslang::EOpGreaterThan:
2217 case glslang::EOpLessThanEqual:
2218 case glslang::EOpGreaterThanEqual:
2219 case glslang::EOpEqual:
2220 case glslang::EOpNotEqual:
2221 case glslang::EOpVectorEqual:
2222 case glslang::EOpVectorNotEqual:
2223 comparison = true;
2224 break;
2225 default:
2226 break;
2227 }
2228
John Kessenich7c1aa102015-10-15 13:29:11 -06002229 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002230 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002231 assert(comparison == false);
John Kessenich140f3df2015-06-26 16:58:36 -06002232 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2233 switch (binOp) {
2234 case spv::OpMatrixTimesScalar:
2235 case spv::OpVectorTimesMatrix:
2236 case spv::OpMatrixTimesVector:
2237 case spv::OpMatrixTimesMatrix:
2238 break;
2239 case spv::OpFDiv:
2240 // turn it into a multiply...
2241 assert(builder.isMatrix(left) && builder.isScalar(right));
2242 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2243 binOp = spv::OpFMul;
2244 break;
2245 default:
2246 spv::MissingFunctionality("binary operation on matrix");
2247 break;
2248 }
2249
2250 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2251 builder.setPrecision(id, precision);
2252
2253 return id;
2254 }
2255
2256 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002257 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002258 builder.promoteScalar(precision, left, right);
2259
2260 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2261 builder.setPrecision(id, precision);
2262
2263 return id;
2264 }
2265
2266 if (! comparison)
2267 return 0;
2268
John Kessenich7c1aa102015-10-15 13:29:11 -06002269 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002270
2271 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2272 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2273
2274 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2275 }
2276
2277 switch (op) {
2278 case glslang::EOpLessThan:
2279 if (isFloat)
2280 binOp = spv::OpFOrdLessThan;
2281 else if (isUnsigned)
2282 binOp = spv::OpULessThan;
2283 else
2284 binOp = spv::OpSLessThan;
2285 break;
2286 case glslang::EOpGreaterThan:
2287 if (isFloat)
2288 binOp = spv::OpFOrdGreaterThan;
2289 else if (isUnsigned)
2290 binOp = spv::OpUGreaterThan;
2291 else
2292 binOp = spv::OpSGreaterThan;
2293 break;
2294 case glslang::EOpLessThanEqual:
2295 if (isFloat)
2296 binOp = spv::OpFOrdLessThanEqual;
2297 else if (isUnsigned)
2298 binOp = spv::OpULessThanEqual;
2299 else
2300 binOp = spv::OpSLessThanEqual;
2301 break;
2302 case glslang::EOpGreaterThanEqual:
2303 if (isFloat)
2304 binOp = spv::OpFOrdGreaterThanEqual;
2305 else if (isUnsigned)
2306 binOp = spv::OpUGreaterThanEqual;
2307 else
2308 binOp = spv::OpSGreaterThanEqual;
2309 break;
2310 case glslang::EOpEqual:
2311 case glslang::EOpVectorEqual:
2312 if (isFloat)
2313 binOp = spv::OpFOrdEqual;
2314 else
2315 binOp = spv::OpIEqual;
2316 break;
2317 case glslang::EOpNotEqual:
2318 case glslang::EOpVectorNotEqual:
2319 if (isFloat)
2320 binOp = spv::OpFOrdNotEqual;
2321 else
2322 binOp = spv::OpINotEqual;
2323 break;
2324 default:
2325 break;
2326 }
2327
2328 if (binOp != spv::OpNop) {
2329 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2330 builder.setPrecision(id, precision);
2331
2332 return id;
2333 }
2334
2335 return 0;
2336}
2337
Rex Xu04db3f52015-09-16 11:44:02 +08002338spv::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 -06002339{
2340 spv::Op unaryOp = spv::OpNop;
2341 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002342 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002343 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002344
2345 switch (op) {
2346 case glslang::EOpNegative:
2347 if (isFloat)
2348 unaryOp = spv::OpFNegate;
2349 else
2350 unaryOp = spv::OpSNegate;
2351 break;
2352
2353 case glslang::EOpLogicalNot:
2354 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002355 unaryOp = spv::OpLogicalNot;
2356 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002357 case glslang::EOpBitwiseNot:
2358 unaryOp = spv::OpNot;
2359 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002360
John Kessenich140f3df2015-06-26 16:58:36 -06002361 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002362 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002363 break;
2364 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002365 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002366 break;
2367 case glslang::EOpTranspose:
2368 unaryOp = spv::OpTranspose;
2369 break;
2370
2371 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002372 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002373 break;
2374 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002375 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002376 break;
2377 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002378 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002379 break;
2380 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002381 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002382 break;
2383 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002384 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002385 break;
2386 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002387 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002388 break;
2389 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002390 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002391 break;
2392 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002393 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002394 break;
2395
2396 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002397 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002398 break;
2399 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002400 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002401 break;
2402 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002403 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002404 break;
2405 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002406 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002407 break;
2408 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002409 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002410 break;
2411 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002412 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002413 break;
2414
2415 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002416 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002417 break;
2418 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002419 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002420 break;
2421
2422 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002423 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002424 break;
2425 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002426 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002427 break;
2428 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002429 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002430 break;
2431 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002432 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002433 break;
2434 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002435 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002436 break;
2437 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002438 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002439 break;
2440
2441 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002442 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002443 break;
2444 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002445 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002446 break;
2447 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002448 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002449 break;
2450 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002451 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002452 break;
2453 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002454 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002455 break;
2456 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002457 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002458 break;
2459
2460 case glslang::EOpIsNan:
2461 unaryOp = spv::OpIsNan;
2462 break;
2463 case glslang::EOpIsInf:
2464 unaryOp = spv::OpIsInf;
2465 break;
2466
John Kessenich140f3df2015-06-26 16:58:36 -06002467 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002468 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002469 break;
2470 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002471 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002472 break;
2473 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002474 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002475 break;
2476 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002477 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002478 break;
2479 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002480 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002481 break;
2482 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002483 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002484 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002485 case glslang::EOpPackSnorm4x8:
2486 libCall = spv::GLSLstd450PackSnorm4x8;
2487 break;
2488 case glslang::EOpUnpackSnorm4x8:
2489 libCall = spv::GLSLstd450UnpackSnorm4x8;
2490 break;
2491 case glslang::EOpPackUnorm4x8:
2492 libCall = spv::GLSLstd450PackUnorm4x8;
2493 break;
2494 case glslang::EOpUnpackUnorm4x8:
2495 libCall = spv::GLSLstd450UnpackUnorm4x8;
2496 break;
2497 case glslang::EOpPackDouble2x32:
2498 libCall = spv::GLSLstd450PackDouble2x32;
2499 break;
2500 case glslang::EOpUnpackDouble2x32:
2501 libCall = spv::GLSLstd450UnpackDouble2x32;
2502 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002503
2504 case glslang::EOpDPdx:
2505 unaryOp = spv::OpDPdx;
2506 break;
2507 case glslang::EOpDPdy:
2508 unaryOp = spv::OpDPdy;
2509 break;
2510 case glslang::EOpFwidth:
2511 unaryOp = spv::OpFwidth;
2512 break;
2513 case glslang::EOpDPdxFine:
2514 unaryOp = spv::OpDPdxFine;
2515 break;
2516 case glslang::EOpDPdyFine:
2517 unaryOp = spv::OpDPdyFine;
2518 break;
2519 case glslang::EOpFwidthFine:
2520 unaryOp = spv::OpFwidthFine;
2521 break;
2522 case glslang::EOpDPdxCoarse:
2523 unaryOp = spv::OpDPdxCoarse;
2524 break;
2525 case glslang::EOpDPdyCoarse:
2526 unaryOp = spv::OpDPdyCoarse;
2527 break;
2528 case glslang::EOpFwidthCoarse:
2529 unaryOp = spv::OpFwidthCoarse;
2530 break;
2531
2532 case glslang::EOpAny:
2533 unaryOp = spv::OpAny;
2534 break;
2535 case glslang::EOpAll:
2536 unaryOp = spv::OpAll;
2537 break;
2538
2539 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002540 if (isFloat)
2541 libCall = spv::GLSLstd450FAbs;
2542 else
2543 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002544 break;
2545 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002546 if (isFloat)
2547 libCall = spv::GLSLstd450FSign;
2548 else
2549 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002550 break;
2551
John Kessenichfc51d282015-08-19 13:34:18 -06002552 case glslang::EOpAtomicCounterIncrement:
2553 case glslang::EOpAtomicCounterDecrement:
2554 case glslang::EOpAtomicCounter:
2555 {
2556 // Handle all of the atomics in one place, in createAtomicOperation()
2557 std::vector<spv::Id> operands;
2558 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002559 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002560 }
2561
2562 case glslang::EOpImageLoad:
2563 unaryOp = spv::OpImageRead;
2564 break;
2565
2566 case glslang::EOpBitFieldReverse:
2567 unaryOp = spv::OpBitReverse;
2568 break;
2569 case glslang::EOpBitCount:
2570 unaryOp = spv::OpBitCount;
2571 break;
2572 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002573 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002574 break;
2575 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002576 if (isUnsigned)
2577 libCall = spv::GLSLstd450FindUMsb;
2578 else
2579 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002580 break;
2581
John Kessenich140f3df2015-06-26 16:58:36 -06002582 default:
2583 return 0;
2584 }
2585
2586 spv::Id id;
2587 if (libCall >= 0) {
2588 std::vector<spv::Id> args;
2589 args.push_back(operand);
2590 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2591 } else
2592 id = builder.createUnaryOp(unaryOp, typeId, operand);
2593
2594 builder.setPrecision(id, precision);
2595
2596 return id;
2597}
2598
2599spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2600{
2601 spv::Op convOp = spv::OpNop;
2602 spv::Id zero = 0;
2603 spv::Id one = 0;
2604
2605 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2606
2607 switch (op) {
2608 case glslang::EOpConvIntToBool:
2609 case glslang::EOpConvUintToBool:
2610 zero = builder.makeUintConstant(0);
2611 zero = makeSmearedConstant(zero, vectorSize);
2612 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2613
2614 case glslang::EOpConvFloatToBool:
2615 zero = builder.makeFloatConstant(0.0F);
2616 zero = makeSmearedConstant(zero, vectorSize);
2617 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2618
2619 case glslang::EOpConvDoubleToBool:
2620 zero = builder.makeDoubleConstant(0.0);
2621 zero = makeSmearedConstant(zero, vectorSize);
2622 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2623
2624 case glslang::EOpConvBoolToFloat:
2625 convOp = spv::OpSelect;
2626 zero = builder.makeFloatConstant(0.0);
2627 one = builder.makeFloatConstant(1.0);
2628 break;
2629 case glslang::EOpConvBoolToDouble:
2630 convOp = spv::OpSelect;
2631 zero = builder.makeDoubleConstant(0.0);
2632 one = builder.makeDoubleConstant(1.0);
2633 break;
2634 case glslang::EOpConvBoolToInt:
2635 zero = builder.makeIntConstant(0);
2636 one = builder.makeIntConstant(1);
2637 convOp = spv::OpSelect;
2638 break;
2639 case glslang::EOpConvBoolToUint:
2640 zero = builder.makeUintConstant(0);
2641 one = builder.makeUintConstant(1);
2642 convOp = spv::OpSelect;
2643 break;
2644
2645 case glslang::EOpConvIntToFloat:
2646 case glslang::EOpConvIntToDouble:
2647 convOp = spv::OpConvertSToF;
2648 break;
2649
2650 case glslang::EOpConvUintToFloat:
2651 case glslang::EOpConvUintToDouble:
2652 convOp = spv::OpConvertUToF;
2653 break;
2654
2655 case glslang::EOpConvDoubleToFloat:
2656 case glslang::EOpConvFloatToDouble:
2657 convOp = spv::OpFConvert;
2658 break;
2659
2660 case glslang::EOpConvFloatToInt:
2661 case glslang::EOpConvDoubleToInt:
2662 convOp = spv::OpConvertFToS;
2663 break;
2664
2665 case glslang::EOpConvUintToInt:
2666 case glslang::EOpConvIntToUint:
2667 convOp = spv::OpBitcast;
2668 break;
2669
2670 case glslang::EOpConvFloatToUint:
2671 case glslang::EOpConvDoubleToUint:
2672 convOp = spv::OpConvertFToU;
2673 break;
2674 default:
2675 break;
2676 }
2677
2678 spv::Id result = 0;
2679 if (convOp == spv::OpNop)
2680 return result;
2681
2682 if (convOp == spv::OpSelect) {
2683 zero = makeSmearedConstant(zero, vectorSize);
2684 one = makeSmearedConstant(one, vectorSize);
2685 result = builder.createTriOp(convOp, destType, operand, one, zero);
2686 } else
2687 result = builder.createUnaryOp(convOp, destType, operand);
2688
2689 builder.setPrecision(result, precision);
2690
2691 return result;
2692}
2693
2694spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2695{
2696 if (vectorSize == 0)
2697 return constant;
2698
2699 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2700 std::vector<spv::Id> components;
2701 for (int c = 0; c < vectorSize; ++c)
2702 components.push_back(constant);
2703 return builder.makeCompositeConstant(vectorTypeId, components);
2704}
2705
John Kessenich426394d2015-07-23 10:22:48 -06002706// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002707spv::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 -06002708{
2709 spv::Op opCode = spv::OpNop;
2710
2711 switch (op) {
2712 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002713 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002714 opCode = spv::OpAtomicIAdd;
2715 break;
2716 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002717 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002718 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002719 break;
2720 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002721 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002722 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002723 break;
2724 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002725 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002726 opCode = spv::OpAtomicAnd;
2727 break;
2728 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002729 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002730 opCode = spv::OpAtomicOr;
2731 break;
2732 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002733 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002734 opCode = spv::OpAtomicXor;
2735 break;
2736 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002737 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002738 opCode = spv::OpAtomicExchange;
2739 break;
2740 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002741 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002742 opCode = spv::OpAtomicCompareExchange;
2743 break;
2744 case glslang::EOpAtomicCounterIncrement:
2745 opCode = spv::OpAtomicIIncrement;
2746 break;
2747 case glslang::EOpAtomicCounterDecrement:
2748 opCode = spv::OpAtomicIDecrement;
2749 break;
2750 case glslang::EOpAtomicCounter:
2751 opCode = spv::OpAtomicLoad;
2752 break;
2753 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002754 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06002755 break;
2756 }
2757
2758 // Sort out the operands
2759 // - mapping from glslang -> SPV
2760 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002761 // - compare-exchange swaps the value and comparator
2762 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002763 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2764 auto opIt = operands.begin(); // walk the glslang operands
2765 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002766 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2767 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2768 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002769 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2770 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002771 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002772 spvAtomicOperands.push_back(*(opIt + 1));
2773 spvAtomicOperands.push_back(*opIt);
2774 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002775 }
John Kessenich426394d2015-07-23 10:22:48 -06002776
John Kessenich3e60a6f2015-09-14 22:45:16 -06002777 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002778 for (; opIt != operands.end(); ++opIt)
2779 spvAtomicOperands.push_back(*opIt);
2780
2781 return builder.createOp(opCode, typeId, spvAtomicOperands);
2782}
2783
John Kessenich5e4b1242015-08-06 22:53:06 -06002784spv::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 -06002785{
John Kessenich5e4b1242015-08-06 22:53:06 -06002786 bool isUnsigned = typeProxy == glslang::EbtUint;
2787 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2788
John Kessenich140f3df2015-06-26 16:58:36 -06002789 spv::Op opCode = spv::OpNop;
2790 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002791 int consumedOperands = operands.size();
2792 spv::Id typeId0 = 0;
2793 if (consumedOperands > 0)
2794 typeId0 = builder.getTypeId(operands[0]);
2795 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002796
2797 switch (op) {
2798 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002799 if (isFloat)
2800 libCall = spv::GLSLstd450FMin;
2801 else if (isUnsigned)
2802 libCall = spv::GLSLstd450UMin;
2803 else
2804 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002805 break;
2806 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002807 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002808 break;
2809 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002810 if (isFloat)
2811 libCall = spv::GLSLstd450FMax;
2812 else if (isUnsigned)
2813 libCall = spv::GLSLstd450UMax;
2814 else
2815 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002816 break;
2817 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002818 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002819 break;
2820 case glslang::EOpDot:
2821 opCode = spv::OpDot;
2822 break;
2823 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002824 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002825 break;
2826
2827 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002828 if (isFloat)
2829 libCall = spv::GLSLstd450FClamp;
2830 else if (isUnsigned)
2831 libCall = spv::GLSLstd450UClamp;
2832 else
2833 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002834 break;
2835 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07002836 if (isFloat)
2837 libCall = spv::GLSLstd450FMix;
2838 else
2839 libCall = spv::GLSLstd450IMix;
John Kessenich140f3df2015-06-26 16:58:36 -06002840 break;
2841 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002842 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002843 break;
2844 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002845 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002846 break;
2847
2848 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002849 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002850 break;
2851 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002852 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002853 break;
2854 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002855 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002856 break;
2857 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002858 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002859 break;
2860 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002861 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002862 break;
John Kessenich426394d2015-07-23 10:22:48 -06002863
John Kessenich55e7d112015-11-15 21:33:39 -07002864 case glslang::EOpAddCarry:
2865 opCode = spv::OpIAddCarry;
2866 typeId = builder.makeStructResultType(typeId0, typeId0);
2867 consumedOperands = 2;
2868 break;
2869 case glslang::EOpSubBorrow:
2870 opCode = spv::OpISubBorrow;
2871 typeId = builder.makeStructResultType(typeId0, typeId0);
2872 consumedOperands = 2;
2873 break;
2874 case glslang::EOpUMulExtended:
2875 opCode = spv::OpUMulExtended;
2876 typeId = builder.makeStructResultType(typeId0, typeId0);
2877 consumedOperands = 2;
2878 break;
2879 case glslang::EOpIMulExtended:
2880 opCode = spv::OpSMulExtended;
2881 typeId = builder.makeStructResultType(typeId0, typeId0);
2882 consumedOperands = 2;
2883 break;
2884 case glslang::EOpBitfieldExtract:
2885 if (isUnsigned)
2886 opCode = spv::OpBitFieldUExtract;
2887 else
2888 opCode = spv::OpBitFieldSExtract;
2889 break;
2890 case glslang::EOpBitfieldInsert:
2891 opCode = spv::OpBitFieldInsert;
2892 break;
2893
2894 case glslang::EOpFma:
2895 libCall = spv::GLSLstd450Fma;
2896 break;
2897 case glslang::EOpFrexp:
2898 libCall = spv::GLSLstd450FrexpStruct;
2899 if (builder.getNumComponents(operands[0]) == 1)
2900 frexpIntType = builder.makeIntegerType(32, true);
2901 else
2902 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
2903 typeId = builder.makeStructResultType(typeId0, frexpIntType);
2904 consumedOperands = 1;
2905 break;
2906 case glslang::EOpLdexp:
2907 libCall = spv::GLSLstd450Ldexp;
2908 break;
2909
John Kessenich140f3df2015-06-26 16:58:36 -06002910 default:
2911 return 0;
2912 }
2913
2914 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07002915 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05002916 // Use an extended instruction from the standard library.
2917 // Construct the call arguments, without modifying the original operands vector.
2918 // We might need the remaining arguments, e.g. in the EOpFrexp case.
2919 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
2920 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07002921 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07002922 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06002923 case 0:
2924 // should all be handled by visitAggregate and createNoArgOperation
2925 assert(0);
2926 return 0;
2927 case 1:
2928 // should all be handled by createUnaryOperation
2929 assert(0);
2930 return 0;
2931 case 2:
2932 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2933 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002934 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002935 // anything 3 or over doesn't have l-value operands, so all should be consumed
2936 assert(consumedOperands == operands.size());
2937 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06002938 break;
2939 }
2940 }
2941
John Kessenich55e7d112015-11-15 21:33:39 -07002942 // Decode the return types that were structures
2943 switch (op) {
2944 case glslang::EOpAddCarry:
2945 case glslang::EOpSubBorrow:
2946 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
2947 id = builder.createCompositeExtract(id, typeId0, 0);
2948 break;
2949 case glslang::EOpUMulExtended:
2950 case glslang::EOpIMulExtended:
2951 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
2952 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
2953 break;
2954 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05002955 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07002956 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
2957 id = builder.createCompositeExtract(id, typeId0, 0);
2958 break;
2959 default:
2960 break;
2961 }
2962
John Kessenich140f3df2015-06-26 16:58:36 -06002963 builder.setPrecision(id, precision);
2964
2965 return id;
2966}
2967
2968// Intrinsics with no arguments, no return value, and no precision.
2969spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2970{
2971 // TODO: get the barrier operands correct
2972
2973 switch (op) {
2974 case glslang::EOpEmitVertex:
2975 builder.createNoResultOp(spv::OpEmitVertex);
2976 return 0;
2977 case glslang::EOpEndPrimitive:
2978 builder.createNoResultOp(spv::OpEndPrimitive);
2979 return 0;
2980 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002981 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2982 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002983 return 0;
2984 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002985 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002986 return 0;
2987 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002988 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002989 return 0;
2990 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002991 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002992 return 0;
2993 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002994 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002995 return 0;
2996 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07002997 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002998 return 0;
2999 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003000 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003001 return 0;
3002 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003003 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003004 return 0;
3005 }
3006}
3007
3008spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3009{
John Kessenich2f273362015-07-18 22:34:27 -06003010 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003011 spv::Id id;
3012 if (symbolValues.end() != iter) {
3013 id = iter->second;
3014 return id;
3015 }
3016
3017 // it was not found, create it
3018 id = createSpvVariable(symbol);
3019 symbolValues[symbol->getId()] = id;
3020
3021 if (! symbol->getType().isStruct()) {
3022 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
3023 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
3024 if (symbol->getQualifier().hasLocation())
3025 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3026 if (symbol->getQualifier().hasIndex())
3027 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3028 if (symbol->getQualifier().hasComponent())
3029 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3030 if (glslangIntermediate->getXfbMode()) {
3031 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003032 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003033 if (symbol->getQualifier().hasXfbBuffer())
3034 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3035 if (symbol->getQualifier().hasXfbOffset())
3036 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3037 }
3038 }
3039
3040 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
3041 if (symbol->getQualifier().hasStream())
3042 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3043 if (symbol->getQualifier().hasSet())
3044 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3045 if (symbol->getQualifier().hasBinding())
3046 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3047 if (glslangIntermediate->getXfbMode()) {
3048 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003049 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003050 if (symbol->getQualifier().hasXfbBuffer())
3051 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3052 }
3053
3054 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003055 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003056 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003057 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003058
John Kessenich140f3df2015-06-26 16:58:36 -06003059 return id;
3060}
3061
John Kessenich55e7d112015-11-15 21:33:39 -07003062// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003063void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3064{
3065 if (dec != spv::BadValue)
3066 builder.addDecoration(id, dec);
3067}
3068
John Kessenich55e7d112015-11-15 21:33:39 -07003069// If 'dec' is valid, add a one-operand decoration to an object
3070void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3071{
3072 if (dec != spv::BadValue)
3073 builder.addDecoration(id, dec, value);
3074}
3075
3076// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003077void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3078{
3079 if (dec != spv::BadValue)
3080 builder.addMemberDecoration(id, (unsigned)member, dec);
3081}
3082
John Kessenich55e7d112015-11-15 21:33:39 -07003083// Make a full tree of instructions to build a SPIR-V specialization constant,
3084// or regularly constant if possible.
3085//
3086// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3087//
3088// Recursively walk the nodes. The nodes form a tree whose leaves are
3089// regular constants, which themselves are trees that createSpvConstant()
3090// recursively walks. So, this function walks the "top" of the tree:
3091// - emit specialization constant-building instructions for specConstant
3092// - when running into a non-spec-constant, switch to createSpvConstant()
3093spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3094{
3095 assert(node.getQualifier().storage == glslang::EvqConst);
3096
3097 // hand off to the non-spec-constant path
3098 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3099 int nextConst = 0;
3100 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3101}
3102
John Kessenich140f3df2015-06-26 16:58:36 -06003103// Use 'consts' as the flattened glslang source of scalar constants to recursively
3104// build the aggregate SPIR-V constant.
3105//
3106// If there are not enough elements present in 'consts', 0 will be substituted;
3107// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3108//
John Kessenich55e7d112015-11-15 21:33:39 -07003109spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003110{
3111 // vector of constants for SPIR-V
3112 std::vector<spv::Id> spvConsts;
3113
3114 // Type is used for struct and array constants
3115 spv::Id typeId = convertGlslangToSpvType(glslangType);
3116
3117 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003118 glslang::TType elementType(glslangType, 0);
3119 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003120 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003121 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003122 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003123 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003124 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003125 } else if (glslangType.getStruct()) {
3126 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3127 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003128 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003129 } else if (glslangType.isVector()) {
3130 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3131 bool zero = nextConst >= consts.size();
3132 switch (glslangType.getBasicType()) {
3133 case glslang::EbtInt:
3134 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3135 break;
3136 case glslang::EbtUint:
3137 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3138 break;
3139 case glslang::EbtFloat:
3140 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3141 break;
3142 case glslang::EbtDouble:
3143 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3144 break;
3145 case glslang::EbtBool:
3146 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3147 break;
3148 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003149 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 }
3152 ++nextConst;
3153 }
3154 } else {
3155 // we have a non-aggregate (scalar) constant
3156 bool zero = nextConst >= consts.size();
3157 spv::Id scalar = 0;
3158 switch (glslangType.getBasicType()) {
3159 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003160 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003161 break;
3162 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003163 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003164 break;
3165 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003166 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003167 break;
3168 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003169 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003170 break;
3171 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003172 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003173 break;
3174 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003175 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003176 break;
3177 }
3178 ++nextConst;
3179 return scalar;
3180 }
3181
3182 return builder.makeCompositeConstant(typeId, spvConsts);
3183}
3184
John Kessenich7c1aa102015-10-15 13:29:11 -06003185// Return true if the node is a constant or symbol whose reading has no
3186// non-trivial observable cost or effect.
3187bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3188{
3189 // don't know what this is
3190 if (node == nullptr)
3191 return false;
3192
3193 // a constant is safe
3194 if (node->getAsConstantUnion() != nullptr)
3195 return true;
3196
3197 // not a symbol means non-trivial
3198 if (node->getAsSymbolNode() == nullptr)
3199 return false;
3200
3201 // a symbol, depends on what's being read
3202 switch (node->getType().getQualifier().storage) {
3203 case glslang::EvqTemporary:
3204 case glslang::EvqGlobal:
3205 case glslang::EvqIn:
3206 case glslang::EvqInOut:
3207 case glslang::EvqConst:
3208 case glslang::EvqConstReadOnly:
3209 case glslang::EvqUniform:
3210 return true;
3211 default:
3212 return false;
3213 }
3214}
3215
3216// A node is trivial if it is a single operation with no side effects.
3217// Error on the side of saying non-trivial.
3218// Return true if trivial.
3219bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3220{
3221 if (node == nullptr)
3222 return false;
3223
3224 // symbols and constants are trivial
3225 if (isTrivialLeaf(node))
3226 return true;
3227
3228 // otherwise, it needs to be a simple operation or one or two leaf nodes
3229
3230 // not a simple operation
3231 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3232 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3233 if (binaryNode == nullptr && unaryNode == nullptr)
3234 return false;
3235
3236 // not on leaf nodes
3237 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3238 return false;
3239
3240 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3241 return false;
3242 }
3243
3244 switch (node->getAsOperator()->getOp()) {
3245 case glslang::EOpLogicalNot:
3246 case glslang::EOpConvIntToBool:
3247 case glslang::EOpConvUintToBool:
3248 case glslang::EOpConvFloatToBool:
3249 case glslang::EOpConvDoubleToBool:
3250 case glslang::EOpEqual:
3251 case glslang::EOpNotEqual:
3252 case glslang::EOpLessThan:
3253 case glslang::EOpGreaterThan:
3254 case glslang::EOpLessThanEqual:
3255 case glslang::EOpGreaterThanEqual:
3256 case glslang::EOpIndexDirect:
3257 case glslang::EOpIndexDirectStruct:
3258 case glslang::EOpLogicalXor:
3259 case glslang::EOpAny:
3260 case glslang::EOpAll:
3261 return true;
3262 default:
3263 return false;
3264 }
3265}
3266
3267// Emit short-circuiting code, where 'right' is never evaluated unless
3268// the left side is true (for &&) or false (for ||).
3269spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3270{
3271 spv::Id boolTypeId = builder.makeBoolType();
3272
3273 // emit left operand
3274 builder.clearAccessChain();
3275 left.traverse(this);
3276 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3277
3278 // Operands to accumulate OpPhi operands
3279 std::vector<spv::Id> phiOperands;
3280 // accumulate left operand's phi information
3281 phiOperands.push_back(leftId);
3282 phiOperands.push_back(builder.getBuildPoint()->getId());
3283
3284 // Make the two kinds of operation symmetric with a "!"
3285 // || => emit "if (! left) result = right"
3286 // && => emit "if ( left) result = right"
3287 //
3288 // TODO: this runtime "not" for || could be avoided by adding functionality
3289 // to 'builder' to have an "else" without an "then"
3290 if (op == glslang::EOpLogicalOr)
3291 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3292
3293 // make an "if" based on the left value
3294 spv::Builder::If ifBuilder(leftId, builder);
3295
3296 // emit right operand as the "then" part of the "if"
3297 builder.clearAccessChain();
3298 right.traverse(this);
3299 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3300
3301 // accumulate left operand's phi information
3302 phiOperands.push_back(rightId);
3303 phiOperands.push_back(builder.getBuildPoint()->getId());
3304
3305 // finish the "if"
3306 ifBuilder.makeEndIf();
3307
3308 // phi together the two results
3309 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3310}
3311
John Kessenich140f3df2015-06-26 16:58:36 -06003312}; // end anonymous namespace
3313
3314namespace glslang {
3315
John Kessenich68d78fd2015-07-12 19:28:10 -06003316void GetSpirvVersion(std::string& version)
3317{
John Kessenich9e55f632015-07-15 10:03:39 -06003318 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003319 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003320 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003321 version = buf;
3322}
3323
John Kessenich140f3df2015-06-26 16:58:36 -06003324// Write SPIR-V out to a binary file
3325void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3326{
3327 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003328 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003329 for (int i = 0; i < (int)spirv.size(); ++i) {
3330 unsigned int word = spirv[i];
3331 out.write((const char*)&word, 4);
3332 }
3333 out.close();
3334}
3335
3336//
3337// Set up the glslang traversal
3338//
3339void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3340{
3341 TIntermNode* root = intermediate.getTreeRoot();
3342
3343 if (root == 0)
3344 return;
3345
3346 glslang::GetThreadPoolAllocator().push();
3347
3348 TGlslangToSpvTraverser it(&intermediate);
3349
3350 root->traverse(&it);
3351
3352 it.dumpSpv(spirv);
3353
3354 glslang::GetThreadPoolAllocator().pop();
3355}
3356
3357}; // end namespace glslang