blob: c005197fe3f35e724fc43d46ab110a4b001a9c37 [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
63const int GlslangMagic = 0x51a;
64
65//
66// The main holder of information for translating glslang to SPIR-V.
67//
68// Derives from the AST walking base class.
69//
70class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
71public:
72 TGlslangToSpvTraverser(const glslang::TIntermediate*);
73 virtual ~TGlslangToSpvTraverser();
74
75 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
76 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
77 void visitConstantUnion(glslang::TIntermConstantUnion*);
78 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
79 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
80 void visitSymbol(glslang::TIntermSymbol* symbol);
81 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
82 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
83 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
84
85 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
86
87protected:
88 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
89 spv::Id getSampledType(const glslang::TSampler&);
90 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich31ed4832015-09-09 17:51:38 -060091 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout);
92 bool requiresExplicitLayout(const glslang::TType& type) const;
Jason Ekstrand54aedf12015-09-05 09:50:58 -070093 int getArrayStride(const glslang::TType& arrayType);
94 int getMatrixStride(const glslang::TType& matrixType);
John Kessenich5e4b1242015-08-06 22:53:06 -060095 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060096
97 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
98 void makeFunctions(const glslang::TIntermSequence&);
99 void makeGlobalInitializers(const glslang::TIntermSequence&);
100 void visitFunctions(const glslang::TIntermSequence&);
101 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800102 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600103 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
104 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600105 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
106
107 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 +0800108 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 -0600109 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
110 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800111 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 -0600112 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 -0600113 spv::Id createNoArgOperation(glslang::TOperator op);
114 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
115 void addDecoration(spv::Id id, spv::Decoration dec);
116 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
117 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
John Kessenich7c1aa102015-10-15 13:29:11 -0600118 bool isTrivialLeaf(const glslang::TIntermTyped* node);
119 bool isTrivial(const glslang::TIntermTyped* node);
120 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600121
122 spv::Function* shaderEntry;
123 int sequenceDepth;
124
125 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
126 spv::Builder builder;
127 bool inMain;
128 bool mainTerminated;
129 bool linkageOnly;
130 const glslang::TIntermediate* glslangIntermediate;
131 spv::Id stdBuiltins;
132
John Kessenich2f273362015-07-18 22:34:27 -0600133 std::unordered_map<int, spv::Id> symbolValues;
134 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
135 std::unordered_map<std::string, spv::Function*> functionMap;
136 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
137 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 -0600138 std::stack<bool> breakForLoop; // false means break for switch
139 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
140};
141
142//
143// Helper functions for translating glslang representations to SPIR-V enumerants.
144//
145
146// Translate glslang profile to SPIR-V source language.
147spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
148{
149 switch (profile) {
150 case ENoProfile:
151 case ECoreProfile:
152 case ECompatibilityProfile:
153 return spv::SourceLanguageGLSL;
154 case EEsProfile:
155 return spv::SourceLanguageESSL;
156 default:
157 return spv::SourceLanguageUnknown;
158 }
159}
160
161// Translate glslang language (stage) to SPIR-V execution model.
162spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
163{
164 switch (stage) {
165 case EShLangVertex: return spv::ExecutionModelVertex;
166 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
167 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
168 case EShLangGeometry: return spv::ExecutionModelGeometry;
169 case EShLangFragment: return spv::ExecutionModelFragment;
170 case EShLangCompute: return spv::ExecutionModelGLCompute;
171 default:
172 spv::MissingFunctionality("GLSL stage");
173 return spv::ExecutionModelFragment;
174 }
175}
176
177// Translate glslang type to SPIR-V storage class.
178spv::StorageClass TranslateStorageClass(const glslang::TType& type)
179{
180 if (type.getQualifier().isPipeInput())
181 return spv::StorageClassInput;
182 else if (type.getQualifier().isPipeOutput())
183 return spv::StorageClassOutput;
184 else if (type.getQualifier().isUniformOrBuffer()) {
185 if (type.getBasicType() == glslang::EbtBlock)
186 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800187 else if (type.getBasicType() == glslang::EbtAtomicUint)
188 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600189 else
190 return spv::StorageClassUniformConstant;
191 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
192 } else {
193 switch (type.getQualifier().storage) {
194 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
195 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
196 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
197 case glslang::EvqTemporary: return spv::StorageClassFunction;
198 default:
199 spv::MissingFunctionality("unknown glslang storage class");
200 return spv::StorageClassFunction;
201 }
202 }
203}
204
205// Translate glslang sampler type to SPIR-V dimensionality.
206spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
207{
208 switch (sampler.dim) {
209 case glslang::Esd1D: return spv::Dim1D;
210 case glslang::Esd2D: return spv::Dim2D;
211 case glslang::Esd3D: return spv::Dim3D;
212 case glslang::EsdCube: return spv::DimCube;
213 case glslang::EsdRect: return spv::DimRect;
214 case glslang::EsdBuffer: return spv::DimBuffer;
215 default:
216 spv::MissingFunctionality("unknown sampler dimension");
217 return spv::Dim2D;
218 }
219}
220
221// Translate glslang type to SPIR-V precision decorations.
222spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
223{
224 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600225 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
226 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
227 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 default:
229 return spv::NoPrecision;
230 }
231}
232
233// Translate glslang type to SPIR-V block decorations.
234spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
235{
236 if (type.getBasicType() == glslang::EbtBlock) {
237 switch (type.getQualifier().storage) {
238 case glslang::EvqUniform: return spv::DecorationBlock;
239 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
240 case glslang::EvqVaryingIn: return spv::DecorationBlock;
241 case glslang::EvqVaryingOut: return spv::DecorationBlock;
242 default:
243 spv::MissingFunctionality("kind of block");
244 break;
245 }
246 }
247
248 return (spv::Decoration)spv::BadValue;
249}
250
251// Translate glslang type to SPIR-V layout decorations.
252spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
253{
254 if (type.isMatrix()) {
255 switch (type.getQualifier().layoutMatrix) {
256 case glslang::ElmRowMajor:
257 return spv::DecorationRowMajor;
258 default:
259 return spv::DecorationColMajor;
260 }
261 } else {
262 switch (type.getBasicType()) {
263 default:
264 return (spv::Decoration)spv::BadValue;
265 break;
266 case glslang::EbtBlock:
267 switch (type.getQualifier().storage) {
268 case glslang::EvqUniform:
269 case glslang::EvqBuffer:
270 switch (type.getQualifier().layoutPacking) {
271 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
273 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600274 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600275 }
276 case glslang::EvqVaryingIn:
277 case glslang::EvqVaryingOut:
278 if (type.getQualifier().layoutPacking != glslang::ElpNone)
279 spv::MissingFunctionality("in/out block layout");
280 return (spv::Decoration)spv::BadValue;
281 default:
282 spv::MissingFunctionality("block storage qualification");
283 return (spv::Decoration)spv::BadValue;
284 }
285 }
286 }
287}
288
289// Translate glslang type to SPIR-V interpolation decorations.
290spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
291{
292 if (type.getQualifier().smooth)
293 return spv::DecorationSmooth;
294 if (type.getQualifier().nopersp)
295 return spv::DecorationNoperspective;
296 else if (type.getQualifier().patch)
297 return spv::DecorationPatch;
298 else if (type.getQualifier().flat)
299 return spv::DecorationFlat;
300 else if (type.getQualifier().centroid)
301 return spv::DecorationCentroid;
302 else if (type.getQualifier().sample)
303 return spv::DecorationSample;
304 else
305 return (spv::Decoration)spv::BadValue;
306}
307
308// If glslang type is invaraiant, return SPIR-V invariant decoration.
309spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
310{
311 if (type.getQualifier().invariant)
312 return spv::DecorationInvariant;
313 else
314 return (spv::Decoration)spv::BadValue;
315}
316
317// Translate glslang built-in variable to SPIR-V built in decoration.
318spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
319{
320 switch (builtIn) {
321 case glslang::EbvPosition: return spv::BuiltInPosition;
322 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600323 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
324 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
325 case glslang::EbvVertexId: return spv::BuiltInVertexId;
326 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600327 case glslang::EbvBaseVertex:
328 case glslang::EbvBaseInstance:
329 case glslang::EbvDrawId:
330 // TODO: Add SPIR-V builtin ID.
331 spv::MissingFunctionality("Draw parameters");
332 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600333 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
334 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
335 case glslang::EbvLayer: return spv::BuiltInLayer;
336 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
337 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
338 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
339 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
340 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
341 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
342 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
343 case glslang::EbvFace: return spv::BuiltInFrontFacing;
344 case glslang::EbvSampleId: return spv::BuiltInSampleId;
345 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
346 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
347 case glslang::EbvFragColor: return spv::BuiltInFragColor;
348 case glslang::EbvFragData: return spv::BuiltInFragColor;
349 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
350 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
351 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
352 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
353 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
354 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
355 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
356 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
357 default: return (spv::BuiltIn)spv::BadValue;
358 }
359}
360
Rex Xufc618912015-09-09 16:42:49 +0800361// Translate glslang image layout format to SPIR-V image format.
362spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
363{
364 assert(type.getBasicType() == glslang::EbtSampler);
365
366 switch (type.getQualifier().layoutFormat) {
367 case glslang::ElfNone: return spv::ImageFormatUnknown;
368 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
369 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
370 case glslang::ElfR32f: return spv::ImageFormatR32f;
371 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
372 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
373 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
374 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
375 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
376 case glslang::ElfR16f: return spv::ImageFormatR16f;
377 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
378 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
379 case glslang::ElfRg16: return spv::ImageFormatRg16;
380 case glslang::ElfRg8: return spv::ImageFormatRg8;
381 case glslang::ElfR16: return spv::ImageFormatR16;
382 case glslang::ElfR8: return spv::ImageFormatR8;
383 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
384 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
385 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
386 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
387 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
388 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
389 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
390 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
391 case glslang::ElfR32i: return spv::ImageFormatR32i;
392 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
393 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
394 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
395 case glslang::ElfR16i: return spv::ImageFormatR16i;
396 case glslang::ElfR8i: return spv::ImageFormatR8i;
397 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
398 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
399 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
400 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
401 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
402 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
403 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
404 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
405 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
406 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
407 default: return (spv::ImageFormat)spv::BadValue;
408 }
409}
410
John Kessenich140f3df2015-06-26 16:58:36 -0600411//
412// Implement the TGlslangToSpvTraverser class.
413//
414
415TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
416 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
417 builder(GlslangMagic),
418 inMain(false), mainTerminated(false), linkageOnly(false),
419 glslangIntermediate(glslangIntermediate)
420{
421 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
422
423 builder.clearAccessChain();
424 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
425 stdBuiltins = builder.import("GLSL.std.450");
426 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
427 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600428 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600429
430 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600431 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
432 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600433 builder.addSourceExtension(it->c_str());
434
435 // Add the top-level modes for this shader.
436
437 if (glslangIntermediate->getXfbMode())
438 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
439
440 unsigned int mode;
441 switch (glslangIntermediate->getStage()) {
442 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600443 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600444 break;
445
446 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600447 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600448 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
449 break;
450
451 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600452 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600453 switch (glslangIntermediate->getInputPrimitive()) {
454 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
455 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
456 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600457 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600458 }
459 if (mode != spv::BadValue)
460 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
461
John Kesseniche6903322015-10-13 16:29:02 -0600462 switch (glslangIntermediate->getVertexSpacing()) {
463 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
464 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
465 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
466 default: mode = spv::BadValue; break;
467 }
468 if (mode != spv::BadValue)
469 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
470
471 switch (glslangIntermediate->getVertexOrder()) {
472 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
473 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
474 default: mode = spv::BadValue; break;
475 }
476 if (mode != spv::BadValue)
477 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
478
479 if (glslangIntermediate->getPointMode())
480 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600481 break;
482
483 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600484 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600485 switch (glslangIntermediate->getInputPrimitive()) {
486 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
487 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
488 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
489 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
490 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
491 default: mode = spv::BadValue; break;
492 }
493 if (mode != spv::BadValue)
494 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
497
498 switch (glslangIntermediate->getOutputPrimitive()) {
499 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
500 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
501 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
502 default: mode = spv::BadValue; break;
503 }
504 if (mode != spv::BadValue)
505 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
506 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
507 break;
508
509 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600510 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600511 if (glslangIntermediate->getPixelCenterInteger())
512 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600513
John Kessenich140f3df2015-06-26 16:58:36 -0600514 if (glslangIntermediate->getOriginUpperLeft())
515 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600516 else
517 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600518
519 if (glslangIntermediate->getEarlyFragmentTests())
520 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
521
522 switch(glslangIntermediate->getDepth()) {
523 case glslang::EldAny: mode = spv::ExecutionModeDepthAny; break;
524 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
525 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
526 default: mode = spv::BadValue; break;
527 }
528 if (mode != spv::BadValue)
529 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
530
531 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
532 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600533 break;
534
535 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600536 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600537 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
538 glslangIntermediate->getLocalSize(1),
539 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600540 break;
541
542 default:
543 break;
544 }
545
546}
547
548TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
549{
550 if (! mainTerminated) {
551 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
552 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600553 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600554 }
555}
556
557//
558// Implement the traversal functions.
559//
560// Return true from interior nodes to have the external traversal
561// continue on to children. Return false if children were
562// already processed.
563//
564
565//
566// Symbols can turn into
567// - uniform/input reads
568// - output writes
569// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
570// - something simple that degenerates into the last bullet
571//
572void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
573{
574 // getSymbolId() will set up all the IO decorations on the first call.
575 // Formal function parameters were mapped during makeFunctions().
576 spv::Id id = getSymbolId(symbol);
577
578 if (! linkageOnly) {
579 // Prepare to generate code for the access
580
581 // L-value chains will be computed left to right. We're on the symbol now,
582 // which is the left-most part of the access chain, so now is "clear" time,
583 // followed by setting the base.
584 builder.clearAccessChain();
585
586 // For now, we consider all user variables as being in memory, so they are pointers,
587 // except for "const in" arguments to a function, which are an intermediate object.
588 // See comments in handleUserFunctionCall().
589 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
590 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
591 builder.setAccessChainRValue(id);
592 else
593 builder.setAccessChainLValue(id);
594 }
595}
596
597bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
598{
599 // First, handle special cases
600 switch (node->getOp()) {
601 case glslang::EOpAssign:
602 case glslang::EOpAddAssign:
603 case glslang::EOpSubAssign:
604 case glslang::EOpMulAssign:
605 case glslang::EOpVectorTimesMatrixAssign:
606 case glslang::EOpVectorTimesScalarAssign:
607 case glslang::EOpMatrixTimesScalarAssign:
608 case glslang::EOpMatrixTimesMatrixAssign:
609 case glslang::EOpDivAssign:
610 case glslang::EOpModAssign:
611 case glslang::EOpAndAssign:
612 case glslang::EOpInclusiveOrAssign:
613 case glslang::EOpExclusiveOrAssign:
614 case glslang::EOpLeftShiftAssign:
615 case glslang::EOpRightShiftAssign:
616 // A bin-op assign "a += b" means the same thing as "a = a + b"
617 // where a is evaluated before b. For a simple assignment, GLSL
618 // says to evaluate the left before the right. So, always, left
619 // node then right node.
620 {
621 // get the left l-value, save it away
622 builder.clearAccessChain();
623 node->getLeft()->traverse(this);
624 spv::Builder::AccessChain lValue = builder.getAccessChain();
625
626 // evaluate the right
627 builder.clearAccessChain();
628 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600629 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600630
631 if (node->getOp() != glslang::EOpAssign) {
632 // the left is also an r-value
633 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600634 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600635
636 // do the operation
637 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
638 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
639 node->getType().getBasicType());
640
641 // these all need their counterparts in createBinaryOperation()
642 if (rValue == 0)
643 spv::MissingFunctionality("createBinaryOperation");
644 }
645
646 // store the result
647 builder.setAccessChain(lValue);
648 builder.accessChainStore(rValue);
649
650 // assignments are expressions having an rValue after they are evaluated...
651 builder.clearAccessChain();
652 builder.setAccessChainRValue(rValue);
653 }
654 return false;
655 case glslang::EOpIndexDirect:
656 case glslang::EOpIndexDirectStruct:
657 {
658 // Get the left part of the access chain.
659 node->getLeft()->traverse(this);
660
661 // Add the next element in the chain
662
663 int index = 0;
664 if (node->getRight()->getAsConstantUnion() == 0)
665 spv::MissingFunctionality("direct index without a constant node");
666 else
667 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
668
669 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
670 // This may be, e.g., an anonymous block-member selection, which generally need
671 // index remapping due to hidden members in anonymous blocks.
672 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
673 if (remapper.size() == 0)
674 spv::MissingFunctionality("block without member remapping");
675 else
676 index = remapper[index];
677 }
678
679 if (! node->getLeft()->getType().isArray() &&
680 node->getLeft()->getType().isVector() &&
681 node->getOp() == glslang::EOpIndexDirect) {
682 // This is essentially a hard-coded vector swizzle of size 1,
683 // so short circuit the access-chain stuff with a swizzle.
684 std::vector<unsigned> swizzle;
685 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600686 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600687 } else {
688 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600689 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600690 }
691 }
692 return false;
693 case glslang::EOpIndexIndirect:
694 {
695 // Structure or array or vector indirection.
696 // Will use native SPIR-V access-chain for struct and array indirection;
697 // matrices are arrays of vectors, so will also work for a matrix.
698 // Will use the access chain's 'component' for variable index into a vector.
699
700 // This adapter is building access chains left to right.
701 // Set up the access chain to the left.
702 node->getLeft()->traverse(this);
703
704 // save it so that computing the right side doesn't trash it
705 spv::Builder::AccessChain partial = builder.getAccessChain();
706
707 // compute the next index in the chain
708 builder.clearAccessChain();
709 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600710 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600711
712 // restore the saved access chain
713 builder.setAccessChain(partial);
714
715 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600716 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600717 else
John Kessenichfa668da2015-09-13 14:46:30 -0600718 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600719 }
720 return false;
721 case glslang::EOpVectorSwizzle:
722 {
723 node->getLeft()->traverse(this);
724 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
725 std::vector<unsigned> swizzle;
726 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
727 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600728 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600729 }
730 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600731 case glslang::EOpLogicalOr:
732 case glslang::EOpLogicalAnd:
733 {
734
735 // These may require short circuiting, but can sometimes be done as straight
736 // binary operations. The right operand must be short circuited if it has
737 // side effects, and should probably be if it is complex.
738 if (isTrivial(node->getRight()->getAsTyped()))
739 break; // handle below as a normal binary operation
740 // otherwise, we need to do dynamic short circuiting on the right operand
741 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
742 builder.clearAccessChain();
743 builder.setAccessChainRValue(result);
744 }
745 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600746 default:
747 break;
748 }
749
750 // Assume generic binary op...
751
752 // Get the operands
753 builder.clearAccessChain();
754 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600755 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600756
757 builder.clearAccessChain();
758 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600759 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600760
761 spv::Id result;
762 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
763
764 result = createBinaryOperation(node->getOp(), precision,
765 convertGlslangToSpvType(node->getType()), left, right,
766 node->getLeft()->getType().getBasicType());
767
768 if (! result) {
769 spv::MissingFunctionality("glslang binary operation");
770 } else {
771 builder.clearAccessChain();
772 builder.setAccessChainRValue(result);
773
774 return false;
775 }
776
777 return true;
778}
779
780bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
781{
John Kessenichfc51d282015-08-19 13:34:18 -0600782 spv::Id result = spv::NoResult;
783
784 // try texturing first
785 result = createImageTextureFunctionCall(node);
786 if (result != spv::NoResult) {
787 builder.clearAccessChain();
788 builder.setAccessChainRValue(result);
789
790 return false; // done with this node
791 }
792
793 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600794
795 if (node->getOp() == glslang::EOpArrayLength) {
796 // Quite special; won't want to evaluate the operand.
797
798 // Normal .length() would have been constant folded by the front-end.
799 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600800 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600801 assert(node->getOperand()->getType().isRuntimeSizedArray());
802 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
803 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600804 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
805 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600806
807 builder.clearAccessChain();
808 builder.setAccessChainRValue(length);
809
810 return false;
811 }
812
John Kessenichfc51d282015-08-19 13:34:18 -0600813 // Start by evaluating the operand
814
John Kessenich140f3df2015-06-26 16:58:36 -0600815 builder.clearAccessChain();
816 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800817
Rex Xufc618912015-09-09 16:42:49 +0800818 spv::Id operand = spv::NoResult;
819
820 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
821 node->getOp() == glslang::EOpAtomicCounterDecrement ||
822 node->getOp() == glslang::EOpAtomicCounter)
823 operand = builder.accessChainGetLValue(); // Special case l-value operands
824 else
Rex Xu30f92582015-09-14 10:38:56 +0800825 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600826
827 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
828
829 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600830 if (! result)
831 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600832
833 // if not, then possibly an operation
834 if (! result)
Rex Xu04db3f52015-09-16 11:44:02 +0800835 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600836
837 if (result) {
838 builder.clearAccessChain();
839 builder.setAccessChainRValue(result);
840
841 return false; // done with this node
842 }
843
844 // it must be a special case, check...
845 switch (node->getOp()) {
846 case glslang::EOpPostIncrement:
847 case glslang::EOpPostDecrement:
848 case glslang::EOpPreIncrement:
849 case glslang::EOpPreDecrement:
850 {
851 // we need the integer value "1" or the floating point "1.0" to add/subtract
852 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
853 builder.makeFloatConstant(1.0F) :
854 builder.makeIntConstant(1);
855 glslang::TOperator op;
856 if (node->getOp() == glslang::EOpPreIncrement ||
857 node->getOp() == glslang::EOpPostIncrement)
858 op = glslang::EOpAdd;
859 else
860 op = glslang::EOpSub;
861
862 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
863 convertGlslangToSpvType(node->getType()), operand, one,
864 node->getType().getBasicType());
865 if (result == 0)
866 spv::MissingFunctionality("createBinaryOperation for unary");
867
868 // The result of operation is always stored, but conditionally the
869 // consumed result. The consumed result is always an r-value.
870 builder.accessChainStore(result);
871 builder.clearAccessChain();
872 if (node->getOp() == glslang::EOpPreIncrement ||
873 node->getOp() == glslang::EOpPreDecrement)
874 builder.setAccessChainRValue(result);
875 else
876 builder.setAccessChainRValue(operand);
877 }
878
879 return false;
880
881 case glslang::EOpEmitStreamVertex:
882 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
883 return false;
884 case glslang::EOpEndStreamPrimitive:
885 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
886 return false;
887
888 default:
889 spv::MissingFunctionality("glslang unary");
890 break;
891 }
892
893 return true;
894}
895
896bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
897{
John Kessenichfc51d282015-08-19 13:34:18 -0600898 spv::Id result = spv::NoResult;
899
900 // try texturing
901 result = createImageTextureFunctionCall(node);
902 if (result != spv::NoResult) {
903 builder.clearAccessChain();
904 builder.setAccessChainRValue(result);
905
906 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600907 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800908 // "imageStore" is a special case, which has no result
909 return false;
910 }
John Kessenichfc51d282015-08-19 13:34:18 -0600911
John Kessenich140f3df2015-06-26 16:58:36 -0600912 glslang::TOperator binOp = glslang::EOpNull;
913 bool reduceComparison = true;
914 bool isMatrix = false;
915 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600916 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600917
918 assert(node->getOp());
919
920 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
921
922 switch (node->getOp()) {
923 case glslang::EOpSequence:
924 {
925 if (preVisit)
926 ++sequenceDepth;
927 else
928 --sequenceDepth;
929
930 if (sequenceDepth == 1) {
931 // If this is the parent node of all the functions, we want to see them
932 // early, so all call points have actual SPIR-V functions to reference.
933 // In all cases, still let the traverser visit the children for us.
934 makeFunctions(node->getAsAggregate()->getSequence());
935
936 // Also, we want all globals initializers to go into the entry of main(), before
937 // anything else gets there, so visit out of order, doing them all now.
938 makeGlobalInitializers(node->getAsAggregate()->getSequence());
939
940 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
941 // so do them manually.
942 visitFunctions(node->getAsAggregate()->getSequence());
943
944 return false;
945 }
946
947 return true;
948 }
949 case glslang::EOpLinkerObjects:
950 {
951 if (visit == glslang::EvPreVisit)
952 linkageOnly = true;
953 else
954 linkageOnly = false;
955
956 return true;
957 }
958 case glslang::EOpComma:
959 {
960 // processing from left to right naturally leaves the right-most
961 // lying around in the access chain
962 glslang::TIntermSequence& glslangOperands = node->getSequence();
963 for (int i = 0; i < (int)glslangOperands.size(); ++i)
964 glslangOperands[i]->traverse(this);
965
966 return false;
967 }
968 case glslang::EOpFunction:
969 if (visit == glslang::EvPreVisit) {
970 if (isShaderEntrypoint(node)) {
971 inMain = true;
972 builder.setBuildPoint(shaderEntry->getLastBlock());
973 } else {
974 handleFunctionEntry(node);
975 }
976 } else {
977 if (inMain)
978 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600979 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600980 inMain = false;
981 }
982
983 return true;
984 case glslang::EOpParameters:
985 // Parameters will have been consumed by EOpFunction processing, but not
986 // the body, so we still visited the function node's children, making this
987 // child redundant.
988 return false;
989 case glslang::EOpFunctionCall:
990 {
991 if (node->isUserDefined())
992 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600993
994 if (! result) {
995 spv::MissingFunctionality("glslang function call");
996 glslang::TConstUnionArray emptyConsts;
997 int nextConst = 0;
998 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
999 }
1000 builder.clearAccessChain();
1001 builder.setAccessChainRValue(result);
1002
1003 return false;
1004 }
1005 case glslang::EOpConstructMat2x2:
1006 case glslang::EOpConstructMat2x3:
1007 case glslang::EOpConstructMat2x4:
1008 case glslang::EOpConstructMat3x2:
1009 case glslang::EOpConstructMat3x3:
1010 case glslang::EOpConstructMat3x4:
1011 case glslang::EOpConstructMat4x2:
1012 case glslang::EOpConstructMat4x3:
1013 case glslang::EOpConstructMat4x4:
1014 case glslang::EOpConstructDMat2x2:
1015 case glslang::EOpConstructDMat2x3:
1016 case glslang::EOpConstructDMat2x4:
1017 case glslang::EOpConstructDMat3x2:
1018 case glslang::EOpConstructDMat3x3:
1019 case glslang::EOpConstructDMat3x4:
1020 case glslang::EOpConstructDMat4x2:
1021 case glslang::EOpConstructDMat4x3:
1022 case glslang::EOpConstructDMat4x4:
1023 isMatrix = true;
1024 // fall through
1025 case glslang::EOpConstructFloat:
1026 case glslang::EOpConstructVec2:
1027 case glslang::EOpConstructVec3:
1028 case glslang::EOpConstructVec4:
1029 case glslang::EOpConstructDouble:
1030 case glslang::EOpConstructDVec2:
1031 case glslang::EOpConstructDVec3:
1032 case glslang::EOpConstructDVec4:
1033 case glslang::EOpConstructBool:
1034 case glslang::EOpConstructBVec2:
1035 case glslang::EOpConstructBVec3:
1036 case glslang::EOpConstructBVec4:
1037 case glslang::EOpConstructInt:
1038 case glslang::EOpConstructIVec2:
1039 case glslang::EOpConstructIVec3:
1040 case glslang::EOpConstructIVec4:
1041 case glslang::EOpConstructUint:
1042 case glslang::EOpConstructUVec2:
1043 case glslang::EOpConstructUVec3:
1044 case glslang::EOpConstructUVec4:
1045 case glslang::EOpConstructStruct:
1046 {
1047 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001048 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001049 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1050 spv::Id constructed;
1051 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1052 std::vector<spv::Id> constituents;
1053 for (int c = 0; c < (int)arguments.size(); ++c)
1054 constituents.push_back(arguments[c]);
1055 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
1056 } else {
1057 if (isMatrix)
1058 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1059 else
1060 constructed = builder.createConstructor(precision, arguments, resultTypeId);
1061 }
1062
1063 builder.clearAccessChain();
1064 builder.setAccessChainRValue(constructed);
1065
1066 return false;
1067 }
1068
1069 // These six are component-wise compares with component-wise results.
1070 // Forward on to createBinaryOperation(), requesting a vector result.
1071 case glslang::EOpLessThan:
1072 case glslang::EOpGreaterThan:
1073 case glslang::EOpLessThanEqual:
1074 case glslang::EOpGreaterThanEqual:
1075 case glslang::EOpVectorEqual:
1076 case glslang::EOpVectorNotEqual:
1077 {
1078 // Map the operation to a binary
1079 binOp = node->getOp();
1080 reduceComparison = false;
1081 switch (node->getOp()) {
1082 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1083 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1084 default: binOp = node->getOp(); break;
1085 }
1086
1087 break;
1088 }
1089 case glslang::EOpMul:
1090 // compontent-wise matrix multiply
1091 binOp = glslang::EOpMul;
1092 break;
1093 case glslang::EOpOuterProduct:
1094 // two vectors multiplied to make a matrix
1095 binOp = glslang::EOpOuterProduct;
1096 break;
1097 case glslang::EOpDot:
1098 {
1099 // for scalar dot product, use multiply
1100 glslang::TIntermSequence& glslangOperands = node->getSequence();
1101 if (! glslangOperands[0]->getAsTyped()->isVector())
1102 binOp = glslang::EOpMul;
1103 break;
1104 }
1105 case glslang::EOpMod:
1106 // when an aggregate, this is the floating-point mod built-in function,
1107 // which can be emitted by the one in createBinaryOperation()
1108 binOp = glslang::EOpMod;
1109 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001110 case glslang::EOpEmitVertex:
1111 case glslang::EOpEndPrimitive:
1112 case glslang::EOpBarrier:
1113 case glslang::EOpMemoryBarrier:
1114 case glslang::EOpMemoryBarrierAtomicCounter:
1115 case glslang::EOpMemoryBarrierBuffer:
1116 case glslang::EOpMemoryBarrierImage:
1117 case glslang::EOpMemoryBarrierShared:
1118 case glslang::EOpGroupMemoryBarrier:
1119 noReturnValue = true;
1120 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1121 break;
1122
John Kessenich426394d2015-07-23 10:22:48 -06001123 case glslang::EOpAtomicAdd:
1124 case glslang::EOpAtomicMin:
1125 case glslang::EOpAtomicMax:
1126 case glslang::EOpAtomicAnd:
1127 case glslang::EOpAtomicOr:
1128 case glslang::EOpAtomicXor:
1129 case glslang::EOpAtomicExchange:
1130 case glslang::EOpAtomicCompSwap:
1131 atomic = true;
1132 break;
1133
John Kessenichfc51d282015-08-19 13:34:18 -06001134 case glslang::EOpAddCarry:
1135 case glslang::EOpSubBorrow:
1136 case glslang::EOpUMulExtended:
1137 case glslang::EOpIMulExtended:
1138 case glslang::EOpBitfieldExtract:
1139 case glslang::EOpBitfieldInsert:
1140 spv::MissingFunctionality("integer aggregate");
1141 break;
1142
1143 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001144 case glslang::EOpFrexp:
1145 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001146 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1147 break;
1148
John Kessenich140f3df2015-06-26 16:58:36 -06001149 default:
1150 break;
1151 }
1152
1153 //
1154 // See if it maps to a regular operation.
1155 //
John Kessenich140f3df2015-06-26 16:58:36 -06001156 if (binOp != glslang::EOpNull) {
1157 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1158 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1159 assert(left && right);
1160
1161 builder.clearAccessChain();
1162 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001163 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001164
1165 builder.clearAccessChain();
1166 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001167 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001168
1169 result = createBinaryOperation(binOp, precision,
1170 convertGlslangToSpvType(node->getType()), leftId, rightId,
1171 left->getType().getBasicType(), reduceComparison);
1172
1173 // code above should only make binOp that exists in createBinaryOperation
1174 if (result == 0)
1175 spv::MissingFunctionality("createBinaryOperation for aggregate");
1176
1177 builder.clearAccessChain();
1178 builder.setAccessChainRValue(result);
1179
1180 return false;
1181 }
1182
John Kessenich426394d2015-07-23 10:22:48 -06001183 //
1184 // Create the list of operands.
1185 //
John Kessenich140f3df2015-06-26 16:58:36 -06001186 glslang::TIntermSequence& glslangOperands = node->getSequence();
1187 std::vector<spv::Id> operands;
1188 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1189 builder.clearAccessChain();
1190 glslangOperands[arg]->traverse(this);
1191
1192 // special case l-value operands; there are just a few
1193 bool lvalue = false;
1194 switch (node->getOp()) {
1195 //case glslang::EOpFrexp:
1196 case glslang::EOpModf:
1197 if (arg == 1)
1198 lvalue = true;
1199 break;
Rex Xud4782c12015-09-06 16:30:11 +08001200 case glslang::EOpAtomicAdd:
1201 case glslang::EOpAtomicMin:
1202 case glslang::EOpAtomicMax:
1203 case glslang::EOpAtomicAnd:
1204 case glslang::EOpAtomicOr:
1205 case glslang::EOpAtomicXor:
1206 case glslang::EOpAtomicExchange:
1207 case glslang::EOpAtomicCompSwap:
1208 if (arg == 0)
1209 lvalue = true;
1210 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001211 //case glslang::EOpUAddCarry:
1212 //case glslang::EOpUSubBorrow:
1213 //case glslang::EOpUMulExtended:
1214 default:
1215 break;
1216 }
1217 if (lvalue)
1218 operands.push_back(builder.accessChainGetLValue());
1219 else
John Kessenichfa668da2015-09-13 14:46:30 -06001220 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001221 }
John Kessenich426394d2015-07-23 10:22:48 -06001222
1223 if (atomic) {
1224 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001225 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001226 } else {
1227 // Pass through to generic operations.
1228 switch (glslangOperands.size()) {
1229 case 0:
1230 result = createNoArgOperation(node->getOp());
1231 break;
1232 case 1:
Rex Xu04db3f52015-09-16 11:44:02 +08001233 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001234 break;
1235 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001236 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001237 break;
1238 }
John Kessenich140f3df2015-06-26 16:58:36 -06001239 }
1240
1241 if (noReturnValue)
1242 return false;
1243
1244 if (! result) {
1245 spv::MissingFunctionality("glslang aggregate");
1246 return true;
1247 } else {
1248 builder.clearAccessChain();
1249 builder.setAccessChainRValue(result);
1250 return false;
1251 }
1252}
1253
1254bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1255{
1256 // This path handles both if-then-else and ?:
1257 // The if-then-else has a node type of void, while
1258 // ?: has a non-void node type
1259 spv::Id result = 0;
1260 if (node->getBasicType() != glslang::EbtVoid) {
1261 // don't handle this as just on-the-fly temporaries, because there will be two names
1262 // and better to leave SSA to later passes
1263 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1264 }
1265
1266 // emit the condition before doing anything with selection
1267 node->getCondition()->traverse(this);
1268
1269 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001270 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001271
1272 if (node->getTrueBlock()) {
1273 // emit the "then" statement
1274 node->getTrueBlock()->traverse(this);
1275 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001276 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001277 }
1278
1279 if (node->getFalseBlock()) {
1280 ifBuilder.makeBeginElse();
1281 // emit the "else" statement
1282 node->getFalseBlock()->traverse(this);
1283 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001284 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001285 }
1286
1287 ifBuilder.makeEndIf();
1288
1289 if (result) {
1290 // GLSL only has r-values as the result of a :?, but
1291 // if we have an l-value, that can be more efficient if it will
1292 // become the base of a complex r-value expression, because the
1293 // next layer copies r-values into memory to use the access-chain mechanism
1294 builder.clearAccessChain();
1295 builder.setAccessChainLValue(result);
1296 }
1297
1298 return false;
1299}
1300
1301bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1302{
1303 // emit and get the condition before doing anything with switch
1304 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001305 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001306
1307 // browse the children to sort out code segments
1308 int defaultSegment = -1;
1309 std::vector<TIntermNode*> codeSegments;
1310 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1311 std::vector<int> caseValues;
1312 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1313 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1314 TIntermNode* child = *c;
1315 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001316 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001317 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001318 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001319 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1320 } else
1321 codeSegments.push_back(child);
1322 }
1323
1324 // handle the case where the last code segment is missing, due to no code
1325 // statements between the last case and the end of the switch statement
1326 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1327 (int)codeSegments.size() == defaultSegment)
1328 codeSegments.push_back(nullptr);
1329
1330 // make the switch statement
1331 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001332 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001333
1334 // emit all the code in the segments
1335 breakForLoop.push(false);
1336 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1337 builder.nextSwitchSegment(segmentBlocks, s);
1338 if (codeSegments[s])
1339 codeSegments[s]->traverse(this);
1340 else
1341 builder.addSwitchBreak();
1342 }
1343 breakForLoop.pop();
1344
1345 builder.endSwitch(segmentBlocks);
1346
1347 return false;
1348}
1349
1350void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1351{
1352 int nextConst = 0;
1353 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1354
1355 builder.clearAccessChain();
1356 builder.setAccessChainRValue(constant);
1357}
1358
1359bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1360{
1361 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1362 loopTerminal.push(node->getTerminal());
1363
David Netoc22f37c2015-07-15 16:21:26 -04001364 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001365
1366 if (node->getTest()) {
1367 node->getTest()->traverse(this);
1368 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001369 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001370 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001371 } else {
1372 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001373 }
1374
David Netoc22f37c2015-07-15 16:21:26 -04001375 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001376 breakForLoop.push(true);
1377 node->getBody()->traverse(this);
1378 breakForLoop.pop();
1379 }
1380
1381 if (loopTerminal.top())
1382 loopTerminal.top()->traverse(this);
1383
1384 builder.closeLoop();
1385
1386 loopTerminal.pop();
1387
1388 return false;
1389}
1390
1391bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1392{
1393 if (node->getExpression())
1394 node->getExpression()->traverse(this);
1395
1396 switch (node->getFlowOp()) {
1397 case glslang::EOpKill:
1398 builder.makeDiscard();
1399 break;
1400 case glslang::EOpBreak:
1401 if (breakForLoop.top())
1402 builder.createLoopExit();
1403 else
1404 builder.addSwitchBreak();
1405 break;
1406 case glslang::EOpContinue:
1407 if (loopTerminal.top())
1408 loopTerminal.top()->traverse(this);
1409 builder.createLoopContinue();
1410 break;
1411 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001412 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001413 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001414 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001415 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001416
1417 builder.clearAccessChain();
1418 break;
1419
1420 default:
1421 spv::MissingFunctionality("branch type");
1422 break;
1423 }
1424
1425 return false;
1426}
1427
1428spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1429{
1430 // First, steer off constants, which are not SPIR-V variables, but
1431 // can still have a mapping to a SPIR-V Id.
1432 if (node->getQualifier().storage == glslang::EvqConst) {
1433 int nextConst = 0;
1434 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1435 }
1436
1437 // Now, handle actual variables
1438 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1439 spv::Id spvType = convertGlslangToSpvType(node->getType());
1440
1441 const char* name = node->getName().c_str();
1442 if (glslang::IsAnonymous(name))
1443 name = "";
1444
1445 return builder.createVariable(storageClass, spvType, name);
1446}
1447
1448// Return type Id of the sampled type.
1449spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1450{
1451 switch (sampler.type) {
1452 case glslang::EbtFloat: return builder.makeFloatType(32);
1453 case glslang::EbtInt: return builder.makeIntType(32);
1454 case glslang::EbtUint: return builder.makeUintType(32);
1455 default:
1456 spv::MissingFunctionality("sampled type");
1457 return builder.makeFloatType(32);
1458 }
1459}
1460
John Kessenich31ed4832015-09-09 17:51:38 -06001461// Convert from a glslang type to an SPV type, by calling into
1462// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001463spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1464{
John Kessenich31ed4832015-09-09 17:51:38 -06001465 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1466}
1467
1468// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1469// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1470spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1471{
John Kessenich140f3df2015-06-26 16:58:36 -06001472 spv::Id spvType = 0;
1473
1474 switch (type.getBasicType()) {
1475 case glslang::EbtVoid:
1476 spvType = builder.makeVoidType();
1477 if (type.isArray())
1478 spv::MissingFunctionality("array of void");
1479 break;
1480 case glslang::EbtFloat:
1481 spvType = builder.makeFloatType(32);
1482 break;
1483 case glslang::EbtDouble:
1484 spvType = builder.makeFloatType(64);
1485 break;
1486 case glslang::EbtBool:
1487 spvType = builder.makeBoolType();
1488 break;
1489 case glslang::EbtInt:
1490 spvType = builder.makeIntType(32);
1491 break;
1492 case glslang::EbtUint:
1493 spvType = builder.makeUintType(32);
1494 break;
John Kessenich426394d2015-07-23 10:22:48 -06001495 case glslang::EbtAtomicUint:
1496 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1497 spvType = builder.makeUintType(32);
1498 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001499 case glslang::EbtSampler:
1500 {
1501 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001502 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
Rex Xufc618912015-09-09 16:42:49 +08001503 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich5e4b1242015-08-06 22:53:06 -06001504 // OpenGL "textures" need to be combined with a sampler
1505 if (! sampler.image)
1506 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001507 }
1508 break;
1509 case glslang::EbtStruct:
1510 case glslang::EbtBlock:
1511 {
1512 // If we've seen this struct type, return it
1513 const glslang::TTypeList* glslangStruct = type.getStruct();
1514 std::vector<spv::Id> structFields;
1515 spvType = structMap[glslangStruct];
1516 if (spvType)
1517 break;
1518
1519 // else, we haven't seen it...
1520
1521 // Create a vector of struct types for SPIR-V to consume
1522 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1523 if (type.getBasicType() == glslang::EbtBlock)
1524 memberRemapper[glslangStruct].resize(glslangStruct->size());
1525 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1526 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1527 if (glslangType.hiddenMember()) {
1528 ++memberDelta;
1529 if (type.getBasicType() == glslang::EbtBlock)
1530 memberRemapper[glslangStruct][i] = -1;
1531 } else {
1532 if (type.getBasicType() == glslang::EbtBlock)
1533 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001534 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001535 }
1536 }
1537
1538 // Make the SPIR-V type
1539 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1540 structMap[glslangStruct] = spvType;
1541
1542 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001543 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001544 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1545 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1546 int member = i;
1547 if (type.getBasicType() == glslang::EbtBlock)
1548 member = memberRemapper[glslangStruct][i];
1549 // using -1 above to indicate a hidden member
1550 if (member >= 0) {
1551 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1552 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1553 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1554 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1555 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1556 if (glslangType.getQualifier().hasLocation())
1557 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1558 if (glslangType.getQualifier().hasComponent())
1559 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1560 if (glslangType.getQualifier().hasXfbOffset())
1561 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001562 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001563 // figure out what to do with offset, which is accumulating
1564 int nextOffset;
1565 updateMemberOffset(type, glslangType, offset, nextOffset);
1566 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001567 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001568 offset = nextOffset;
1569 }
John Kessenich140f3df2015-06-26 16:58:36 -06001570
John Kessenich31ed4832015-09-09 17:51:38 -06001571 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001572 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1573 }
1574
John Kessenich140f3df2015-06-26 16:58:36 -06001575 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001576 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1577 if (builtIn != spv::BadValue)
1578 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001579 }
1580 }
1581
1582 // Decorate the structure
1583 addDecoration(spvType, TranslateLayoutDecoration(type));
1584 addDecoration(spvType, TranslateBlockDecoration(type));
1585 if (type.getQualifier().hasStream())
1586 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1587 if (glslangIntermediate->getXfbMode()) {
1588 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001589 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001590 if (type.getQualifier().hasXfbBuffer())
1591 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1592 }
1593 }
1594 break;
1595 default:
1596 spv::MissingFunctionality("basic type");
1597 break;
1598 }
1599
1600 if (type.isMatrix())
1601 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1602 else {
1603 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1604 if (type.getVectorSize() > 1)
1605 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1606 }
1607
1608 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001609 // Do all but the outer dimension
1610 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1611 assert(type.getArraySizes()->getDimSize(dim) > 0);
1612 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1613 }
John Kessenich31ed4832015-09-09 17:51:38 -06001614
John Kessenichc9a80832015-09-12 12:17:44 -06001615 // Do the outer dimension, which might not be known for a runtime-sized array
1616 if (type.isRuntimeSizedArray()) {
1617 spvType = builder.makeRuntimeArray(spvType);
1618 } else {
1619 assert(type.getOuterArraySize() > 0);
1620 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1621 }
1622
1623 // TODO: layout still needs to be done hierarchically for arrays of arrays, which
1624 // may still require additional "link time" support from the front-end
1625 // for arrays of arrays
John Kessenich31ed4832015-09-09 17:51:38 -06001626 if (explicitLayout)
1627 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001628 }
1629
1630 return spvType;
1631}
1632
John Kessenich31ed4832015-09-09 17:51:38 -06001633bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1634{
1635 return type.getBasicType() == glslang::EbtBlock &&
1636 type.getQualifier().layoutPacking != glslang::ElpShared &&
1637 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1638 (type.getQualifier().storage == glslang::EvqUniform ||
1639 type.getQualifier().storage == glslang::EvqBuffer);
1640}
1641
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001642// Given an array type, returns the integer stride required for that array
1643int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1644{
1645 glslang::TType derefType(arrayType, 0);
1646 int size;
1647 glslangIntermediate->getBaseAlignment(derefType, size, true);
1648 return size;
1649}
1650
1651// Given a matrix type, returns the integer stride required for that matrix
1652// when used as a member of an interface block
1653int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1654{
1655 int size;
1656 return glslangIntermediate->getBaseAlignment(matrixType, size, true);
1657}
1658
John Kessenich5e4b1242015-08-06 22:53:06 -06001659// Given a member type of a struct, realign the current offset for it, and compute
1660// the next (not yet aligned) offset for the next member, which will get aligned
1661// on the next call.
1662// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1663// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1664// -1 means a non-forced member offset (no decoration needed).
1665void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1666{
1667 // this will get a positive value when deemed necessary
1668 nextOffset = -1;
1669
1670 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1671 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1672
1673 // override anything in currentOffset with user-set offset
1674 if (memberType.getQualifier().hasOffset())
1675 currentOffset = memberType.getQualifier().layoutOffset;
1676
1677 // It could be that current linker usage in glslang updated all the layoutOffset,
1678 // in which case the following code does not matter. But, that's not quite right
1679 // once cross-compilation unit GLSL validation is done, as the original user
1680 // settings are needed in layoutOffset, and then the following will come into play.
1681
1682 if (! forceOffset) {
1683 if (! memberType.getQualifier().hasOffset())
1684 currentOffset = -1;
1685
1686 return;
1687 }
1688
1689 // Getting this far means we are forcing offsets
1690 if (currentOffset < 0)
1691 currentOffset = 0;
1692
1693 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1694 // but possibly not yet correctly aligned.
1695
1696 int memberSize;
1697 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1698 glslang::RoundToPow2(currentOffset, memberAlignment);
1699 nextOffset = currentOffset + memberSize;
1700}
1701
John Kessenich140f3df2015-06-26 16:58:36 -06001702bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1703{
1704 return node->getName() == "main(";
1705}
1706
1707// Make all the functions, skeletally, without actually visiting their bodies.
1708void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1709{
1710 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1711 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1712 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1713 continue;
1714
1715 // We're on a user function. Set up the basic interface for the function now,
1716 // so that it's available to call.
1717 // Translating the body will happen later.
1718 //
1719 // Typically (except for a "const in" parameter), an address will be passed to the
1720 // function. What it is an address of varies:
1721 //
1722 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1723 // so that write needs to be to a copy, hence the address of a copy works.
1724 //
1725 // - "const in" parameters can just be the r-value, as no writes need occur.
1726 //
1727 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1728 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1729
1730 std::vector<spv::Id> paramTypes;
1731 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1732
1733 for (int p = 0; p < (int)parameters.size(); ++p) {
1734 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1735 spv::Id typeId = convertGlslangToSpvType(paramType);
1736 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1737 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1738 else
1739 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1740 paramTypes.push_back(typeId);
1741 }
1742
1743 spv::Block* functionBlock;
1744 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1745 paramTypes, &functionBlock);
1746
1747 // Track function to emit/call later
1748 functionMap[glslFunction->getName().c_str()] = function;
1749
1750 // Set the parameter id's
1751 for (int p = 0; p < (int)parameters.size(); ++p) {
1752 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1753 // give a name too
1754 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1755 }
1756 }
1757}
1758
1759// Process all the initializers, while skipping the functions and link objects
1760void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1761{
1762 builder.setBuildPoint(shaderEntry->getLastBlock());
1763 for (int i = 0; i < (int)initializers.size(); ++i) {
1764 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1765 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1766
1767 // We're on a top-level node that's not a function. Treat as an initializer, whose
1768 // code goes into the beginning of main.
1769 initializer->traverse(this);
1770 }
1771 }
1772}
1773
1774// Process all the functions, while skipping initializers.
1775void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1776{
1777 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1778 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1779 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1780 node->traverse(this);
1781 }
1782}
1783
1784void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1785{
1786 // SPIR-V functions should already be in the functionMap from the prepass
1787 // that called makeFunctions().
1788 spv::Function* function = functionMap[node->getName().c_str()];
1789 spv::Block* functionBlock = function->getEntryBlock();
1790 builder.setBuildPoint(functionBlock);
1791}
1792
Rex Xu04db3f52015-09-16 11:44:02 +08001793void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001794{
Rex Xufc618912015-09-09 16:42:49 +08001795 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001796 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1797 builder.clearAccessChain();
1798 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001799
1800 // Special case l-value operands
1801 bool lvalue = false;
1802 switch (node.getOp()) {
1803 case glslang::EOpImageAtomicAdd:
1804 case glslang::EOpImageAtomicMin:
1805 case glslang::EOpImageAtomicMax:
1806 case glslang::EOpImageAtomicAnd:
1807 case glslang::EOpImageAtomicOr:
1808 case glslang::EOpImageAtomicXor:
1809 case glslang::EOpImageAtomicExchange:
1810 case glslang::EOpImageAtomicCompSwap:
1811 if (i == 0)
1812 lvalue = true;
1813 break;
1814 default:
1815 break;
1816 }
1817
Rex Xu6b86d492015-09-16 17:48:22 +08001818 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001819 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001820 else
Rex Xu30f92582015-09-14 10:38:56 +08001821 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001822 }
1823}
1824
John Kessenichfc51d282015-08-19 13:34:18 -06001825void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001826{
John Kessenichfc51d282015-08-19 13:34:18 -06001827 builder.clearAccessChain();
1828 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001829 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001830}
John Kessenich140f3df2015-06-26 16:58:36 -06001831
John Kessenichfc51d282015-08-19 13:34:18 -06001832spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1833{
Rex Xufc618912015-09-09 16:42:49 +08001834 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001835 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001836 }
1837
John Kessenichfc51d282015-08-19 13:34:18 -06001838 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001839 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1840 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1841 std::vector<spv::Id> arguments;
1842 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001843 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001844 else
1845 translateArguments(*node->getAsUnaryNode(), arguments);
1846 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1847
1848 spv::Builder::TextureParameters params = { };
1849 params.sampler = arguments[0];
1850
Rex Xu04db3f52015-09-16 11:44:02 +08001851 glslang::TCrackedTextureOp cracked;
1852 node->crackTexture(sampler, cracked);
1853
John Kessenichfc51d282015-08-19 13:34:18 -06001854 // Check for queries
1855 if (cracked.query) {
1856 switch (node->getOp()) {
1857 case glslang::EOpImageQuerySize:
1858 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001859 if (arguments.size() > 1) {
1860 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001861 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001862 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001863 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001864 case glslang::EOpImageQuerySamples:
1865 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001866 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001867 case glslang::EOpTextureQueryLod:
1868 params.coords = arguments[1];
1869 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1870 case glslang::EOpTextureQueryLevels:
1871 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1872 default:
1873 assert(0);
1874 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001875 }
John Kessenich140f3df2015-06-26 16:58:36 -06001876 }
1877
Rex Xufc618912015-09-09 16:42:49 +08001878 // Check for image functions other than queries
1879 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001880 std::vector<spv::Id> operands;
1881 auto opIt = arguments.begin();
1882 operands.push_back(*(opIt++));
1883 operands.push_back(*(opIt++));
1884 if (node->getOp() == glslang::EOpImageStore)
Rex Xu6b86d492015-09-16 17:48:22 +08001885 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001886 // TODO: add 'sample' operand
1887 if (node->getOp() == glslang::EOpImageLoad) {
1888 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1889 } else if (node->getOp() == glslang::EOpImageStore) {
1890 builder.createNoResultOp(spv::OpImageWrite, operands);
1891 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001892 } else {
1893 // Process image atomic operations
1894
1895 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1896 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001897 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001898
Rex Xufc618912015-09-09 16:42:49 +08001899 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001900 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001901
1902 std::vector<spv::Id> operands;
1903 operands.push_back(pointer);
1904 for (; opIt != arguments.end(); ++opIt)
1905 operands.push_back(*opIt);
1906
Rex Xu04db3f52015-09-16 11:44:02 +08001907 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001908 }
1909 }
1910
1911 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001912 if (cracked.gather)
1913 spv::MissingFunctionality("texture gather");
1914
1915 // check for bias argument
1916 bool bias = false;
1917 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1918 int nonBiasArgCount = 2;
1919 if (cracked.offset)
1920 ++nonBiasArgCount;
1921 if (cracked.grad)
1922 nonBiasArgCount += 2;
1923
1924 if ((int)arguments.size() > nonBiasArgCount)
1925 bias = true;
1926 }
1927
1928 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1929
1930 // set the rest of the arguments
1931 params.coords = arguments[1];
1932 int extraArgs = 0;
1933 if (cubeCompare)
1934 params.Dref = arguments[2];
1935 else if (sampler.shadow) {
1936 std::vector<spv::Id> indexes;
1937 int comp;
1938 if (cracked.proj)
1939 comp = 3;
1940 else
1941 comp = builder.getNumComponents(params.coords) - 1;
1942 indexes.push_back(comp);
1943 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1944 }
1945 if (cracked.lod) {
1946 params.lod = arguments[2];
1947 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08001948 } else if (sampler.ms) {
1949 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08001950 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001951 }
1952 if (cracked.grad) {
1953 params.gradX = arguments[2 + extraArgs];
1954 params.gradY = arguments[3 + extraArgs];
1955 extraArgs += 2;
1956 }
1957 //if (gather && compare) {
1958 // params.compare = arguments[2 + extraArgs];
1959 // ++extraArgs;
1960 //}
1961 if (cracked.offset || cracked.offsets) {
1962 params.offset = arguments[2 + extraArgs];
1963 ++extraArgs;
1964 }
1965 if (bias) {
1966 params.bias = arguments[2 + extraArgs];
1967 ++extraArgs;
1968 }
1969
Jason Ekstrand18b9fbd2015-09-05 14:14:48 -07001970 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001971}
1972
1973spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1974{
1975 // Grab the function's pointer from the previously created function
1976 spv::Function* function = functionMap[node->getName().c_str()];
1977 if (! function)
1978 return 0;
1979
1980 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1981 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1982
1983 // See comments in makeFunctions() for details about the semantics for parameter passing.
1984 //
1985 // These imply we need a four step process:
1986 // 1. Evaluate the arguments
1987 // 2. Allocate and make copies of in, out, and inout arguments
1988 // 3. Make the call
1989 // 4. Copy back the results
1990
1991 // 1. Evaluate the arguments
1992 std::vector<spv::Builder::AccessChain> lValues;
1993 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06001994 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06001995 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1996 // build l-value
1997 builder.clearAccessChain();
1998 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001999 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002000 // keep outputs as l-values, evaluate input-only as r-values
2001 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2002 // save l-value
2003 lValues.push_back(builder.getAccessChain());
2004 } else {
2005 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002006 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002007 }
2008 }
2009
2010 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2011 // copy the original into that space.
2012 //
2013 // Also, build up the list of actual arguments to pass in for the call
2014 int lValueCount = 0;
2015 int rValueCount = 0;
2016 std::vector<spv::Id> spvArgs;
2017 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2018 spv::Id arg;
2019 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2020 // need space to hold the copy
2021 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2022 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2023 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2024 // need to copy the input into output space
2025 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002026 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002027 builder.createStore(copy, arg);
2028 }
2029 ++lValueCount;
2030 } else {
2031 arg = rValues[rValueCount];
2032 ++rValueCount;
2033 }
2034 spvArgs.push_back(arg);
2035 }
2036
2037 // 3. Make the call.
2038 spv::Id result = builder.createFunctionCall(function, spvArgs);
2039
2040 // 4. Copy back out an "out" arguments.
2041 lValueCount = 0;
2042 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2043 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2044 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2045 spv::Id copy = builder.createLoad(spvArgs[a]);
2046 builder.setAccessChain(lValues[lValueCount]);
2047 builder.accessChainStore(copy);
2048 }
2049 ++lValueCount;
2050 }
2051 }
2052
2053 return result;
2054}
2055
2056// Translate AST operation to SPV operation, already having SPV-based operands/types.
2057spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2058 spv::Id typeId, spv::Id left, spv::Id right,
2059 glslang::TBasicType typeProxy, bool reduceComparison)
2060{
2061 bool isUnsigned = typeProxy == glslang::EbtUint;
2062 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2063
2064 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002065 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002066 bool comparison = false;
2067
2068 switch (op) {
2069 case glslang::EOpAdd:
2070 case glslang::EOpAddAssign:
2071 if (isFloat)
2072 binOp = spv::OpFAdd;
2073 else
2074 binOp = spv::OpIAdd;
2075 break;
2076 case glslang::EOpSub:
2077 case glslang::EOpSubAssign:
2078 if (isFloat)
2079 binOp = spv::OpFSub;
2080 else
2081 binOp = spv::OpISub;
2082 break;
2083 case glslang::EOpMul:
2084 case glslang::EOpMulAssign:
2085 if (isFloat)
2086 binOp = spv::OpFMul;
2087 else
2088 binOp = spv::OpIMul;
2089 break;
2090 case glslang::EOpVectorTimesScalar:
2091 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002092 if (isFloat) {
2093 if (builder.isVector(right))
2094 std::swap(left, right);
2095 assert(builder.isScalar(right));
2096 needMatchingVectors = false;
2097 binOp = spv::OpVectorTimesScalar;
2098 } else
2099 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002100 break;
2101 case glslang::EOpVectorTimesMatrix:
2102 case glslang::EOpVectorTimesMatrixAssign:
2103 assert(builder.isVector(left));
2104 assert(builder.isMatrix(right));
2105 binOp = spv::OpVectorTimesMatrix;
2106 break;
2107 case glslang::EOpMatrixTimesVector:
2108 assert(builder.isMatrix(left));
2109 assert(builder.isVector(right));
2110 binOp = spv::OpMatrixTimesVector;
2111 break;
2112 case glslang::EOpMatrixTimesScalar:
2113 case glslang::EOpMatrixTimesScalarAssign:
2114 if (builder.isMatrix(right))
2115 std::swap(left, right);
2116 assert(builder.isScalar(right));
2117 binOp = spv::OpMatrixTimesScalar;
2118 break;
2119 case glslang::EOpMatrixTimesMatrix:
2120 case glslang::EOpMatrixTimesMatrixAssign:
2121 assert(builder.isMatrix(left));
2122 assert(builder.isMatrix(right));
2123 binOp = spv::OpMatrixTimesMatrix;
2124 break;
2125 case glslang::EOpOuterProduct:
2126 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002127 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002128 break;
2129
2130 case glslang::EOpDiv:
2131 case glslang::EOpDivAssign:
2132 if (isFloat)
2133 binOp = spv::OpFDiv;
2134 else if (isUnsigned)
2135 binOp = spv::OpUDiv;
2136 else
2137 binOp = spv::OpSDiv;
2138 break;
2139 case glslang::EOpMod:
2140 case glslang::EOpModAssign:
2141 if (isFloat)
2142 binOp = spv::OpFMod;
2143 else if (isUnsigned)
2144 binOp = spv::OpUMod;
2145 else
2146 binOp = spv::OpSMod;
2147 break;
2148 case glslang::EOpRightShift:
2149 case glslang::EOpRightShiftAssign:
2150 if (isUnsigned)
2151 binOp = spv::OpShiftRightLogical;
2152 else
2153 binOp = spv::OpShiftRightArithmetic;
2154 break;
2155 case glslang::EOpLeftShift:
2156 case glslang::EOpLeftShiftAssign:
2157 binOp = spv::OpShiftLeftLogical;
2158 break;
2159 case glslang::EOpAnd:
2160 case glslang::EOpAndAssign:
2161 binOp = spv::OpBitwiseAnd;
2162 break;
2163 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002164 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002165 binOp = spv::OpLogicalAnd;
2166 break;
2167 case glslang::EOpInclusiveOr:
2168 case glslang::EOpInclusiveOrAssign:
2169 binOp = spv::OpBitwiseOr;
2170 break;
2171 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002172 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002173 binOp = spv::OpLogicalOr;
2174 break;
2175 case glslang::EOpExclusiveOr:
2176 case glslang::EOpExclusiveOrAssign:
2177 binOp = spv::OpBitwiseXor;
2178 break;
2179 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002180 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002181 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002182 break;
2183
2184 case glslang::EOpLessThan:
2185 case glslang::EOpGreaterThan:
2186 case glslang::EOpLessThanEqual:
2187 case glslang::EOpGreaterThanEqual:
2188 case glslang::EOpEqual:
2189 case glslang::EOpNotEqual:
2190 case glslang::EOpVectorEqual:
2191 case glslang::EOpVectorNotEqual:
2192 comparison = true;
2193 break;
2194 default:
2195 break;
2196 }
2197
John Kessenich7c1aa102015-10-15 13:29:11 -06002198 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002199 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002200 assert(comparison == false);
John Kessenich140f3df2015-06-26 16:58:36 -06002201 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2202 switch (binOp) {
2203 case spv::OpMatrixTimesScalar:
2204 case spv::OpVectorTimesMatrix:
2205 case spv::OpMatrixTimesVector:
2206 case spv::OpMatrixTimesMatrix:
2207 break;
2208 case spv::OpFDiv:
2209 // turn it into a multiply...
2210 assert(builder.isMatrix(left) && builder.isScalar(right));
2211 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2212 binOp = spv::OpFMul;
2213 break;
2214 default:
2215 spv::MissingFunctionality("binary operation on matrix");
2216 break;
2217 }
2218
2219 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2220 builder.setPrecision(id, precision);
2221
2222 return id;
2223 }
2224
2225 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002226 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002227 builder.promoteScalar(precision, left, right);
2228
2229 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2230 builder.setPrecision(id, precision);
2231
2232 return id;
2233 }
2234
2235 if (! comparison)
2236 return 0;
2237
John Kessenich7c1aa102015-10-15 13:29:11 -06002238 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002239
2240 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2241 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2242
2243 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2244 }
2245
2246 switch (op) {
2247 case glslang::EOpLessThan:
2248 if (isFloat)
2249 binOp = spv::OpFOrdLessThan;
2250 else if (isUnsigned)
2251 binOp = spv::OpULessThan;
2252 else
2253 binOp = spv::OpSLessThan;
2254 break;
2255 case glslang::EOpGreaterThan:
2256 if (isFloat)
2257 binOp = spv::OpFOrdGreaterThan;
2258 else if (isUnsigned)
2259 binOp = spv::OpUGreaterThan;
2260 else
2261 binOp = spv::OpSGreaterThan;
2262 break;
2263 case glslang::EOpLessThanEqual:
2264 if (isFloat)
2265 binOp = spv::OpFOrdLessThanEqual;
2266 else if (isUnsigned)
2267 binOp = spv::OpULessThanEqual;
2268 else
2269 binOp = spv::OpSLessThanEqual;
2270 break;
2271 case glslang::EOpGreaterThanEqual:
2272 if (isFloat)
2273 binOp = spv::OpFOrdGreaterThanEqual;
2274 else if (isUnsigned)
2275 binOp = spv::OpUGreaterThanEqual;
2276 else
2277 binOp = spv::OpSGreaterThanEqual;
2278 break;
2279 case glslang::EOpEqual:
2280 case glslang::EOpVectorEqual:
2281 if (isFloat)
2282 binOp = spv::OpFOrdEqual;
2283 else
2284 binOp = spv::OpIEqual;
2285 break;
2286 case glslang::EOpNotEqual:
2287 case glslang::EOpVectorNotEqual:
2288 if (isFloat)
2289 binOp = spv::OpFOrdNotEqual;
2290 else
2291 binOp = spv::OpINotEqual;
2292 break;
2293 default:
2294 break;
2295 }
2296
2297 if (binOp != spv::OpNop) {
2298 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2299 builder.setPrecision(id, precision);
2300
2301 return id;
2302 }
2303
2304 return 0;
2305}
2306
Rex Xu04db3f52015-09-16 11:44:02 +08002307spv::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 -06002308{
2309 spv::Op unaryOp = spv::OpNop;
2310 int libCall = -1;
Rex Xu04db3f52015-09-16 11:44:02 +08002311 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002312
2313 switch (op) {
2314 case glslang::EOpNegative:
2315 if (isFloat)
2316 unaryOp = spv::OpFNegate;
2317 else
2318 unaryOp = spv::OpSNegate;
2319 break;
2320
2321 case glslang::EOpLogicalNot:
2322 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002323 unaryOp = spv::OpLogicalNot;
2324 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002325 case glslang::EOpBitwiseNot:
2326 unaryOp = spv::OpNot;
2327 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002328
John Kessenich140f3df2015-06-26 16:58:36 -06002329 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002330 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002331 break;
2332 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002333 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002334 break;
2335 case glslang::EOpTranspose:
2336 unaryOp = spv::OpTranspose;
2337 break;
2338
2339 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002340 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002341 break;
2342 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002343 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002344 break;
2345 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002346 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002347 break;
2348 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002349 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002350 break;
2351 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002352 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002353 break;
2354 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002355 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002356 break;
2357 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002358 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002359 break;
2360 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002361 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002362 break;
2363
2364 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002365 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002366 break;
2367 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002368 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002369 break;
2370 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002371 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002372 break;
2373 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002374 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002375 break;
2376 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002377 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002378 break;
2379 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002380 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002381 break;
2382
2383 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002384 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002385 break;
2386 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002387 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002388 break;
2389
2390 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002391 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002392 break;
2393 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002394 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002395 break;
2396 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002397 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002398 break;
2399 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002400 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002401 break;
2402 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002403 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002404 break;
2405 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002406 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002407 break;
2408
2409 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002410 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002411 break;
2412 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002413 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002414 break;
2415 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002416 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002417 break;
2418 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002419 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002420 break;
2421 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002422 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002423 break;
2424 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002425 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002426 break;
2427
2428 case glslang::EOpIsNan:
2429 unaryOp = spv::OpIsNan;
2430 break;
2431 case glslang::EOpIsInf:
2432 unaryOp = spv::OpIsInf;
2433 break;
2434
John Kessenich140f3df2015-06-26 16:58:36 -06002435 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002436 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002437 break;
2438 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002439 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002440 break;
2441 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002442 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002443 break;
2444 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002445 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002446 break;
2447 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002448 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002449 break;
2450 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002451 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002452 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002453 case glslang::EOpPackSnorm4x8:
2454 libCall = spv::GLSLstd450PackSnorm4x8;
2455 break;
2456 case glslang::EOpUnpackSnorm4x8:
2457 libCall = spv::GLSLstd450UnpackSnorm4x8;
2458 break;
2459 case glslang::EOpPackUnorm4x8:
2460 libCall = spv::GLSLstd450PackUnorm4x8;
2461 break;
2462 case glslang::EOpUnpackUnorm4x8:
2463 libCall = spv::GLSLstd450UnpackUnorm4x8;
2464 break;
2465 case glslang::EOpPackDouble2x32:
2466 libCall = spv::GLSLstd450PackDouble2x32;
2467 break;
2468 case glslang::EOpUnpackDouble2x32:
2469 libCall = spv::GLSLstd450UnpackDouble2x32;
2470 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002471
2472 case glslang::EOpDPdx:
2473 unaryOp = spv::OpDPdx;
2474 break;
2475 case glslang::EOpDPdy:
2476 unaryOp = spv::OpDPdy;
2477 break;
2478 case glslang::EOpFwidth:
2479 unaryOp = spv::OpFwidth;
2480 break;
2481 case glslang::EOpDPdxFine:
2482 unaryOp = spv::OpDPdxFine;
2483 break;
2484 case glslang::EOpDPdyFine:
2485 unaryOp = spv::OpDPdyFine;
2486 break;
2487 case glslang::EOpFwidthFine:
2488 unaryOp = spv::OpFwidthFine;
2489 break;
2490 case glslang::EOpDPdxCoarse:
2491 unaryOp = spv::OpDPdxCoarse;
2492 break;
2493 case glslang::EOpDPdyCoarse:
2494 unaryOp = spv::OpDPdyCoarse;
2495 break;
2496 case glslang::EOpFwidthCoarse:
2497 unaryOp = spv::OpFwidthCoarse;
2498 break;
2499
2500 case glslang::EOpAny:
2501 unaryOp = spv::OpAny;
2502 break;
2503 case glslang::EOpAll:
2504 unaryOp = spv::OpAll;
2505 break;
2506
2507 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002508 if (isFloat)
2509 libCall = spv::GLSLstd450FAbs;
2510 else
2511 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002512 break;
2513 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002514 if (isFloat)
2515 libCall = spv::GLSLstd450FSign;
2516 else
2517 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002518 break;
2519
John Kessenichfc51d282015-08-19 13:34:18 -06002520 case glslang::EOpAtomicCounterIncrement:
2521 case glslang::EOpAtomicCounterDecrement:
2522 case glslang::EOpAtomicCounter:
2523 {
2524 // Handle all of the atomics in one place, in createAtomicOperation()
2525 std::vector<spv::Id> operands;
2526 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002527 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002528 }
2529
2530 case glslang::EOpImageLoad:
2531 unaryOp = spv::OpImageRead;
2532 break;
2533
2534 case glslang::EOpBitFieldReverse:
2535 unaryOp = spv::OpBitReverse;
2536 break;
2537 case glslang::EOpBitCount:
2538 unaryOp = spv::OpBitCount;
2539 break;
2540 case glslang::EOpFindLSB:
2541 libCall = spv::GLSLstd450FindILSB;
2542 break;
2543 case glslang::EOpFindMSB:
2544 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2545 libCall = spv::GLSLstd450FindSMSB;
2546 break;
2547
John Kessenich140f3df2015-06-26 16:58:36 -06002548 default:
2549 return 0;
2550 }
2551
2552 spv::Id id;
2553 if (libCall >= 0) {
2554 std::vector<spv::Id> args;
2555 args.push_back(operand);
2556 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2557 } else
2558 id = builder.createUnaryOp(unaryOp, typeId, operand);
2559
2560 builder.setPrecision(id, precision);
2561
2562 return id;
2563}
2564
2565spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2566{
2567 spv::Op convOp = spv::OpNop;
2568 spv::Id zero = 0;
2569 spv::Id one = 0;
2570
2571 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2572
2573 switch (op) {
2574 case glslang::EOpConvIntToBool:
2575 case glslang::EOpConvUintToBool:
2576 zero = builder.makeUintConstant(0);
2577 zero = makeSmearedConstant(zero, vectorSize);
2578 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2579
2580 case glslang::EOpConvFloatToBool:
2581 zero = builder.makeFloatConstant(0.0F);
2582 zero = makeSmearedConstant(zero, vectorSize);
2583 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2584
2585 case glslang::EOpConvDoubleToBool:
2586 zero = builder.makeDoubleConstant(0.0);
2587 zero = makeSmearedConstant(zero, vectorSize);
2588 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2589
2590 case glslang::EOpConvBoolToFloat:
2591 convOp = spv::OpSelect;
2592 zero = builder.makeFloatConstant(0.0);
2593 one = builder.makeFloatConstant(1.0);
2594 break;
2595 case glslang::EOpConvBoolToDouble:
2596 convOp = spv::OpSelect;
2597 zero = builder.makeDoubleConstant(0.0);
2598 one = builder.makeDoubleConstant(1.0);
2599 break;
2600 case glslang::EOpConvBoolToInt:
2601 zero = builder.makeIntConstant(0);
2602 one = builder.makeIntConstant(1);
2603 convOp = spv::OpSelect;
2604 break;
2605 case glslang::EOpConvBoolToUint:
2606 zero = builder.makeUintConstant(0);
2607 one = builder.makeUintConstant(1);
2608 convOp = spv::OpSelect;
2609 break;
2610
2611 case glslang::EOpConvIntToFloat:
2612 case glslang::EOpConvIntToDouble:
2613 convOp = spv::OpConvertSToF;
2614 break;
2615
2616 case glslang::EOpConvUintToFloat:
2617 case glslang::EOpConvUintToDouble:
2618 convOp = spv::OpConvertUToF;
2619 break;
2620
2621 case glslang::EOpConvDoubleToFloat:
2622 case glslang::EOpConvFloatToDouble:
2623 convOp = spv::OpFConvert;
2624 break;
2625
2626 case glslang::EOpConvFloatToInt:
2627 case glslang::EOpConvDoubleToInt:
2628 convOp = spv::OpConvertFToS;
2629 break;
2630
2631 case glslang::EOpConvUintToInt:
2632 case glslang::EOpConvIntToUint:
2633 convOp = spv::OpBitcast;
2634 break;
2635
2636 case glslang::EOpConvFloatToUint:
2637 case glslang::EOpConvDoubleToUint:
2638 convOp = spv::OpConvertFToU;
2639 break;
2640 default:
2641 break;
2642 }
2643
2644 spv::Id result = 0;
2645 if (convOp == spv::OpNop)
2646 return result;
2647
2648 if (convOp == spv::OpSelect) {
2649 zero = makeSmearedConstant(zero, vectorSize);
2650 one = makeSmearedConstant(one, vectorSize);
2651 result = builder.createTriOp(convOp, destType, operand, one, zero);
2652 } else
2653 result = builder.createUnaryOp(convOp, destType, operand);
2654
2655 builder.setPrecision(result, precision);
2656
2657 return result;
2658}
2659
2660spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2661{
2662 if (vectorSize == 0)
2663 return constant;
2664
2665 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2666 std::vector<spv::Id> components;
2667 for (int c = 0; c < vectorSize; ++c)
2668 components.push_back(constant);
2669 return builder.makeCompositeConstant(vectorTypeId, components);
2670}
2671
John Kessenich426394d2015-07-23 10:22:48 -06002672// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002673spv::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 -06002674{
2675 spv::Op opCode = spv::OpNop;
2676
2677 switch (op) {
2678 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002679 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002680 opCode = spv::OpAtomicIAdd;
2681 break;
2682 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002683 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002684 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002685 break;
2686 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002687 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002688 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002689 break;
2690 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002691 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002692 opCode = spv::OpAtomicAnd;
2693 break;
2694 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002695 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002696 opCode = spv::OpAtomicOr;
2697 break;
2698 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002699 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002700 opCode = spv::OpAtomicXor;
2701 break;
2702 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002703 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002704 opCode = spv::OpAtomicExchange;
2705 break;
2706 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002707 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002708 opCode = spv::OpAtomicCompareExchange;
2709 break;
2710 case glslang::EOpAtomicCounterIncrement:
2711 opCode = spv::OpAtomicIIncrement;
2712 break;
2713 case glslang::EOpAtomicCounterDecrement:
2714 opCode = spv::OpAtomicIDecrement;
2715 break;
2716 case glslang::EOpAtomicCounter:
2717 opCode = spv::OpAtomicLoad;
2718 break;
2719 default:
2720 spv::MissingFunctionality("missing nested atomic");
2721 break;
2722 }
2723
2724 // Sort out the operands
2725 // - mapping from glslang -> SPV
2726 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002727 // - compare-exchange swaps the value and comparator
2728 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002729 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2730 auto opIt = operands.begin(); // walk the glslang operands
2731 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002732 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2733 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2734 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002735 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2736 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002737 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002738 spvAtomicOperands.push_back(*(opIt + 1));
2739 spvAtomicOperands.push_back(*opIt);
2740 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002741 }
John Kessenich426394d2015-07-23 10:22:48 -06002742
John Kessenich3e60a6f2015-09-14 22:45:16 -06002743 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002744 for (; opIt != operands.end(); ++opIt)
2745 spvAtomicOperands.push_back(*opIt);
2746
2747 return builder.createOp(opCode, typeId, spvAtomicOperands);
2748}
2749
John Kessenich5e4b1242015-08-06 22:53:06 -06002750spv::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 -06002751{
John Kessenich5e4b1242015-08-06 22:53:06 -06002752 bool isUnsigned = typeProxy == glslang::EbtUint;
2753 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2754
John Kessenich140f3df2015-06-26 16:58:36 -06002755 spv::Op opCode = spv::OpNop;
2756 int libCall = -1;
2757
2758 switch (op) {
2759 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002760 if (isFloat)
2761 libCall = spv::GLSLstd450FMin;
2762 else if (isUnsigned)
2763 libCall = spv::GLSLstd450UMin;
2764 else
2765 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002766 break;
2767 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002768 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002769 break;
2770 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002771 if (isFloat)
2772 libCall = spv::GLSLstd450FMax;
2773 else if (isUnsigned)
2774 libCall = spv::GLSLstd450UMax;
2775 else
2776 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002777 break;
2778 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002779 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002780 break;
2781 case glslang::EOpDot:
2782 opCode = spv::OpDot;
2783 break;
2784 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002785 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002786 break;
2787
2788 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002789 if (isFloat)
2790 libCall = spv::GLSLstd450FClamp;
2791 else if (isUnsigned)
2792 libCall = spv::GLSLstd450UClamp;
2793 else
2794 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002795 break;
2796 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002797 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002798 break;
2799 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002800 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002801 break;
2802 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002803 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002804 break;
2805
2806 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002807 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002808 break;
2809 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002810 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002811 break;
2812 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002813 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002814 break;
2815 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002816 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002817 break;
2818 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002819 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002820 break;
John Kessenich426394d2015-07-23 10:22:48 -06002821
John Kessenich140f3df2015-06-26 16:58:36 -06002822 default:
2823 return 0;
2824 }
2825
2826 spv::Id id = 0;
2827 if (libCall >= 0)
2828 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2829 else {
2830 switch (operands.size()) {
2831 case 0:
2832 // should all be handled by visitAggregate and createNoArgOperation
2833 assert(0);
2834 return 0;
2835 case 1:
2836 // should all be handled by createUnaryOperation
2837 assert(0);
2838 return 0;
2839 case 2:
2840 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2841 break;
2842 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002843 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002844 break;
2845 default:
2846 // These do not exist yet
2847 assert(0 && "operation with more than 3 operands");
2848 break;
2849 }
2850 }
2851
2852 builder.setPrecision(id, precision);
2853
2854 return id;
2855}
2856
2857// Intrinsics with no arguments, no return value, and no precision.
2858spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2859{
2860 // TODO: get the barrier operands correct
2861
2862 switch (op) {
2863 case glslang::EOpEmitVertex:
2864 builder.createNoResultOp(spv::OpEmitVertex);
2865 return 0;
2866 case glslang::EOpEndPrimitive:
2867 builder.createNoResultOp(spv::OpEndPrimitive);
2868 return 0;
2869 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002870 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2871 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002872 return 0;
2873 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002874 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002875 return 0;
2876 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002877 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002878 return 0;
2879 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002880 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002881 return 0;
2882 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002883 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002884 return 0;
2885 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002886 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002887 return 0;
2888 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002889 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002890 return 0;
2891 default:
2892 spv::MissingFunctionality("operation with no arguments");
2893 return 0;
2894 }
2895}
2896
2897spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2898{
John Kessenich2f273362015-07-18 22:34:27 -06002899 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002900 spv::Id id;
2901 if (symbolValues.end() != iter) {
2902 id = iter->second;
2903 return id;
2904 }
2905
2906 // it was not found, create it
2907 id = createSpvVariable(symbol);
2908 symbolValues[symbol->getId()] = id;
2909
2910 if (! symbol->getType().isStruct()) {
2911 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2912 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2913 if (symbol->getQualifier().hasLocation())
2914 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2915 if (symbol->getQualifier().hasIndex())
2916 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2917 if (symbol->getQualifier().hasComponent())
2918 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2919 if (glslangIntermediate->getXfbMode()) {
2920 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002921 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002922 if (symbol->getQualifier().hasXfbBuffer())
2923 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2924 if (symbol->getQualifier().hasXfbOffset())
2925 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2926 }
2927 }
2928
2929 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2930 if (symbol->getQualifier().hasStream())
2931 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2932 if (symbol->getQualifier().hasSet())
2933 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2934 if (symbol->getQualifier().hasBinding())
2935 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2936 if (glslangIntermediate->getXfbMode()) {
2937 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002938 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002939 if (symbol->getQualifier().hasXfbBuffer())
2940 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2941 }
2942
2943 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002944 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002945 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002946 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002947
2948 if (linkageOnly)
2949 builder.addDecoration(id, spv::DecorationNoStaticUse);
2950
2951 return id;
2952}
2953
2954void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2955{
2956 if (dec != spv::BadValue)
2957 builder.addDecoration(id, dec);
2958}
2959
2960void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2961{
2962 if (dec != spv::BadValue)
2963 builder.addMemberDecoration(id, (unsigned)member, dec);
2964}
2965
2966// Use 'consts' as the flattened glslang source of scalar constants to recursively
2967// build the aggregate SPIR-V constant.
2968//
2969// If there are not enough elements present in 'consts', 0 will be substituted;
2970// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2971//
2972spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2973{
2974 // vector of constants for SPIR-V
2975 std::vector<spv::Id> spvConsts;
2976
2977 // Type is used for struct and array constants
2978 spv::Id typeId = convertGlslangToSpvType(glslangType);
2979
2980 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002981 glslang::TType elementType(glslangType, 0);
2982 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002983 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2984 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002985 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002986 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2987 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2988 } else if (glslangType.getStruct()) {
2989 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2990 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2991 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2992 } else if (glslangType.isVector()) {
2993 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2994 bool zero = nextConst >= consts.size();
2995 switch (glslangType.getBasicType()) {
2996 case glslang::EbtInt:
2997 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2998 break;
2999 case glslang::EbtUint:
3000 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3001 break;
3002 case glslang::EbtFloat:
3003 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3004 break;
3005 case glslang::EbtDouble:
3006 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3007 break;
3008 case glslang::EbtBool:
3009 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3010 break;
3011 default:
3012 spv::MissingFunctionality("constant vector type");
3013 break;
3014 }
3015 ++nextConst;
3016 }
3017 } else {
3018 // we have a non-aggregate (scalar) constant
3019 bool zero = nextConst >= consts.size();
3020 spv::Id scalar = 0;
3021 switch (glslangType.getBasicType()) {
3022 case glslang::EbtInt:
3023 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
3024 break;
3025 case glslang::EbtUint:
3026 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
3027 break;
3028 case glslang::EbtFloat:
3029 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
3030 break;
3031 case glslang::EbtDouble:
3032 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
3033 break;
3034 case glslang::EbtBool:
3035 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
3036 break;
3037 default:
3038 spv::MissingFunctionality("constant scalar type");
3039 break;
3040 }
3041 ++nextConst;
3042 return scalar;
3043 }
3044
3045 return builder.makeCompositeConstant(typeId, spvConsts);
3046}
3047
John Kessenich7c1aa102015-10-15 13:29:11 -06003048// Return true if the node is a constant or symbol whose reading has no
3049// non-trivial observable cost or effect.
3050bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3051{
3052 // don't know what this is
3053 if (node == nullptr)
3054 return false;
3055
3056 // a constant is safe
3057 if (node->getAsConstantUnion() != nullptr)
3058 return true;
3059
3060 // not a symbol means non-trivial
3061 if (node->getAsSymbolNode() == nullptr)
3062 return false;
3063
3064 // a symbol, depends on what's being read
3065 switch (node->getType().getQualifier().storage) {
3066 case glslang::EvqTemporary:
3067 case glslang::EvqGlobal:
3068 case glslang::EvqIn:
3069 case glslang::EvqInOut:
3070 case glslang::EvqConst:
3071 case glslang::EvqConstReadOnly:
3072 case glslang::EvqUniform:
3073 return true;
3074 default:
3075 return false;
3076 }
3077}
3078
3079// A node is trivial if it is a single operation with no side effects.
3080// Error on the side of saying non-trivial.
3081// Return true if trivial.
3082bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3083{
3084 if (node == nullptr)
3085 return false;
3086
3087 // symbols and constants are trivial
3088 if (isTrivialLeaf(node))
3089 return true;
3090
3091 // otherwise, it needs to be a simple operation or one or two leaf nodes
3092
3093 // not a simple operation
3094 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3095 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3096 if (binaryNode == nullptr && unaryNode == nullptr)
3097 return false;
3098
3099 // not on leaf nodes
3100 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3101 return false;
3102
3103 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3104 return false;
3105 }
3106
3107 switch (node->getAsOperator()->getOp()) {
3108 case glslang::EOpLogicalNot:
3109 case glslang::EOpConvIntToBool:
3110 case glslang::EOpConvUintToBool:
3111 case glslang::EOpConvFloatToBool:
3112 case glslang::EOpConvDoubleToBool:
3113 case glslang::EOpEqual:
3114 case glslang::EOpNotEqual:
3115 case glslang::EOpLessThan:
3116 case glslang::EOpGreaterThan:
3117 case glslang::EOpLessThanEqual:
3118 case glslang::EOpGreaterThanEqual:
3119 case glslang::EOpIndexDirect:
3120 case glslang::EOpIndexDirectStruct:
3121 case glslang::EOpLogicalXor:
3122 case glslang::EOpAny:
3123 case glslang::EOpAll:
3124 return true;
3125 default:
3126 return false;
3127 }
3128}
3129
3130// Emit short-circuiting code, where 'right' is never evaluated unless
3131// the left side is true (for &&) or false (for ||).
3132spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3133{
3134 spv::Id boolTypeId = builder.makeBoolType();
3135
3136 // emit left operand
3137 builder.clearAccessChain();
3138 left.traverse(this);
3139 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3140
3141 // Operands to accumulate OpPhi operands
3142 std::vector<spv::Id> phiOperands;
3143 // accumulate left operand's phi information
3144 phiOperands.push_back(leftId);
3145 phiOperands.push_back(builder.getBuildPoint()->getId());
3146
3147 // Make the two kinds of operation symmetric with a "!"
3148 // || => emit "if (! left) result = right"
3149 // && => emit "if ( left) result = right"
3150 //
3151 // TODO: this runtime "not" for || could be avoided by adding functionality
3152 // to 'builder' to have an "else" without an "then"
3153 if (op == glslang::EOpLogicalOr)
3154 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3155
3156 // make an "if" based on the left value
3157 spv::Builder::If ifBuilder(leftId, builder);
3158
3159 // emit right operand as the "then" part of the "if"
3160 builder.clearAccessChain();
3161 right.traverse(this);
3162 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3163
3164 // accumulate left operand's phi information
3165 phiOperands.push_back(rightId);
3166 phiOperands.push_back(builder.getBuildPoint()->getId());
3167
3168 // finish the "if"
3169 ifBuilder.makeEndIf();
3170
3171 // phi together the two results
3172 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3173}
3174
John Kessenich140f3df2015-06-26 16:58:36 -06003175}; // end anonymous namespace
3176
3177namespace glslang {
3178
John Kessenich68d78fd2015-07-12 19:28:10 -06003179void GetSpirvVersion(std::string& version)
3180{
John Kessenich9e55f632015-07-15 10:03:39 -06003181 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003182 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06003183 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003184 version = buf;
3185}
3186
John Kessenich140f3df2015-06-26 16:58:36 -06003187// Write SPIR-V out to a binary file
3188void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3189{
3190 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003191 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003192 for (int i = 0; i < (int)spirv.size(); ++i) {
3193 unsigned int word = spirv[i];
3194 out.write((const char*)&word, 4);
3195 }
3196 out.close();
3197}
3198
3199//
3200// Set up the glslang traversal
3201//
3202void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3203{
3204 TIntermNode* root = intermediate.getTreeRoot();
3205
3206 if (root == 0)
3207 return;
3208
3209 glslang::GetThreadPoolAllocator().push();
3210
3211 TGlslangToSpvTraverser it(&intermediate);
3212
3213 root->traverse(&it);
3214
3215 it.dumpSpv(spirv);
3216
3217 glslang::GetThreadPoolAllocator().pop();
3218}
3219
3220}; // end namespace glslang