blob: 844efb56f448c04b66059e9fc1df9e6bd4ee2c7f [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);
Jason Ekstrand54aedf12015-09-05 09:50:58 -070091 int getArrayStride(const glslang::TType& arrayType);
92 int getMatrixStride(const glslang::TType& matrixType);
John Kessenich5e4b1242015-08-06 22:53:06 -060093 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060094
95 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
96 void makeFunctions(const glslang::TIntermSequence&);
97 void makeGlobalInitializers(const glslang::TIntermSequence&);
98 void visitFunctions(const glslang::TIntermSequence&);
99 void handleFunctionEntry(const glslang::TIntermAggregate* node);
100 void translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600101 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
102 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600103 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
104
105 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
106 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat);
107 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
108 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich426394d2015-07-23 10:22:48 -0600109 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600110 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 -0600111 spv::Id createNoArgOperation(glslang::TOperator op);
112 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
113 void addDecoration(spv::Id id, spv::Decoration dec);
114 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
115 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
116
117 spv::Function* shaderEntry;
118 int sequenceDepth;
119
120 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
121 spv::Builder builder;
122 bool inMain;
123 bool mainTerminated;
124 bool linkageOnly;
125 const glslang::TIntermediate* glslangIntermediate;
126 spv::Id stdBuiltins;
127
John Kessenich2f273362015-07-18 22:34:27 -0600128 std::unordered_map<int, spv::Id> symbolValues;
129 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
130 std::unordered_map<std::string, spv::Function*> functionMap;
131 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
132 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 -0600133 std::stack<bool> breakForLoop; // false means break for switch
134 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
135};
136
137//
138// Helper functions for translating glslang representations to SPIR-V enumerants.
139//
140
141// Translate glslang profile to SPIR-V source language.
142spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
143{
144 switch (profile) {
145 case ENoProfile:
146 case ECoreProfile:
147 case ECompatibilityProfile:
148 return spv::SourceLanguageGLSL;
149 case EEsProfile:
150 return spv::SourceLanguageESSL;
151 default:
152 return spv::SourceLanguageUnknown;
153 }
154}
155
156// Translate glslang language (stage) to SPIR-V execution model.
157spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
158{
159 switch (stage) {
160 case EShLangVertex: return spv::ExecutionModelVertex;
161 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
162 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
163 case EShLangGeometry: return spv::ExecutionModelGeometry;
164 case EShLangFragment: return spv::ExecutionModelFragment;
165 case EShLangCompute: return spv::ExecutionModelGLCompute;
166 default:
167 spv::MissingFunctionality("GLSL stage");
168 return spv::ExecutionModelFragment;
169 }
170}
171
172// Translate glslang type to SPIR-V storage class.
173spv::StorageClass TranslateStorageClass(const glslang::TType& type)
174{
175 if (type.getQualifier().isPipeInput())
176 return spv::StorageClassInput;
177 else if (type.getQualifier().isPipeOutput())
178 return spv::StorageClassOutput;
179 else if (type.getQualifier().isUniformOrBuffer()) {
180 if (type.getBasicType() == glslang::EbtBlock)
181 return spv::StorageClassUniform;
182 else
183 return spv::StorageClassUniformConstant;
184 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
185 } else {
186 switch (type.getQualifier().storage) {
187 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
188 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
189 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
190 case glslang::EvqTemporary: return spv::StorageClassFunction;
191 default:
192 spv::MissingFunctionality("unknown glslang storage class");
193 return spv::StorageClassFunction;
194 }
195 }
196}
197
198// Translate glslang sampler type to SPIR-V dimensionality.
199spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
200{
201 switch (sampler.dim) {
202 case glslang::Esd1D: return spv::Dim1D;
203 case glslang::Esd2D: return spv::Dim2D;
204 case glslang::Esd3D: return spv::Dim3D;
205 case glslang::EsdCube: return spv::DimCube;
206 case glslang::EsdRect: return spv::DimRect;
207 case glslang::EsdBuffer: return spv::DimBuffer;
208 default:
209 spv::MissingFunctionality("unknown sampler dimension");
210 return spv::Dim2D;
211 }
212}
213
214// Translate glslang type to SPIR-V precision decorations.
215spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
216{
217 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600218 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
219 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
220 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600221 default:
222 return spv::NoPrecision;
223 }
224}
225
226// Translate glslang type to SPIR-V block decorations.
227spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
228{
229 if (type.getBasicType() == glslang::EbtBlock) {
230 switch (type.getQualifier().storage) {
231 case glslang::EvqUniform: return spv::DecorationBlock;
232 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
233 case glslang::EvqVaryingIn: return spv::DecorationBlock;
234 case glslang::EvqVaryingOut: return spv::DecorationBlock;
235 default:
236 spv::MissingFunctionality("kind of block");
237 break;
238 }
239 }
240
241 return (spv::Decoration)spv::BadValue;
242}
243
244// Translate glslang type to SPIR-V layout decorations.
245spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
246{
247 if (type.isMatrix()) {
248 switch (type.getQualifier().layoutMatrix) {
249 case glslang::ElmRowMajor:
250 return spv::DecorationRowMajor;
251 default:
252 return spv::DecorationColMajor;
253 }
254 } else {
255 switch (type.getBasicType()) {
256 default:
257 return (spv::Decoration)spv::BadValue;
258 break;
259 case glslang::EbtBlock:
260 switch (type.getQualifier().storage) {
261 case glslang::EvqUniform:
262 case glslang::EvqBuffer:
263 switch (type.getQualifier().layoutPacking) {
264 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600265 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
266 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600267 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600268 }
269 case glslang::EvqVaryingIn:
270 case glslang::EvqVaryingOut:
271 if (type.getQualifier().layoutPacking != glslang::ElpNone)
272 spv::MissingFunctionality("in/out block layout");
273 return (spv::Decoration)spv::BadValue;
274 default:
275 spv::MissingFunctionality("block storage qualification");
276 return (spv::Decoration)spv::BadValue;
277 }
278 }
279 }
280}
281
282// Translate glslang type to SPIR-V interpolation decorations.
283spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
284{
285 if (type.getQualifier().smooth)
286 return spv::DecorationSmooth;
287 if (type.getQualifier().nopersp)
288 return spv::DecorationNoperspective;
289 else if (type.getQualifier().patch)
290 return spv::DecorationPatch;
291 else if (type.getQualifier().flat)
292 return spv::DecorationFlat;
293 else if (type.getQualifier().centroid)
294 return spv::DecorationCentroid;
295 else if (type.getQualifier().sample)
296 return spv::DecorationSample;
297 else
298 return (spv::Decoration)spv::BadValue;
299}
300
301// If glslang type is invaraiant, return SPIR-V invariant decoration.
302spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
303{
304 if (type.getQualifier().invariant)
305 return spv::DecorationInvariant;
306 else
307 return (spv::Decoration)spv::BadValue;
308}
309
310// Translate glslang built-in variable to SPIR-V built in decoration.
311spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
312{
313 switch (builtIn) {
314 case glslang::EbvPosition: return spv::BuiltInPosition;
315 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600316 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
317 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
318 case glslang::EbvVertexId: return spv::BuiltInVertexId;
319 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
320 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
321 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
322 case glslang::EbvLayer: return spv::BuiltInLayer;
323 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
324 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
325 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
326 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
327 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
328 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
329 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
330 case glslang::EbvFace: return spv::BuiltInFrontFacing;
331 case glslang::EbvSampleId: return spv::BuiltInSampleId;
332 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
333 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
334 case glslang::EbvFragColor: return spv::BuiltInFragColor;
335 case glslang::EbvFragData: return spv::BuiltInFragColor;
336 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
337 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
338 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
339 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
340 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
341 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
342 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
343 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
344 default: return (spv::BuiltIn)spv::BadValue;
345 }
346}
347
348//
349// Implement the TGlslangToSpvTraverser class.
350//
351
352TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
353 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
354 builder(GlslangMagic),
355 inMain(false), mainTerminated(false), linkageOnly(false),
356 glslangIntermediate(glslangIntermediate)
357{
358 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
359
360 builder.clearAccessChain();
361 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
362 stdBuiltins = builder.import("GLSL.std.450");
363 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
364 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600365 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600366
367 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600368 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
369 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600370 builder.addSourceExtension(it->c_str());
371
372 // Add the top-level modes for this shader.
373
374 if (glslangIntermediate->getXfbMode())
375 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
376
377 unsigned int mode;
378 switch (glslangIntermediate->getStage()) {
379 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600380 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600381 break;
382
383 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600384 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600385 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
386 break;
387
388 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600389 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600390 switch (glslangIntermediate->getInputPrimitive()) {
391 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
392 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
393 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
394 default: mode = spv::BadValue; break;
395 }
396 if (mode != spv::BadValue)
397 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
398
399 // TODO
400 //builder.addExecutionMode(spv::VertexSpacingMdName, glslangIntermediate->getVertexSpacing());
401 //builder.addExecutionMode(spv::VertexOrderMdName, glslangIntermediate->getVertexOrder());
402 //builder.addExecutionMode(spv::PointModeMdName, glslangIntermediate->getPointMode());
403 break;
404
405 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600406 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600407 switch (glslangIntermediate->getInputPrimitive()) {
408 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
409 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
410 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
411 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
412 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
413 default: mode = spv::BadValue; break;
414 }
415 if (mode != spv::BadValue)
416 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
417 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
418
419 switch (glslangIntermediate->getOutputPrimitive()) {
420 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
421 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
422 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
423 default: mode = spv::BadValue; break;
424 }
425 if (mode != spv::BadValue)
426 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
427 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
428 break;
429
430 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600431 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600432 if (glslangIntermediate->getPixelCenterInteger())
433 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
434 if (glslangIntermediate->getOriginUpperLeft())
435 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600436 else
437 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kessenich140f3df2015-06-26 16:58:36 -0600438 break;
439
440 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600441 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600442 break;
443
444 default:
445 break;
446 }
447
448}
449
450TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
451{
452 if (! mainTerminated) {
453 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
454 builder.setBuildPoint(lastMainBlock);
455 builder.leaveFunction(true);
456 }
457}
458
459//
460// Implement the traversal functions.
461//
462// Return true from interior nodes to have the external traversal
463// continue on to children. Return false if children were
464// already processed.
465//
466
467//
468// Symbols can turn into
469// - uniform/input reads
470// - output writes
471// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
472// - something simple that degenerates into the last bullet
473//
474void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
475{
476 // getSymbolId() will set up all the IO decorations on the first call.
477 // Formal function parameters were mapped during makeFunctions().
478 spv::Id id = getSymbolId(symbol);
479
480 if (! linkageOnly) {
481 // Prepare to generate code for the access
482
483 // L-value chains will be computed left to right. We're on the symbol now,
484 // which is the left-most part of the access chain, so now is "clear" time,
485 // followed by setting the base.
486 builder.clearAccessChain();
487
488 // For now, we consider all user variables as being in memory, so they are pointers,
489 // except for "const in" arguments to a function, which are an intermediate object.
490 // See comments in handleUserFunctionCall().
491 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
492 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
493 builder.setAccessChainRValue(id);
494 else
495 builder.setAccessChainLValue(id);
496 }
497}
498
499bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
500{
501 // First, handle special cases
502 switch (node->getOp()) {
503 case glslang::EOpAssign:
504 case glslang::EOpAddAssign:
505 case glslang::EOpSubAssign:
506 case glslang::EOpMulAssign:
507 case glslang::EOpVectorTimesMatrixAssign:
508 case glslang::EOpVectorTimesScalarAssign:
509 case glslang::EOpMatrixTimesScalarAssign:
510 case glslang::EOpMatrixTimesMatrixAssign:
511 case glslang::EOpDivAssign:
512 case glslang::EOpModAssign:
513 case glslang::EOpAndAssign:
514 case glslang::EOpInclusiveOrAssign:
515 case glslang::EOpExclusiveOrAssign:
516 case glslang::EOpLeftShiftAssign:
517 case glslang::EOpRightShiftAssign:
518 // A bin-op assign "a += b" means the same thing as "a = a + b"
519 // where a is evaluated before b. For a simple assignment, GLSL
520 // says to evaluate the left before the right. So, always, left
521 // node then right node.
522 {
523 // get the left l-value, save it away
524 builder.clearAccessChain();
525 node->getLeft()->traverse(this);
526 spv::Builder::AccessChain lValue = builder.getAccessChain();
527
528 // evaluate the right
529 builder.clearAccessChain();
530 node->getRight()->traverse(this);
531 spv::Id rValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
532
533 if (node->getOp() != glslang::EOpAssign) {
534 // the left is also an r-value
535 builder.setAccessChain(lValue);
536 spv::Id leftRValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
537
538 // do the operation
539 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
540 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
541 node->getType().getBasicType());
542
543 // these all need their counterparts in createBinaryOperation()
544 if (rValue == 0)
545 spv::MissingFunctionality("createBinaryOperation");
546 }
547
548 // store the result
549 builder.setAccessChain(lValue);
550 builder.accessChainStore(rValue);
551
552 // assignments are expressions having an rValue after they are evaluated...
553 builder.clearAccessChain();
554 builder.setAccessChainRValue(rValue);
555 }
556 return false;
557 case glslang::EOpIndexDirect:
558 case glslang::EOpIndexDirectStruct:
559 {
560 // Get the left part of the access chain.
561 node->getLeft()->traverse(this);
562
563 // Add the next element in the chain
564
565 int index = 0;
566 if (node->getRight()->getAsConstantUnion() == 0)
567 spv::MissingFunctionality("direct index without a constant node");
568 else
569 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
570
571 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
572 // This may be, e.g., an anonymous block-member selection, which generally need
573 // index remapping due to hidden members in anonymous blocks.
574 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
575 if (remapper.size() == 0)
576 spv::MissingFunctionality("block without member remapping");
577 else
578 index = remapper[index];
579 }
580
581 if (! node->getLeft()->getType().isArray() &&
582 node->getLeft()->getType().isVector() &&
583 node->getOp() == glslang::EOpIndexDirect) {
584 // This is essentially a hard-coded vector swizzle of size 1,
585 // so short circuit the access-chain stuff with a swizzle.
586 std::vector<unsigned> swizzle;
587 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
588 builder.accessChainPushSwizzle(swizzle);
589 } else {
590 // normal case for indexing array or structure or block
591 builder.accessChainPush(builder.makeIntConstant(index), convertGlslangToSpvType(node->getType()));
592 }
593 }
594 return false;
595 case glslang::EOpIndexIndirect:
596 {
597 // Structure or array or vector indirection.
598 // Will use native SPIR-V access-chain for struct and array indirection;
599 // matrices are arrays of vectors, so will also work for a matrix.
600 // Will use the access chain's 'component' for variable index into a vector.
601
602 // This adapter is building access chains left to right.
603 // Set up the access chain to the left.
604 node->getLeft()->traverse(this);
605
606 // save it so that computing the right side doesn't trash it
607 spv::Builder::AccessChain partial = builder.getAccessChain();
608
609 // compute the next index in the chain
610 builder.clearAccessChain();
611 node->getRight()->traverse(this);
612 spv::Id index = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
613
614 // restore the saved access chain
615 builder.setAccessChain(partial);
616
617 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
618 builder.accessChainPushComponent(index);
619 else
620 builder.accessChainPush(index, convertGlslangToSpvType(node->getType()));
621 }
622 return false;
623 case glslang::EOpVectorSwizzle:
624 {
625 node->getLeft()->traverse(this);
626 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
627 std::vector<unsigned> swizzle;
628 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
629 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
630 builder.accessChainPushSwizzle(swizzle);
631 }
632 return false;
633 default:
634 break;
635 }
636
637 // Assume generic binary op...
638
639 // Get the operands
640 builder.clearAccessChain();
641 node->getLeft()->traverse(this);
642 spv::Id left = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
643
644 builder.clearAccessChain();
645 node->getRight()->traverse(this);
646 spv::Id right = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
647
648 spv::Id result;
649 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
650
651 result = createBinaryOperation(node->getOp(), precision,
652 convertGlslangToSpvType(node->getType()), left, right,
653 node->getLeft()->getType().getBasicType());
654
655 if (! result) {
656 spv::MissingFunctionality("glslang binary operation");
657 } else {
658 builder.clearAccessChain();
659 builder.setAccessChainRValue(result);
660
661 return false;
662 }
663
664 return true;
665}
666
667bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
668{
John Kessenichfc51d282015-08-19 13:34:18 -0600669 spv::Id result = spv::NoResult;
670
671 // try texturing first
672 result = createImageTextureFunctionCall(node);
673 if (result != spv::NoResult) {
674 builder.clearAccessChain();
675 builder.setAccessChainRValue(result);
676
677 return false; // done with this node
678 }
679
680 // Non-texturing.
681 // Start by evaluating the operand
682
John Kessenich140f3df2015-06-26 16:58:36 -0600683 builder.clearAccessChain();
684 node->getOperand()->traverse(this);
685 spv::Id operand = builder.accessChainLoad(TranslatePrecisionDecoration(node->getOperand()->getType()));
686
687 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
688
689 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600690 if (! result)
691 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600692
693 // if not, then possibly an operation
694 if (! result)
John Kessenichfc51d282015-08-19 13:34:18 -0600695 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand,
696 node->getBasicType() == glslang::EbtFloat || node->getBasicType() == glslang::EbtDouble);
John Kessenich140f3df2015-06-26 16:58:36 -0600697
698 if (result) {
699 builder.clearAccessChain();
700 builder.setAccessChainRValue(result);
701
702 return false; // done with this node
703 }
704
705 // it must be a special case, check...
706 switch (node->getOp()) {
707 case glslang::EOpPostIncrement:
708 case glslang::EOpPostDecrement:
709 case glslang::EOpPreIncrement:
710 case glslang::EOpPreDecrement:
711 {
712 // we need the integer value "1" or the floating point "1.0" to add/subtract
713 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
714 builder.makeFloatConstant(1.0F) :
715 builder.makeIntConstant(1);
716 glslang::TOperator op;
717 if (node->getOp() == glslang::EOpPreIncrement ||
718 node->getOp() == glslang::EOpPostIncrement)
719 op = glslang::EOpAdd;
720 else
721 op = glslang::EOpSub;
722
723 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
724 convertGlslangToSpvType(node->getType()), operand, one,
725 node->getType().getBasicType());
726 if (result == 0)
727 spv::MissingFunctionality("createBinaryOperation for unary");
728
729 // The result of operation is always stored, but conditionally the
730 // consumed result. The consumed result is always an r-value.
731 builder.accessChainStore(result);
732 builder.clearAccessChain();
733 if (node->getOp() == glslang::EOpPreIncrement ||
734 node->getOp() == glslang::EOpPreDecrement)
735 builder.setAccessChainRValue(result);
736 else
737 builder.setAccessChainRValue(operand);
738 }
739
740 return false;
741
742 case glslang::EOpEmitStreamVertex:
743 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
744 return false;
745 case glslang::EOpEndStreamPrimitive:
746 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
747 return false;
748
749 default:
750 spv::MissingFunctionality("glslang unary");
751 break;
752 }
753
754 return true;
755}
756
757bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
758{
John Kessenichfc51d282015-08-19 13:34:18 -0600759 spv::Id result = spv::NoResult;
760
761 // try texturing
762 result = createImageTextureFunctionCall(node);
763 if (result != spv::NoResult) {
764 builder.clearAccessChain();
765 builder.setAccessChainRValue(result);
766
767 return false;
768 }
769
John Kessenich140f3df2015-06-26 16:58:36 -0600770 glslang::TOperator binOp = glslang::EOpNull;
771 bool reduceComparison = true;
772 bool isMatrix = false;
773 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600774 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600775
776 assert(node->getOp());
777
778 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
779
780 switch (node->getOp()) {
781 case glslang::EOpSequence:
782 {
783 if (preVisit)
784 ++sequenceDepth;
785 else
786 --sequenceDepth;
787
788 if (sequenceDepth == 1) {
789 // If this is the parent node of all the functions, we want to see them
790 // early, so all call points have actual SPIR-V functions to reference.
791 // In all cases, still let the traverser visit the children for us.
792 makeFunctions(node->getAsAggregate()->getSequence());
793
794 // Also, we want all globals initializers to go into the entry of main(), before
795 // anything else gets there, so visit out of order, doing them all now.
796 makeGlobalInitializers(node->getAsAggregate()->getSequence());
797
798 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
799 // so do them manually.
800 visitFunctions(node->getAsAggregate()->getSequence());
801
802 return false;
803 }
804
805 return true;
806 }
807 case glslang::EOpLinkerObjects:
808 {
809 if (visit == glslang::EvPreVisit)
810 linkageOnly = true;
811 else
812 linkageOnly = false;
813
814 return true;
815 }
816 case glslang::EOpComma:
817 {
818 // processing from left to right naturally leaves the right-most
819 // lying around in the access chain
820 glslang::TIntermSequence& glslangOperands = node->getSequence();
821 for (int i = 0; i < (int)glslangOperands.size(); ++i)
822 glslangOperands[i]->traverse(this);
823
824 return false;
825 }
826 case glslang::EOpFunction:
827 if (visit == glslang::EvPreVisit) {
828 if (isShaderEntrypoint(node)) {
829 inMain = true;
830 builder.setBuildPoint(shaderEntry->getLastBlock());
831 } else {
832 handleFunctionEntry(node);
833 }
834 } else {
835 if (inMain)
836 mainTerminated = true;
837 builder.leaveFunction(inMain);
838 inMain = false;
839 }
840
841 return true;
842 case glslang::EOpParameters:
843 // Parameters will have been consumed by EOpFunction processing, but not
844 // the body, so we still visited the function node's children, making this
845 // child redundant.
846 return false;
847 case glslang::EOpFunctionCall:
848 {
849 if (node->isUserDefined())
850 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600851
852 if (! result) {
853 spv::MissingFunctionality("glslang function call");
854 glslang::TConstUnionArray emptyConsts;
855 int nextConst = 0;
856 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
857 }
858 builder.clearAccessChain();
859 builder.setAccessChainRValue(result);
860
861 return false;
862 }
863 case glslang::EOpConstructMat2x2:
864 case glslang::EOpConstructMat2x3:
865 case glslang::EOpConstructMat2x4:
866 case glslang::EOpConstructMat3x2:
867 case glslang::EOpConstructMat3x3:
868 case glslang::EOpConstructMat3x4:
869 case glslang::EOpConstructMat4x2:
870 case glslang::EOpConstructMat4x3:
871 case glslang::EOpConstructMat4x4:
872 case glslang::EOpConstructDMat2x2:
873 case glslang::EOpConstructDMat2x3:
874 case glslang::EOpConstructDMat2x4:
875 case glslang::EOpConstructDMat3x2:
876 case glslang::EOpConstructDMat3x3:
877 case glslang::EOpConstructDMat3x4:
878 case glslang::EOpConstructDMat4x2:
879 case glslang::EOpConstructDMat4x3:
880 case glslang::EOpConstructDMat4x4:
881 isMatrix = true;
882 // fall through
883 case glslang::EOpConstructFloat:
884 case glslang::EOpConstructVec2:
885 case glslang::EOpConstructVec3:
886 case glslang::EOpConstructVec4:
887 case glslang::EOpConstructDouble:
888 case glslang::EOpConstructDVec2:
889 case glslang::EOpConstructDVec3:
890 case glslang::EOpConstructDVec4:
891 case glslang::EOpConstructBool:
892 case glslang::EOpConstructBVec2:
893 case glslang::EOpConstructBVec3:
894 case glslang::EOpConstructBVec4:
895 case glslang::EOpConstructInt:
896 case glslang::EOpConstructIVec2:
897 case glslang::EOpConstructIVec3:
898 case glslang::EOpConstructIVec4:
899 case glslang::EOpConstructUint:
900 case glslang::EOpConstructUVec2:
901 case glslang::EOpConstructUVec3:
902 case glslang::EOpConstructUVec4:
903 case glslang::EOpConstructStruct:
904 {
905 std::vector<spv::Id> arguments;
906 translateArguments(node->getSequence(), arguments);
907 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
908 spv::Id constructed;
909 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
910 std::vector<spv::Id> constituents;
911 for (int c = 0; c < (int)arguments.size(); ++c)
912 constituents.push_back(arguments[c]);
913 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
914 } else {
915 if (isMatrix)
916 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
917 else
918 constructed = builder.createConstructor(precision, arguments, resultTypeId);
919 }
920
921 builder.clearAccessChain();
922 builder.setAccessChainRValue(constructed);
923
924 return false;
925 }
926
927 // These six are component-wise compares with component-wise results.
928 // Forward on to createBinaryOperation(), requesting a vector result.
929 case glslang::EOpLessThan:
930 case glslang::EOpGreaterThan:
931 case glslang::EOpLessThanEqual:
932 case glslang::EOpGreaterThanEqual:
933 case glslang::EOpVectorEqual:
934 case glslang::EOpVectorNotEqual:
935 {
936 // Map the operation to a binary
937 binOp = node->getOp();
938 reduceComparison = false;
939 switch (node->getOp()) {
940 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
941 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
942 default: binOp = node->getOp(); break;
943 }
944
945 break;
946 }
947 case glslang::EOpMul:
948 // compontent-wise matrix multiply
949 binOp = glslang::EOpMul;
950 break;
951 case glslang::EOpOuterProduct:
952 // two vectors multiplied to make a matrix
953 binOp = glslang::EOpOuterProduct;
954 break;
955 case glslang::EOpDot:
956 {
957 // for scalar dot product, use multiply
958 glslang::TIntermSequence& glslangOperands = node->getSequence();
959 if (! glslangOperands[0]->getAsTyped()->isVector())
960 binOp = glslang::EOpMul;
961 break;
962 }
963 case glslang::EOpMod:
964 // when an aggregate, this is the floating-point mod built-in function,
965 // which can be emitted by the one in createBinaryOperation()
966 binOp = glslang::EOpMod;
967 break;
968 case glslang::EOpArrayLength:
969 {
970 glslang::TIntermTyped* typedNode = node->getSequence()[0]->getAsTyped();
971 assert(typedNode);
John Kessenich65c78a02015-08-10 17:08:55 -0600972 spv::Id length = builder.makeIntConstant(typedNode->getType().getOuterArraySize());
John Kessenich140f3df2015-06-26 16:58:36 -0600973
974 builder.clearAccessChain();
975 builder.setAccessChainRValue(length);
976
977 return false;
978 }
979 case glslang::EOpEmitVertex:
980 case glslang::EOpEndPrimitive:
981 case glslang::EOpBarrier:
982 case glslang::EOpMemoryBarrier:
983 case glslang::EOpMemoryBarrierAtomicCounter:
984 case glslang::EOpMemoryBarrierBuffer:
985 case glslang::EOpMemoryBarrierImage:
986 case glslang::EOpMemoryBarrierShared:
987 case glslang::EOpGroupMemoryBarrier:
988 noReturnValue = true;
989 // These all have 0 operands and will naturally finish up in the code below for 0 operands
990 break;
991
John Kessenich426394d2015-07-23 10:22:48 -0600992 case glslang::EOpAtomicAdd:
993 case glslang::EOpAtomicMin:
994 case glslang::EOpAtomicMax:
995 case glslang::EOpAtomicAnd:
996 case glslang::EOpAtomicOr:
997 case glslang::EOpAtomicXor:
998 case glslang::EOpAtomicExchange:
999 case glslang::EOpAtomicCompSwap:
1000 atomic = true;
1001 break;
1002
John Kessenichfc51d282015-08-19 13:34:18 -06001003 case glslang::EOpAddCarry:
1004 case glslang::EOpSubBorrow:
1005 case glslang::EOpUMulExtended:
1006 case glslang::EOpIMulExtended:
1007 case glslang::EOpBitfieldExtract:
1008 case glslang::EOpBitfieldInsert:
1009 spv::MissingFunctionality("integer aggregate");
1010 break;
1011
1012 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001013 case glslang::EOpFrexp:
1014 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001015 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1016 break;
1017
John Kessenich140f3df2015-06-26 16:58:36 -06001018 default:
1019 break;
1020 }
1021
1022 //
1023 // See if it maps to a regular operation.
1024 //
John Kessenich140f3df2015-06-26 16:58:36 -06001025 if (binOp != glslang::EOpNull) {
1026 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1027 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1028 assert(left && right);
1029
1030 builder.clearAccessChain();
1031 left->traverse(this);
1032 spv::Id leftId = builder.accessChainLoad(TranslatePrecisionDecoration(left->getType()));
1033
1034 builder.clearAccessChain();
1035 right->traverse(this);
1036 spv::Id rightId = builder.accessChainLoad(TranslatePrecisionDecoration(right->getType()));
1037
1038 result = createBinaryOperation(binOp, precision,
1039 convertGlslangToSpvType(node->getType()), leftId, rightId,
1040 left->getType().getBasicType(), reduceComparison);
1041
1042 // code above should only make binOp that exists in createBinaryOperation
1043 if (result == 0)
1044 spv::MissingFunctionality("createBinaryOperation for aggregate");
1045
1046 builder.clearAccessChain();
1047 builder.setAccessChainRValue(result);
1048
1049 return false;
1050 }
1051
John Kessenich426394d2015-07-23 10:22:48 -06001052 //
1053 // Create the list of operands.
1054 //
John Kessenich140f3df2015-06-26 16:58:36 -06001055 glslang::TIntermSequence& glslangOperands = node->getSequence();
1056 std::vector<spv::Id> operands;
1057 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1058 builder.clearAccessChain();
1059 glslangOperands[arg]->traverse(this);
1060
1061 // special case l-value operands; there are just a few
1062 bool lvalue = false;
1063 switch (node->getOp()) {
1064 //case glslang::EOpFrexp:
1065 case glslang::EOpModf:
1066 if (arg == 1)
1067 lvalue = true;
1068 break;
1069 //case glslang::EOpUAddCarry:
1070 //case glslang::EOpUSubBorrow:
1071 //case glslang::EOpUMulExtended:
1072 default:
1073 break;
1074 }
1075 if (lvalue)
1076 operands.push_back(builder.accessChainGetLValue());
1077 else
1078 operands.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangOperands[arg]->getAsTyped()->getType())));
1079 }
John Kessenich426394d2015-07-23 10:22:48 -06001080
1081 if (atomic) {
1082 // Handle all atomics
1083 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands);
1084 } else {
1085 // Pass through to generic operations.
1086 switch (glslangOperands.size()) {
1087 case 0:
1088 result = createNoArgOperation(node->getOp());
1089 break;
1090 case 1:
1091 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType() == glslang::EbtFloat || node->getType().getBasicType() == glslang::EbtDouble);
1092 break;
1093 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001094 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001095 break;
1096 }
John Kessenich140f3df2015-06-26 16:58:36 -06001097 }
1098
1099 if (noReturnValue)
1100 return false;
1101
1102 if (! result) {
1103 spv::MissingFunctionality("glslang aggregate");
1104 return true;
1105 } else {
1106 builder.clearAccessChain();
1107 builder.setAccessChainRValue(result);
1108 return false;
1109 }
1110}
1111
1112bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1113{
1114 // This path handles both if-then-else and ?:
1115 // The if-then-else has a node type of void, while
1116 // ?: has a non-void node type
1117 spv::Id result = 0;
1118 if (node->getBasicType() != glslang::EbtVoid) {
1119 // don't handle this as just on-the-fly temporaries, because there will be two names
1120 // and better to leave SSA to later passes
1121 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1122 }
1123
1124 // emit the condition before doing anything with selection
1125 node->getCondition()->traverse(this);
1126
1127 // make an "if" based on the value created by the condition
1128 spv::Builder::If ifBuilder(builder.accessChainLoad(spv::NoPrecision), builder);
1129
1130 if (node->getTrueBlock()) {
1131 // emit the "then" statement
1132 node->getTrueBlock()->traverse(this);
1133 if (result)
1134 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getTrueBlock()->getAsTyped()->getType())), result);
1135 }
1136
1137 if (node->getFalseBlock()) {
1138 ifBuilder.makeBeginElse();
1139 // emit the "else" statement
1140 node->getFalseBlock()->traverse(this);
1141 if (result)
1142 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getFalseBlock()->getAsTyped()->getType())), result);
1143 }
1144
1145 ifBuilder.makeEndIf();
1146
1147 if (result) {
1148 // GLSL only has r-values as the result of a :?, but
1149 // if we have an l-value, that can be more efficient if it will
1150 // become the base of a complex r-value expression, because the
1151 // next layer copies r-values into memory to use the access-chain mechanism
1152 builder.clearAccessChain();
1153 builder.setAccessChainLValue(result);
1154 }
1155
1156 return false;
1157}
1158
1159bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1160{
1161 // emit and get the condition before doing anything with switch
1162 node->getCondition()->traverse(this);
1163 spv::Id selector = builder.accessChainLoad(TranslatePrecisionDecoration(node->getCondition()->getAsTyped()->getType()));
1164
1165 // browse the children to sort out code segments
1166 int defaultSegment = -1;
1167 std::vector<TIntermNode*> codeSegments;
1168 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1169 std::vector<int> caseValues;
1170 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1171 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1172 TIntermNode* child = *c;
1173 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001174 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001175 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001176 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001177 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1178 } else
1179 codeSegments.push_back(child);
1180 }
1181
1182 // handle the case where the last code segment is missing, due to no code
1183 // statements between the last case and the end of the switch statement
1184 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1185 (int)codeSegments.size() == defaultSegment)
1186 codeSegments.push_back(nullptr);
1187
1188 // make the switch statement
1189 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001190 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001191
1192 // emit all the code in the segments
1193 breakForLoop.push(false);
1194 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1195 builder.nextSwitchSegment(segmentBlocks, s);
1196 if (codeSegments[s])
1197 codeSegments[s]->traverse(this);
1198 else
1199 builder.addSwitchBreak();
1200 }
1201 breakForLoop.pop();
1202
1203 builder.endSwitch(segmentBlocks);
1204
1205 return false;
1206}
1207
1208void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1209{
1210 int nextConst = 0;
1211 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1212
1213 builder.clearAccessChain();
1214 builder.setAccessChainRValue(constant);
1215}
1216
1217bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1218{
1219 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1220 loopTerminal.push(node->getTerminal());
1221
David Netoc22f37c2015-07-15 16:21:26 -04001222 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001223
1224 if (node->getTest()) {
1225 node->getTest()->traverse(this);
1226 // the AST only contained the test computation, not the branch, we have to add it
1227 spv::Id condition = builder.accessChainLoad(TranslatePrecisionDecoration(node->getTest()->getType()));
1228 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001229 } else {
1230 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001231 }
1232
David Netoc22f37c2015-07-15 16:21:26 -04001233 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001234 breakForLoop.push(true);
1235 node->getBody()->traverse(this);
1236 breakForLoop.pop();
1237 }
1238
1239 if (loopTerminal.top())
1240 loopTerminal.top()->traverse(this);
1241
1242 builder.closeLoop();
1243
1244 loopTerminal.pop();
1245
1246 return false;
1247}
1248
1249bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1250{
1251 if (node->getExpression())
1252 node->getExpression()->traverse(this);
1253
1254 switch (node->getFlowOp()) {
1255 case glslang::EOpKill:
1256 builder.makeDiscard();
1257 break;
1258 case glslang::EOpBreak:
1259 if (breakForLoop.top())
1260 builder.createLoopExit();
1261 else
1262 builder.addSwitchBreak();
1263 break;
1264 case glslang::EOpContinue:
1265 if (loopTerminal.top())
1266 loopTerminal.top()->traverse(this);
1267 builder.createLoopContinue();
1268 break;
1269 case glslang::EOpReturn:
1270 if (inMain)
1271 builder.makeMainReturn();
1272 else if (node->getExpression())
1273 builder.makeReturn(false, builder.accessChainLoad(TranslatePrecisionDecoration(node->getExpression()->getType())));
1274 else
1275 builder.makeReturn();
1276
1277 builder.clearAccessChain();
1278 break;
1279
1280 default:
1281 spv::MissingFunctionality("branch type");
1282 break;
1283 }
1284
1285 return false;
1286}
1287
1288spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1289{
1290 // First, steer off constants, which are not SPIR-V variables, but
1291 // can still have a mapping to a SPIR-V Id.
1292 if (node->getQualifier().storage == glslang::EvqConst) {
1293 int nextConst = 0;
1294 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1295 }
1296
1297 // Now, handle actual variables
1298 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1299 spv::Id spvType = convertGlslangToSpvType(node->getType());
1300
1301 const char* name = node->getName().c_str();
1302 if (glslang::IsAnonymous(name))
1303 name = "";
1304
1305 return builder.createVariable(storageClass, spvType, name);
1306}
1307
1308// Return type Id of the sampled type.
1309spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1310{
1311 switch (sampler.type) {
1312 case glslang::EbtFloat: return builder.makeFloatType(32);
1313 case glslang::EbtInt: return builder.makeIntType(32);
1314 case glslang::EbtUint: return builder.makeUintType(32);
1315 default:
1316 spv::MissingFunctionality("sampled type");
1317 return builder.makeFloatType(32);
1318 }
1319}
1320
1321// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1322spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1323{
1324 spv::Id spvType = 0;
1325
1326 switch (type.getBasicType()) {
1327 case glslang::EbtVoid:
1328 spvType = builder.makeVoidType();
1329 if (type.isArray())
1330 spv::MissingFunctionality("array of void");
1331 break;
1332 case glslang::EbtFloat:
1333 spvType = builder.makeFloatType(32);
1334 break;
1335 case glslang::EbtDouble:
1336 spvType = builder.makeFloatType(64);
1337 break;
1338 case glslang::EbtBool:
1339 spvType = builder.makeBoolType();
1340 break;
1341 case glslang::EbtInt:
1342 spvType = builder.makeIntType(32);
1343 break;
1344 case glslang::EbtUint:
1345 spvType = builder.makeUintType(32);
1346 break;
John Kessenich426394d2015-07-23 10:22:48 -06001347 case glslang::EbtAtomicUint:
1348 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1349 spvType = builder.makeUintType(32);
1350 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001351 case glslang::EbtSampler:
1352 {
1353 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001354 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1355 sampler.image ? 2 : 1, spv::ImageFormatUnknown); // TODO: translate format, needed for GLSL image ops
1356 // OpenGL "textures" need to be combined with a sampler
1357 if (! sampler.image)
1358 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001359 }
1360 break;
1361 case glslang::EbtStruct:
1362 case glslang::EbtBlock:
1363 {
1364 // If we've seen this struct type, return it
1365 const glslang::TTypeList* glslangStruct = type.getStruct();
1366 std::vector<spv::Id> structFields;
1367 spvType = structMap[glslangStruct];
1368 if (spvType)
1369 break;
1370
1371 // else, we haven't seen it...
1372
1373 // Create a vector of struct types for SPIR-V to consume
1374 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1375 if (type.getBasicType() == glslang::EbtBlock)
1376 memberRemapper[glslangStruct].resize(glslangStruct->size());
1377 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1378 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1379 if (glslangType.hiddenMember()) {
1380 ++memberDelta;
1381 if (type.getBasicType() == glslang::EbtBlock)
1382 memberRemapper[glslangStruct][i] = -1;
1383 } else {
1384 if (type.getBasicType() == glslang::EbtBlock)
1385 memberRemapper[glslangStruct][i] = i - memberDelta;
1386 structFields.push_back(convertGlslangToSpvType(glslangType));
1387 }
1388 }
1389
1390 // Make the SPIR-V type
1391 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1392 structMap[glslangStruct] = spvType;
1393
1394 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001395 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001396 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1397 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1398 int member = i;
1399 if (type.getBasicType() == glslang::EbtBlock)
1400 member = memberRemapper[glslangStruct][i];
1401 // using -1 above to indicate a hidden member
1402 if (member >= 0) {
1403 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1404 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1405 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1406 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1407 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1408 if (glslangType.getQualifier().hasLocation())
1409 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1410 if (glslangType.getQualifier().hasComponent())
1411 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1412 if (glslangType.getQualifier().hasXfbOffset())
1413 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001414 else {
1415 // figure out what to do with offset, which is accumulating
1416 int nextOffset;
1417 updateMemberOffset(type, glslangType, offset, nextOffset);
1418 if (offset >= 0)
1419 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutOffset);
1420 offset = nextOffset;
1421 }
John Kessenich140f3df2015-06-26 16:58:36 -06001422
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001423 if (glslangType.isMatrix()) {
1424 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1425 }
1426
John Kessenich140f3df2015-06-26 16:58:36 -06001427 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001428 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1429 if (builtIn != spv::BadValue)
1430 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001431 }
1432 }
1433
1434 // Decorate the structure
1435 addDecoration(spvType, TranslateLayoutDecoration(type));
1436 addDecoration(spvType, TranslateBlockDecoration(type));
1437 if (type.getQualifier().hasStream())
1438 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1439 if (glslangIntermediate->getXfbMode()) {
1440 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001441 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001442 if (type.getQualifier().hasXfbBuffer())
1443 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1444 }
1445 }
1446 break;
1447 default:
1448 spv::MissingFunctionality("basic type");
1449 break;
1450 }
1451
1452 if (type.isMatrix())
1453 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1454 else {
1455 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1456 if (type.getVectorSize() > 1)
1457 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1458 }
1459
1460 if (type.isArray()) {
1461 unsigned arraySize;
1462 if (! type.isExplicitlySizedArray()) {
1463 spv::MissingFunctionality("Unsized array");
1464 arraySize = 8;
1465 } else
John Kessenich65c78a02015-08-10 17:08:55 -06001466 arraySize = type.getOuterArraySize();
John Kessenich140f3df2015-06-26 16:58:36 -06001467 spvType = builder.makeArrayType(spvType, arraySize);
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001468 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001469 }
1470
1471 return spvType;
1472}
1473
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001474// Given an array type, returns the integer stride required for that array
1475int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1476{
1477 glslang::TType derefType(arrayType, 0);
1478 int size;
1479 glslangIntermediate->getBaseAlignment(derefType, size, true);
1480 return size;
1481}
1482
1483// Given a matrix type, returns the integer stride required for that matrix
1484// when used as a member of an interface block
1485int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1486{
1487 int size;
1488 return glslangIntermediate->getBaseAlignment(matrixType, size, true);
1489}
1490
John Kessenich5e4b1242015-08-06 22:53:06 -06001491// Given a member type of a struct, realign the current offset for it, and compute
1492// the next (not yet aligned) offset for the next member, which will get aligned
1493// on the next call.
1494// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1495// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1496// -1 means a non-forced member offset (no decoration needed).
1497void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1498{
1499 // this will get a positive value when deemed necessary
1500 nextOffset = -1;
1501
1502 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1503 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1504
1505 // override anything in currentOffset with user-set offset
1506 if (memberType.getQualifier().hasOffset())
1507 currentOffset = memberType.getQualifier().layoutOffset;
1508
1509 // It could be that current linker usage in glslang updated all the layoutOffset,
1510 // in which case the following code does not matter. But, that's not quite right
1511 // once cross-compilation unit GLSL validation is done, as the original user
1512 // settings are needed in layoutOffset, and then the following will come into play.
1513
1514 if (! forceOffset) {
1515 if (! memberType.getQualifier().hasOffset())
1516 currentOffset = -1;
1517
1518 return;
1519 }
1520
1521 // Getting this far means we are forcing offsets
1522 if (currentOffset < 0)
1523 currentOffset = 0;
1524
1525 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1526 // but possibly not yet correctly aligned.
1527
1528 int memberSize;
1529 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1530 glslang::RoundToPow2(currentOffset, memberAlignment);
1531 nextOffset = currentOffset + memberSize;
1532}
1533
John Kessenich140f3df2015-06-26 16:58:36 -06001534bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1535{
1536 return node->getName() == "main(";
1537}
1538
1539// Make all the functions, skeletally, without actually visiting their bodies.
1540void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1541{
1542 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1543 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1544 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1545 continue;
1546
1547 // We're on a user function. Set up the basic interface for the function now,
1548 // so that it's available to call.
1549 // Translating the body will happen later.
1550 //
1551 // Typically (except for a "const in" parameter), an address will be passed to the
1552 // function. What it is an address of varies:
1553 //
1554 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1555 // so that write needs to be to a copy, hence the address of a copy works.
1556 //
1557 // - "const in" parameters can just be the r-value, as no writes need occur.
1558 //
1559 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1560 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1561
1562 std::vector<spv::Id> paramTypes;
1563 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1564
1565 for (int p = 0; p < (int)parameters.size(); ++p) {
1566 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1567 spv::Id typeId = convertGlslangToSpvType(paramType);
1568 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1569 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1570 else
1571 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1572 paramTypes.push_back(typeId);
1573 }
1574
1575 spv::Block* functionBlock;
1576 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1577 paramTypes, &functionBlock);
1578
1579 // Track function to emit/call later
1580 functionMap[glslFunction->getName().c_str()] = function;
1581
1582 // Set the parameter id's
1583 for (int p = 0; p < (int)parameters.size(); ++p) {
1584 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1585 // give a name too
1586 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1587 }
1588 }
1589}
1590
1591// Process all the initializers, while skipping the functions and link objects
1592void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1593{
1594 builder.setBuildPoint(shaderEntry->getLastBlock());
1595 for (int i = 0; i < (int)initializers.size(); ++i) {
1596 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1597 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1598
1599 // We're on a top-level node that's not a function. Treat as an initializer, whose
1600 // code goes into the beginning of main.
1601 initializer->traverse(this);
1602 }
1603 }
1604}
1605
1606// Process all the functions, while skipping initializers.
1607void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1608{
1609 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1610 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1611 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1612 node->traverse(this);
1613 }
1614}
1615
1616void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1617{
1618 // SPIR-V functions should already be in the functionMap from the prepass
1619 // that called makeFunctions().
1620 spv::Function* function = functionMap[node->getName().c_str()];
1621 spv::Block* functionBlock = function->getEntryBlock();
1622 builder.setBuildPoint(functionBlock);
1623}
1624
1625void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments)
1626{
1627 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1628 builder.clearAccessChain();
1629 glslangArguments[i]->traverse(this);
1630 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArguments[i]->getAsTyped()->getType())));
1631 }
1632}
1633
John Kessenichfc51d282015-08-19 13:34:18 -06001634void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001635{
John Kessenichfc51d282015-08-19 13:34:18 -06001636 builder.clearAccessChain();
1637 node.getOperand()->traverse(this);
1638 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(node.getAsTyped()->getType())));
1639}
John Kessenich140f3df2015-06-26 16:58:36 -06001640
John Kessenichfc51d282015-08-19 13:34:18 -06001641spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1642{
1643 if (node->isImage()) {
1644 spv::MissingFunctionality("GLSL image function");
1645 return spv::NoResult;
1646 } else if (! node->isTexture()) {
1647 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001648 }
1649
John Kessenichfc51d282015-08-19 13:34:18 -06001650 // Process a GLSL texturing op (will be SPV image)
John Kessenich140f3df2015-06-26 16:58:36 -06001651
John Kessenichfc51d282015-08-19 13:34:18 -06001652 glslang::TCrackedTextureOp cracked;
1653 node->crackTexture(cracked);
1654
1655 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1656 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1657 std::vector<spv::Id> arguments;
1658 if (node->getAsAggregate())
1659 translateArguments(node->getAsAggregate()->getSequence(), arguments);
1660 else
1661 translateArguments(*node->getAsUnaryNode(), arguments);
1662 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1663
1664 spv::Builder::TextureParameters params = { };
1665 params.sampler = arguments[0];
1666
1667 // Check for queries
1668 if (cracked.query) {
1669 switch (node->getOp()) {
1670 case glslang::EOpImageQuerySize:
1671 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001672 if (arguments.size() > 1) {
1673 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001674 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001676 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001677 case glslang::EOpImageQuerySamples:
1678 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001679 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001680 case glslang::EOpTextureQueryLod:
1681 params.coords = arguments[1];
1682 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1683 case glslang::EOpTextureQueryLevels:
1684 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1685 default:
1686 assert(0);
1687 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001688 }
John Kessenich140f3df2015-06-26 16:58:36 -06001689 }
1690
John Kessenichfc51d282015-08-19 13:34:18 -06001691 // This is no longer a query....
John Kessenich140f3df2015-06-26 16:58:36 -06001692
John Kessenichfc51d282015-08-19 13:34:18 -06001693 if (cracked.fetch)
1694 spv::MissingFunctionality("texel fetch");
1695 if (cracked.gather)
1696 spv::MissingFunctionality("texture gather");
1697
1698 // check for bias argument
1699 bool bias = false;
1700 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1701 int nonBiasArgCount = 2;
1702 if (cracked.offset)
1703 ++nonBiasArgCount;
1704 if (cracked.grad)
1705 nonBiasArgCount += 2;
1706
1707 if ((int)arguments.size() > nonBiasArgCount)
1708 bias = true;
1709 }
1710
1711 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1712
1713 // set the rest of the arguments
1714 params.coords = arguments[1];
1715 int extraArgs = 0;
1716 if (cubeCompare)
1717 params.Dref = arguments[2];
1718 else if (sampler.shadow) {
1719 std::vector<spv::Id> indexes;
1720 int comp;
1721 if (cracked.proj)
1722 comp = 3;
1723 else
1724 comp = builder.getNumComponents(params.coords) - 1;
1725 indexes.push_back(comp);
1726 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1727 }
1728 if (cracked.lod) {
1729 params.lod = arguments[2];
1730 ++extraArgs;
1731 }
1732 if (cracked.grad) {
1733 params.gradX = arguments[2 + extraArgs];
1734 params.gradY = arguments[3 + extraArgs];
1735 extraArgs += 2;
1736 }
1737 //if (gather && compare) {
1738 // params.compare = arguments[2 + extraArgs];
1739 // ++extraArgs;
1740 //}
1741 if (cracked.offset || cracked.offsets) {
1742 params.offset = arguments[2 + extraArgs];
1743 ++extraArgs;
1744 }
1745 if (bias) {
1746 params.bias = arguments[2 + extraArgs];
1747 ++extraArgs;
1748 }
1749
1750 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001751}
1752
1753spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1754{
1755 // Grab the function's pointer from the previously created function
1756 spv::Function* function = functionMap[node->getName().c_str()];
1757 if (! function)
1758 return 0;
1759
1760 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1761 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1762
1763 // See comments in makeFunctions() for details about the semantics for parameter passing.
1764 //
1765 // These imply we need a four step process:
1766 // 1. Evaluate the arguments
1767 // 2. Allocate and make copies of in, out, and inout arguments
1768 // 3. Make the call
1769 // 4. Copy back the results
1770
1771 // 1. Evaluate the arguments
1772 std::vector<spv::Builder::AccessChain> lValues;
1773 std::vector<spv::Id> rValues;
1774 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1775 // build l-value
1776 builder.clearAccessChain();
1777 glslangArgs[a]->traverse(this);
1778 // keep outputs as l-values, evaluate input-only as r-values
1779 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1780 // save l-value
1781 lValues.push_back(builder.getAccessChain());
1782 } else {
1783 // process r-value
1784 rValues.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArgs[a]->getAsTyped()->getType())));
1785 }
1786 }
1787
1788 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1789 // copy the original into that space.
1790 //
1791 // Also, build up the list of actual arguments to pass in for the call
1792 int lValueCount = 0;
1793 int rValueCount = 0;
1794 std::vector<spv::Id> spvArgs;
1795 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1796 spv::Id arg;
1797 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1798 // need space to hold the copy
1799 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1800 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1801 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1802 // need to copy the input into output space
1803 builder.setAccessChain(lValues[lValueCount]);
1804 spv::Id copy = builder.accessChainLoad(spv::NoPrecision); // TODO: get precision
1805 builder.createStore(copy, arg);
1806 }
1807 ++lValueCount;
1808 } else {
1809 arg = rValues[rValueCount];
1810 ++rValueCount;
1811 }
1812 spvArgs.push_back(arg);
1813 }
1814
1815 // 3. Make the call.
1816 spv::Id result = builder.createFunctionCall(function, spvArgs);
1817
1818 // 4. Copy back out an "out" arguments.
1819 lValueCount = 0;
1820 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1821 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1822 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1823 spv::Id copy = builder.createLoad(spvArgs[a]);
1824 builder.setAccessChain(lValues[lValueCount]);
1825 builder.accessChainStore(copy);
1826 }
1827 ++lValueCount;
1828 }
1829 }
1830
1831 return result;
1832}
1833
1834// Translate AST operation to SPV operation, already having SPV-based operands/types.
1835spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
1836 spv::Id typeId, spv::Id left, spv::Id right,
1837 glslang::TBasicType typeProxy, bool reduceComparison)
1838{
1839 bool isUnsigned = typeProxy == glslang::EbtUint;
1840 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
1841
1842 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06001843 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06001844 bool comparison = false;
1845
1846 switch (op) {
1847 case glslang::EOpAdd:
1848 case glslang::EOpAddAssign:
1849 if (isFloat)
1850 binOp = spv::OpFAdd;
1851 else
1852 binOp = spv::OpIAdd;
1853 break;
1854 case glslang::EOpSub:
1855 case glslang::EOpSubAssign:
1856 if (isFloat)
1857 binOp = spv::OpFSub;
1858 else
1859 binOp = spv::OpISub;
1860 break;
1861 case glslang::EOpMul:
1862 case glslang::EOpMulAssign:
1863 if (isFloat)
1864 binOp = spv::OpFMul;
1865 else
1866 binOp = spv::OpIMul;
1867 break;
1868 case glslang::EOpVectorTimesScalar:
1869 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06001870 if (isFloat) {
1871 if (builder.isVector(right))
1872 std::swap(left, right);
1873 assert(builder.isScalar(right));
1874 needMatchingVectors = false;
1875 binOp = spv::OpVectorTimesScalar;
1876 } else
1877 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06001878 break;
1879 case glslang::EOpVectorTimesMatrix:
1880 case glslang::EOpVectorTimesMatrixAssign:
1881 assert(builder.isVector(left));
1882 assert(builder.isMatrix(right));
1883 binOp = spv::OpVectorTimesMatrix;
1884 break;
1885 case glslang::EOpMatrixTimesVector:
1886 assert(builder.isMatrix(left));
1887 assert(builder.isVector(right));
1888 binOp = spv::OpMatrixTimesVector;
1889 break;
1890 case glslang::EOpMatrixTimesScalar:
1891 case glslang::EOpMatrixTimesScalarAssign:
1892 if (builder.isMatrix(right))
1893 std::swap(left, right);
1894 assert(builder.isScalar(right));
1895 binOp = spv::OpMatrixTimesScalar;
1896 break;
1897 case glslang::EOpMatrixTimesMatrix:
1898 case glslang::EOpMatrixTimesMatrixAssign:
1899 assert(builder.isMatrix(left));
1900 assert(builder.isMatrix(right));
1901 binOp = spv::OpMatrixTimesMatrix;
1902 break;
1903 case glslang::EOpOuterProduct:
1904 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06001905 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001906 break;
1907
1908 case glslang::EOpDiv:
1909 case glslang::EOpDivAssign:
1910 if (isFloat)
1911 binOp = spv::OpFDiv;
1912 else if (isUnsigned)
1913 binOp = spv::OpUDiv;
1914 else
1915 binOp = spv::OpSDiv;
1916 break;
1917 case glslang::EOpMod:
1918 case glslang::EOpModAssign:
1919 if (isFloat)
1920 binOp = spv::OpFMod;
1921 else if (isUnsigned)
1922 binOp = spv::OpUMod;
1923 else
1924 binOp = spv::OpSMod;
1925 break;
1926 case glslang::EOpRightShift:
1927 case glslang::EOpRightShiftAssign:
1928 if (isUnsigned)
1929 binOp = spv::OpShiftRightLogical;
1930 else
1931 binOp = spv::OpShiftRightArithmetic;
1932 break;
1933 case glslang::EOpLeftShift:
1934 case glslang::EOpLeftShiftAssign:
1935 binOp = spv::OpShiftLeftLogical;
1936 break;
1937 case glslang::EOpAnd:
1938 case glslang::EOpAndAssign:
1939 binOp = spv::OpBitwiseAnd;
1940 break;
1941 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06001942 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001943 binOp = spv::OpLogicalAnd;
1944 break;
1945 case glslang::EOpInclusiveOr:
1946 case glslang::EOpInclusiveOrAssign:
1947 binOp = spv::OpBitwiseOr;
1948 break;
1949 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06001950 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001951 binOp = spv::OpLogicalOr;
1952 break;
1953 case glslang::EOpExclusiveOr:
1954 case glslang::EOpExclusiveOrAssign:
1955 binOp = spv::OpBitwiseXor;
1956 break;
1957 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06001958 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06001959 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06001960 break;
1961
1962 case glslang::EOpLessThan:
1963 case glslang::EOpGreaterThan:
1964 case glslang::EOpLessThanEqual:
1965 case glslang::EOpGreaterThanEqual:
1966 case glslang::EOpEqual:
1967 case glslang::EOpNotEqual:
1968 case glslang::EOpVectorEqual:
1969 case glslang::EOpVectorNotEqual:
1970 comparison = true;
1971 break;
1972 default:
1973 break;
1974 }
1975
1976 if (binOp != spv::OpNop) {
1977 if (builder.isMatrix(left) || builder.isMatrix(right)) {
1978 switch (binOp) {
1979 case spv::OpMatrixTimesScalar:
1980 case spv::OpVectorTimesMatrix:
1981 case spv::OpMatrixTimesVector:
1982 case spv::OpMatrixTimesMatrix:
1983 break;
1984 case spv::OpFDiv:
1985 // turn it into a multiply...
1986 assert(builder.isMatrix(left) && builder.isScalar(right));
1987 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
1988 binOp = spv::OpFMul;
1989 break;
1990 default:
1991 spv::MissingFunctionality("binary operation on matrix");
1992 break;
1993 }
1994
1995 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
1996 builder.setPrecision(id, precision);
1997
1998 return id;
1999 }
2000
2001 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002002 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002003 builder.promoteScalar(precision, left, right);
2004
2005 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2006 builder.setPrecision(id, precision);
2007
2008 return id;
2009 }
2010
2011 if (! comparison)
2012 return 0;
2013
2014 // Comparison instructions
2015
2016 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2017 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2018
2019 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2020 }
2021
2022 switch (op) {
2023 case glslang::EOpLessThan:
2024 if (isFloat)
2025 binOp = spv::OpFOrdLessThan;
2026 else if (isUnsigned)
2027 binOp = spv::OpULessThan;
2028 else
2029 binOp = spv::OpSLessThan;
2030 break;
2031 case glslang::EOpGreaterThan:
2032 if (isFloat)
2033 binOp = spv::OpFOrdGreaterThan;
2034 else if (isUnsigned)
2035 binOp = spv::OpUGreaterThan;
2036 else
2037 binOp = spv::OpSGreaterThan;
2038 break;
2039 case glslang::EOpLessThanEqual:
2040 if (isFloat)
2041 binOp = spv::OpFOrdLessThanEqual;
2042 else if (isUnsigned)
2043 binOp = spv::OpULessThanEqual;
2044 else
2045 binOp = spv::OpSLessThanEqual;
2046 break;
2047 case glslang::EOpGreaterThanEqual:
2048 if (isFloat)
2049 binOp = spv::OpFOrdGreaterThanEqual;
2050 else if (isUnsigned)
2051 binOp = spv::OpUGreaterThanEqual;
2052 else
2053 binOp = spv::OpSGreaterThanEqual;
2054 break;
2055 case glslang::EOpEqual:
2056 case glslang::EOpVectorEqual:
2057 if (isFloat)
2058 binOp = spv::OpFOrdEqual;
2059 else
2060 binOp = spv::OpIEqual;
2061 break;
2062 case glslang::EOpNotEqual:
2063 case glslang::EOpVectorNotEqual:
2064 if (isFloat)
2065 binOp = spv::OpFOrdNotEqual;
2066 else
2067 binOp = spv::OpINotEqual;
2068 break;
2069 default:
2070 break;
2071 }
2072
2073 if (binOp != spv::OpNop) {
2074 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2075 builder.setPrecision(id, precision);
2076
2077 return id;
2078 }
2079
2080 return 0;
2081}
2082
2083spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat)
2084{
2085 spv::Op unaryOp = spv::OpNop;
2086 int libCall = -1;
2087
2088 switch (op) {
2089 case glslang::EOpNegative:
2090 if (isFloat)
2091 unaryOp = spv::OpFNegate;
2092 else
2093 unaryOp = spv::OpSNegate;
2094 break;
2095
2096 case glslang::EOpLogicalNot:
2097 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002098 unaryOp = spv::OpLogicalNot;
2099 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002100 case glslang::EOpBitwiseNot:
2101 unaryOp = spv::OpNot;
2102 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002103
John Kessenich140f3df2015-06-26 16:58:36 -06002104 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002105 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002106 break;
2107 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002108 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002109 break;
2110 case glslang::EOpTranspose:
2111 unaryOp = spv::OpTranspose;
2112 break;
2113
2114 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002115 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002116 break;
2117 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002118 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002119 break;
2120 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002121 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002122 break;
2123 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002124 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002125 break;
2126 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002127 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002128 break;
2129 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002130 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002131 break;
2132 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002133 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002134 break;
2135 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002136 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002137 break;
2138
2139 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002140 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002141 break;
2142 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002143 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002144 break;
2145 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002146 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002147 break;
2148 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002149 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002150 break;
2151 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002152 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002153 break;
2154 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002155 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002156 break;
2157
2158 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002159 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002160 break;
2161 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002162 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002163 break;
2164
2165 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002166 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002167 break;
2168 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002169 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002170 break;
2171 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002172 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002173 break;
2174 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002175 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002176 break;
2177 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002178 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002179 break;
2180 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002181 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002182 break;
2183
2184 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002185 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002186 break;
2187 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002188 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002189 break;
2190 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002191 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002192 break;
2193 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002194 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002195 break;
2196 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002197 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002198 break;
2199 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002200 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002201 break;
2202
2203 case glslang::EOpIsNan:
2204 unaryOp = spv::OpIsNan;
2205 break;
2206 case glslang::EOpIsInf:
2207 unaryOp = spv::OpIsInf;
2208 break;
2209
John Kessenich140f3df2015-06-26 16:58:36 -06002210 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002211 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002212 break;
2213 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002214 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002215 break;
2216 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002217 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002218 break;
2219 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002220 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002221 break;
2222 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002223 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002224 break;
2225 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002226 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002227 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002228 case glslang::EOpPackSnorm4x8:
2229 libCall = spv::GLSLstd450PackSnorm4x8;
2230 break;
2231 case glslang::EOpUnpackSnorm4x8:
2232 libCall = spv::GLSLstd450UnpackSnorm4x8;
2233 break;
2234 case glslang::EOpPackUnorm4x8:
2235 libCall = spv::GLSLstd450PackUnorm4x8;
2236 break;
2237 case glslang::EOpUnpackUnorm4x8:
2238 libCall = spv::GLSLstd450UnpackUnorm4x8;
2239 break;
2240 case glslang::EOpPackDouble2x32:
2241 libCall = spv::GLSLstd450PackDouble2x32;
2242 break;
2243 case glslang::EOpUnpackDouble2x32:
2244 libCall = spv::GLSLstd450UnpackDouble2x32;
2245 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002246
2247 case glslang::EOpDPdx:
2248 unaryOp = spv::OpDPdx;
2249 break;
2250 case glslang::EOpDPdy:
2251 unaryOp = spv::OpDPdy;
2252 break;
2253 case glslang::EOpFwidth:
2254 unaryOp = spv::OpFwidth;
2255 break;
2256 case glslang::EOpDPdxFine:
2257 unaryOp = spv::OpDPdxFine;
2258 break;
2259 case glslang::EOpDPdyFine:
2260 unaryOp = spv::OpDPdyFine;
2261 break;
2262 case glslang::EOpFwidthFine:
2263 unaryOp = spv::OpFwidthFine;
2264 break;
2265 case glslang::EOpDPdxCoarse:
2266 unaryOp = spv::OpDPdxCoarse;
2267 break;
2268 case glslang::EOpDPdyCoarse:
2269 unaryOp = spv::OpDPdyCoarse;
2270 break;
2271 case glslang::EOpFwidthCoarse:
2272 unaryOp = spv::OpFwidthCoarse;
2273 break;
2274
2275 case glslang::EOpAny:
2276 unaryOp = spv::OpAny;
2277 break;
2278 case glslang::EOpAll:
2279 unaryOp = spv::OpAll;
2280 break;
2281
2282 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002283 if (isFloat)
2284 libCall = spv::GLSLstd450FAbs;
2285 else
2286 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002287 break;
2288 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002289 if (isFloat)
2290 libCall = spv::GLSLstd450FSign;
2291 else
2292 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002293 break;
2294
John Kessenichfc51d282015-08-19 13:34:18 -06002295 case glslang::EOpAtomicCounterIncrement:
2296 case glslang::EOpAtomicCounterDecrement:
2297 case glslang::EOpAtomicCounter:
2298 {
2299 // Handle all of the atomics in one place, in createAtomicOperation()
2300 std::vector<spv::Id> operands;
2301 operands.push_back(operand);
2302 return createAtomicOperation(op, precision, typeId, operands);
2303 }
2304
2305 case glslang::EOpImageLoad:
2306 unaryOp = spv::OpImageRead;
2307 break;
2308
2309 case glslang::EOpBitFieldReverse:
2310 unaryOp = spv::OpBitReverse;
2311 break;
2312 case glslang::EOpBitCount:
2313 unaryOp = spv::OpBitCount;
2314 break;
2315 case glslang::EOpFindLSB:
2316 libCall = spv::GLSLstd450FindILSB;
2317 break;
2318 case glslang::EOpFindMSB:
2319 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2320 libCall = spv::GLSLstd450FindSMSB;
2321 break;
2322
John Kessenich140f3df2015-06-26 16:58:36 -06002323 default:
2324 return 0;
2325 }
2326
2327 spv::Id id;
2328 if (libCall >= 0) {
2329 std::vector<spv::Id> args;
2330 args.push_back(operand);
2331 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2332 } else
2333 id = builder.createUnaryOp(unaryOp, typeId, operand);
2334
2335 builder.setPrecision(id, precision);
2336
2337 return id;
2338}
2339
2340spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2341{
2342 spv::Op convOp = spv::OpNop;
2343 spv::Id zero = 0;
2344 spv::Id one = 0;
2345
2346 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2347
2348 switch (op) {
2349 case glslang::EOpConvIntToBool:
2350 case glslang::EOpConvUintToBool:
2351 zero = builder.makeUintConstant(0);
2352 zero = makeSmearedConstant(zero, vectorSize);
2353 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2354
2355 case glslang::EOpConvFloatToBool:
2356 zero = builder.makeFloatConstant(0.0F);
2357 zero = makeSmearedConstant(zero, vectorSize);
2358 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2359
2360 case glslang::EOpConvDoubleToBool:
2361 zero = builder.makeDoubleConstant(0.0);
2362 zero = makeSmearedConstant(zero, vectorSize);
2363 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2364
2365 case glslang::EOpConvBoolToFloat:
2366 convOp = spv::OpSelect;
2367 zero = builder.makeFloatConstant(0.0);
2368 one = builder.makeFloatConstant(1.0);
2369 break;
2370 case glslang::EOpConvBoolToDouble:
2371 convOp = spv::OpSelect;
2372 zero = builder.makeDoubleConstant(0.0);
2373 one = builder.makeDoubleConstant(1.0);
2374 break;
2375 case glslang::EOpConvBoolToInt:
2376 zero = builder.makeIntConstant(0);
2377 one = builder.makeIntConstant(1);
2378 convOp = spv::OpSelect;
2379 break;
2380 case glslang::EOpConvBoolToUint:
2381 zero = builder.makeUintConstant(0);
2382 one = builder.makeUintConstant(1);
2383 convOp = spv::OpSelect;
2384 break;
2385
2386 case glslang::EOpConvIntToFloat:
2387 case glslang::EOpConvIntToDouble:
2388 convOp = spv::OpConvertSToF;
2389 break;
2390
2391 case glslang::EOpConvUintToFloat:
2392 case glslang::EOpConvUintToDouble:
2393 convOp = spv::OpConvertUToF;
2394 break;
2395
2396 case glslang::EOpConvDoubleToFloat:
2397 case glslang::EOpConvFloatToDouble:
2398 convOp = spv::OpFConvert;
2399 break;
2400
2401 case glslang::EOpConvFloatToInt:
2402 case glslang::EOpConvDoubleToInt:
2403 convOp = spv::OpConvertFToS;
2404 break;
2405
2406 case glslang::EOpConvUintToInt:
2407 case glslang::EOpConvIntToUint:
2408 convOp = spv::OpBitcast;
2409 break;
2410
2411 case glslang::EOpConvFloatToUint:
2412 case glslang::EOpConvDoubleToUint:
2413 convOp = spv::OpConvertFToU;
2414 break;
2415 default:
2416 break;
2417 }
2418
2419 spv::Id result = 0;
2420 if (convOp == spv::OpNop)
2421 return result;
2422
2423 if (convOp == spv::OpSelect) {
2424 zero = makeSmearedConstant(zero, vectorSize);
2425 one = makeSmearedConstant(one, vectorSize);
2426 result = builder.createTriOp(convOp, destType, operand, one, zero);
2427 } else
2428 result = builder.createUnaryOp(convOp, destType, operand);
2429
2430 builder.setPrecision(result, precision);
2431
2432 return result;
2433}
2434
2435spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2436{
2437 if (vectorSize == 0)
2438 return constant;
2439
2440 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2441 std::vector<spv::Id> components;
2442 for (int c = 0; c < vectorSize; ++c)
2443 components.push_back(constant);
2444 return builder.makeCompositeConstant(vectorTypeId, components);
2445}
2446
John Kessenich426394d2015-07-23 10:22:48 -06002447// For glslang ops that map to SPV atomic opCodes
2448spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands)
2449{
2450 spv::Op opCode = spv::OpNop;
2451
2452 switch (op) {
2453 case glslang::EOpAtomicAdd:
2454 opCode = spv::OpAtomicIAdd;
2455 break;
2456 case glslang::EOpAtomicMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002457 opCode = spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002458 break;
2459 case glslang::EOpAtomicMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002460 opCode = spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002461 break;
2462 case glslang::EOpAtomicAnd:
2463 opCode = spv::OpAtomicAnd;
2464 break;
2465 case glslang::EOpAtomicOr:
2466 opCode = spv::OpAtomicOr;
2467 break;
2468 case glslang::EOpAtomicXor:
2469 opCode = spv::OpAtomicXor;
2470 break;
2471 case glslang::EOpAtomicExchange:
2472 opCode = spv::OpAtomicExchange;
2473 break;
2474 case glslang::EOpAtomicCompSwap:
2475 opCode = spv::OpAtomicCompareExchange;
2476 break;
2477 case glslang::EOpAtomicCounterIncrement:
2478 opCode = spv::OpAtomicIIncrement;
2479 break;
2480 case glslang::EOpAtomicCounterDecrement:
2481 opCode = spv::OpAtomicIDecrement;
2482 break;
2483 case glslang::EOpAtomicCounter:
2484 opCode = spv::OpAtomicLoad;
2485 break;
2486 default:
2487 spv::MissingFunctionality("missing nested atomic");
2488 break;
2489 }
2490
2491 // Sort out the operands
2492 // - mapping from glslang -> SPV
2493 // - there are extra SPV operands with no glslang source
2494 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2495 auto opIt = operands.begin(); // walk the glslang operands
2496 spvAtomicOperands.push_back(*(opIt++));
John Kessenich5e4b1242015-08-06 22:53:06 -06002497 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2498 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
John Kessenich426394d2015-07-23 10:22:48 -06002499
2500 // Add the rest of the operands, skipping the first one, which was dealt with above.
2501 // For some ops, there are none, for some 1, for compare-exchange, 2.
2502 for (; opIt != operands.end(); ++opIt)
2503 spvAtomicOperands.push_back(*opIt);
2504
2505 return builder.createOp(opCode, typeId, spvAtomicOperands);
2506}
2507
John Kessenich5e4b1242015-08-06 22:53:06 -06002508spv::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 -06002509{
John Kessenich5e4b1242015-08-06 22:53:06 -06002510 bool isUnsigned = typeProxy == glslang::EbtUint;
2511 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2512
John Kessenich140f3df2015-06-26 16:58:36 -06002513 spv::Op opCode = spv::OpNop;
2514 int libCall = -1;
2515
2516 switch (op) {
2517 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002518 if (isFloat)
2519 libCall = spv::GLSLstd450FMin;
2520 else if (isUnsigned)
2521 libCall = spv::GLSLstd450UMin;
2522 else
2523 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002524 break;
2525 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002526 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002527 break;
2528 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002529 if (isFloat)
2530 libCall = spv::GLSLstd450FMax;
2531 else if (isUnsigned)
2532 libCall = spv::GLSLstd450UMax;
2533 else
2534 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002535 break;
2536 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002537 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002538 break;
2539 case glslang::EOpDot:
2540 opCode = spv::OpDot;
2541 break;
2542 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002543 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002544 break;
2545
2546 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002547 if (isFloat)
2548 libCall = spv::GLSLstd450FClamp;
2549 else if (isUnsigned)
2550 libCall = spv::GLSLstd450UClamp;
2551 else
2552 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002553 break;
2554 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002555 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002556 break;
2557 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002558 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002559 break;
2560 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002561 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002562 break;
2563
2564 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002565 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002566 break;
2567 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002568 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002569 break;
2570 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002571 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002572 break;
2573 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002574 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002575 break;
2576 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002577 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002578 break;
John Kessenich426394d2015-07-23 10:22:48 -06002579
John Kessenich140f3df2015-06-26 16:58:36 -06002580 default:
2581 return 0;
2582 }
2583
2584 spv::Id id = 0;
2585 if (libCall >= 0)
2586 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2587 else {
2588 switch (operands.size()) {
2589 case 0:
2590 // should all be handled by visitAggregate and createNoArgOperation
2591 assert(0);
2592 return 0;
2593 case 1:
2594 // should all be handled by createUnaryOperation
2595 assert(0);
2596 return 0;
2597 case 2:
2598 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2599 break;
2600 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002601 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002602 break;
2603 default:
2604 // These do not exist yet
2605 assert(0 && "operation with more than 3 operands");
2606 break;
2607 }
2608 }
2609
2610 builder.setPrecision(id, precision);
2611
2612 return id;
2613}
2614
2615// Intrinsics with no arguments, no return value, and no precision.
2616spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2617{
2618 // TODO: get the barrier operands correct
2619
2620 switch (op) {
2621 case glslang::EOpEmitVertex:
2622 builder.createNoResultOp(spv::OpEmitVertex);
2623 return 0;
2624 case glslang::EOpEndPrimitive:
2625 builder.createNoResultOp(spv::OpEndPrimitive);
2626 return 0;
2627 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002628 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2629 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002630 return 0;
2631 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002632 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002633 return 0;
2634 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002635 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002636 return 0;
2637 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002638 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002639 return 0;
2640 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002641 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002642 return 0;
2643 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002644 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002645 return 0;
2646 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002647 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002648 return 0;
2649 default:
2650 spv::MissingFunctionality("operation with no arguments");
2651 return 0;
2652 }
2653}
2654
2655spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2656{
John Kessenich2f273362015-07-18 22:34:27 -06002657 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002658 spv::Id id;
2659 if (symbolValues.end() != iter) {
2660 id = iter->second;
2661 return id;
2662 }
2663
2664 // it was not found, create it
2665 id = createSpvVariable(symbol);
2666 symbolValues[symbol->getId()] = id;
2667
2668 if (! symbol->getType().isStruct()) {
2669 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2670 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2671 if (symbol->getQualifier().hasLocation())
2672 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2673 if (symbol->getQualifier().hasIndex())
2674 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2675 if (symbol->getQualifier().hasComponent())
2676 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2677 if (glslangIntermediate->getXfbMode()) {
2678 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002679 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002680 if (symbol->getQualifier().hasXfbBuffer())
2681 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2682 if (symbol->getQualifier().hasXfbOffset())
2683 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2684 }
2685 }
2686
2687 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2688 if (symbol->getQualifier().hasStream())
2689 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2690 if (symbol->getQualifier().hasSet())
2691 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2692 if (symbol->getQualifier().hasBinding())
2693 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2694 if (glslangIntermediate->getXfbMode()) {
2695 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002696 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002697 if (symbol->getQualifier().hasXfbBuffer())
2698 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2699 }
2700
2701 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002702 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002703 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002704 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002705
2706 if (linkageOnly)
2707 builder.addDecoration(id, spv::DecorationNoStaticUse);
2708
2709 return id;
2710}
2711
2712void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2713{
2714 if (dec != spv::BadValue)
2715 builder.addDecoration(id, dec);
2716}
2717
2718void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2719{
2720 if (dec != spv::BadValue)
2721 builder.addMemberDecoration(id, (unsigned)member, dec);
2722}
2723
2724// Use 'consts' as the flattened glslang source of scalar constants to recursively
2725// build the aggregate SPIR-V constant.
2726//
2727// If there are not enough elements present in 'consts', 0 will be substituted;
2728// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2729//
2730spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2731{
2732 // vector of constants for SPIR-V
2733 std::vector<spv::Id> spvConsts;
2734
2735 // Type is used for struct and array constants
2736 spv::Id typeId = convertGlslangToSpvType(glslangType);
2737
2738 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002739 glslang::TType elementType(glslangType, 0);
2740 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002741 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2742 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002743 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002744 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2745 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2746 } else if (glslangType.getStruct()) {
2747 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2748 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2749 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2750 } else if (glslangType.isVector()) {
2751 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2752 bool zero = nextConst >= consts.size();
2753 switch (glslangType.getBasicType()) {
2754 case glslang::EbtInt:
2755 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2756 break;
2757 case glslang::EbtUint:
2758 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2759 break;
2760 case glslang::EbtFloat:
2761 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2762 break;
2763 case glslang::EbtDouble:
2764 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2765 break;
2766 case glslang::EbtBool:
2767 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2768 break;
2769 default:
2770 spv::MissingFunctionality("constant vector type");
2771 break;
2772 }
2773 ++nextConst;
2774 }
2775 } else {
2776 // we have a non-aggregate (scalar) constant
2777 bool zero = nextConst >= consts.size();
2778 spv::Id scalar = 0;
2779 switch (glslangType.getBasicType()) {
2780 case glslang::EbtInt:
2781 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2782 break;
2783 case glslang::EbtUint:
2784 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2785 break;
2786 case glslang::EbtFloat:
2787 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2788 break;
2789 case glslang::EbtDouble:
2790 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2791 break;
2792 case glslang::EbtBool:
2793 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2794 break;
2795 default:
2796 spv::MissingFunctionality("constant scalar type");
2797 break;
2798 }
2799 ++nextConst;
2800 return scalar;
2801 }
2802
2803 return builder.makeCompositeConstant(typeId, spvConsts);
2804}
2805
2806}; // end anonymous namespace
2807
2808namespace glslang {
2809
John Kessenich68d78fd2015-07-12 19:28:10 -06002810void GetSpirvVersion(std::string& version)
2811{
John Kessenich9e55f632015-07-15 10:03:39 -06002812 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002813 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002814 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002815 version = buf;
2816}
2817
John Kessenich140f3df2015-06-26 16:58:36 -06002818// Write SPIR-V out to a binary file
2819void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
2820{
2821 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06002822 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06002823 for (int i = 0; i < (int)spirv.size(); ++i) {
2824 unsigned int word = spirv[i];
2825 out.write((const char*)&word, 4);
2826 }
2827 out.close();
2828}
2829
2830//
2831// Set up the glslang traversal
2832//
2833void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
2834{
2835 TIntermNode* root = intermediate.getTreeRoot();
2836
2837 if (root == 0)
2838 return;
2839
2840 glslang::GetThreadPoolAllocator().push();
2841
2842 TGlslangToSpvTraverser it(&intermediate);
2843
2844 root->traverse(&it);
2845
2846 it.dumpSpv(spirv);
2847
2848 glslang::GetThreadPoolAllocator().pop();
2849}
2850
2851}; // end namespace glslang