blob: 4b8c93309e2630b8a4560ddfe1bd25fbaa05c395 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
2//Copyright (C) 2014 LunarG, Inc.
3//
4//All rights reserved.
5//
6//Redistribution and use in source and binary forms, with or without
7//modification, are permitted provided that the following conditions
8//are met:
9//
10// Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//
13// Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following
15// disclaimer in the documentation and/or other materials provided
16// with the distribution.
17//
18// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19// contributors may be used to endorse or promote products derived
20// from this software without specific prior written permission.
21//
22//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33//POSSIBILITY OF SUCH DAMAGE.
34
35//
36// Author: John Kessenich, LunarG
37//
38// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
46 #include "GLSL.std.450.h"
47}
John Kessenich140f3df2015-06-26 16:58:36 -060048
49// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020050#include "../glslang/MachineIndependent/localintermediate.h"
51#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060053
54#include <string>
55#include <map>
56#include <list>
57#include <vector>
58#include <stack>
59#include <fstream>
60
61namespace {
62
63const int GlslangMagic = 0x51a;
64
65//
66// The main holder of information for translating glslang to SPIR-V.
67//
68// Derives from the AST walking base class.
69//
70class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
71public:
72 TGlslangToSpvTraverser(const glslang::TIntermediate*);
73 virtual ~TGlslangToSpvTraverser();
74
75 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
76 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
77 void visitConstantUnion(glslang::TIntermConstantUnion*);
78 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
79 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
80 void visitSymbol(glslang::TIntermSymbol* symbol);
81 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
82 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
83 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
84
85 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
86
87protected:
88 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
89 spv::Id getSampledType(const glslang::TSampler&);
90 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich5e4b1242015-08-06 22:53:06 -060091 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060092
93 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
94 void makeFunctions(const glslang::TIntermSequence&);
95 void makeGlobalInitializers(const glslang::TIntermSequence&);
96 void visitFunctions(const glslang::TIntermSequence&);
97 void handleFunctionEntry(const glslang::TIntermAggregate* node);
98 void translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments);
99 spv::Id handleBuiltInFunctionCall(const glslang::TIntermAggregate*);
John Kessenich5e4b1242015-08-06 22:53:06 -0600100 spv::Id handleTextureCall(spv::Decoration precision, glslang::TOperator, spv::Id typeId, glslang::TSampler, std::vector<spv::Id>& idArguments);
John Kessenich140f3df2015-06-26 16:58:36 -0600101 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
102
103 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
104 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat);
105 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
106 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich426394d2015-07-23 10:22:48 -0600107 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600108 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 -0600109 spv::Id createNoArgOperation(glslang::TOperator op);
110 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
111 void addDecoration(spv::Id id, spv::Decoration dec);
112 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
113 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
114
115 spv::Function* shaderEntry;
116 int sequenceDepth;
117
118 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
119 spv::Builder builder;
120 bool inMain;
121 bool mainTerminated;
122 bool linkageOnly;
123 const glslang::TIntermediate* glslangIntermediate;
124 spv::Id stdBuiltins;
125
John Kessenich2f273362015-07-18 22:34:27 -0600126 std::unordered_map<int, spv::Id> symbolValues;
127 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
128 std::unordered_map<std::string, spv::Function*> functionMap;
129 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
130 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 -0600131 std::stack<bool> breakForLoop; // false means break for switch
132 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
133};
134
135//
136// Helper functions for translating glslang representations to SPIR-V enumerants.
137//
138
139// Translate glslang profile to SPIR-V source language.
140spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
141{
142 switch (profile) {
143 case ENoProfile:
144 case ECoreProfile:
145 case ECompatibilityProfile:
146 return spv::SourceLanguageGLSL;
147 case EEsProfile:
148 return spv::SourceLanguageESSL;
149 default:
150 return spv::SourceLanguageUnknown;
151 }
152}
153
154// Translate glslang language (stage) to SPIR-V execution model.
155spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
156{
157 switch (stage) {
158 case EShLangVertex: return spv::ExecutionModelVertex;
159 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
160 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
161 case EShLangGeometry: return spv::ExecutionModelGeometry;
162 case EShLangFragment: return spv::ExecutionModelFragment;
163 case EShLangCompute: return spv::ExecutionModelGLCompute;
164 default:
165 spv::MissingFunctionality("GLSL stage");
166 return spv::ExecutionModelFragment;
167 }
168}
169
170// Translate glslang type to SPIR-V storage class.
171spv::StorageClass TranslateStorageClass(const glslang::TType& type)
172{
173 if (type.getQualifier().isPipeInput())
174 return spv::StorageClassInput;
175 else if (type.getQualifier().isPipeOutput())
176 return spv::StorageClassOutput;
177 else if (type.getQualifier().isUniformOrBuffer()) {
178 if (type.getBasicType() == glslang::EbtBlock)
179 return spv::StorageClassUniform;
180 else
181 return spv::StorageClassUniformConstant;
182 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
183 } else {
184 switch (type.getQualifier().storage) {
185 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
186 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
187 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
188 case glslang::EvqTemporary: return spv::StorageClassFunction;
189 default:
190 spv::MissingFunctionality("unknown glslang storage class");
191 return spv::StorageClassFunction;
192 }
193 }
194}
195
196// Translate glslang sampler type to SPIR-V dimensionality.
197spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
198{
199 switch (sampler.dim) {
200 case glslang::Esd1D: return spv::Dim1D;
201 case glslang::Esd2D: return spv::Dim2D;
202 case glslang::Esd3D: return spv::Dim3D;
203 case glslang::EsdCube: return spv::DimCube;
204 case glslang::EsdRect: return spv::DimRect;
205 case glslang::EsdBuffer: return spv::DimBuffer;
206 default:
207 spv::MissingFunctionality("unknown sampler dimension");
208 return spv::Dim2D;
209 }
210}
211
212// Translate glslang type to SPIR-V precision decorations.
213spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
214{
215 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600216 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
217 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
218 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600219 default:
220 return spv::NoPrecision;
221 }
222}
223
224// Translate glslang type to SPIR-V block decorations.
225spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
226{
227 if (type.getBasicType() == glslang::EbtBlock) {
228 switch (type.getQualifier().storage) {
229 case glslang::EvqUniform: return spv::DecorationBlock;
230 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
231 case glslang::EvqVaryingIn: return spv::DecorationBlock;
232 case glslang::EvqVaryingOut: return spv::DecorationBlock;
233 default:
234 spv::MissingFunctionality("kind of block");
235 break;
236 }
237 }
238
239 return (spv::Decoration)spv::BadValue;
240}
241
242// Translate glslang type to SPIR-V layout decorations.
243spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
244{
245 if (type.isMatrix()) {
246 switch (type.getQualifier().layoutMatrix) {
247 case glslang::ElmRowMajor:
248 return spv::DecorationRowMajor;
249 default:
250 return spv::DecorationColMajor;
251 }
252 } else {
253 switch (type.getBasicType()) {
254 default:
255 return (spv::Decoration)spv::BadValue;
256 break;
257 case glslang::EbtBlock:
258 switch (type.getQualifier().storage) {
259 case glslang::EvqUniform:
260 case glslang::EvqBuffer:
261 switch (type.getQualifier().layoutPacking) {
262 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600263 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
264 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600265 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600266 }
267 case glslang::EvqVaryingIn:
268 case glslang::EvqVaryingOut:
269 if (type.getQualifier().layoutPacking != glslang::ElpNone)
270 spv::MissingFunctionality("in/out block layout");
271 return (spv::Decoration)spv::BadValue;
272 default:
273 spv::MissingFunctionality("block storage qualification");
274 return (spv::Decoration)spv::BadValue;
275 }
276 }
277 }
278}
279
280// Translate glslang type to SPIR-V interpolation decorations.
281spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
282{
283 if (type.getQualifier().smooth)
284 return spv::DecorationSmooth;
285 if (type.getQualifier().nopersp)
286 return spv::DecorationNoperspective;
287 else if (type.getQualifier().patch)
288 return spv::DecorationPatch;
289 else if (type.getQualifier().flat)
290 return spv::DecorationFlat;
291 else if (type.getQualifier().centroid)
292 return spv::DecorationCentroid;
293 else if (type.getQualifier().sample)
294 return spv::DecorationSample;
295 else
296 return (spv::Decoration)spv::BadValue;
297}
298
299// If glslang type is invaraiant, return SPIR-V invariant decoration.
300spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
301{
302 if (type.getQualifier().invariant)
303 return spv::DecorationInvariant;
304 else
305 return (spv::Decoration)spv::BadValue;
306}
307
308// Translate glslang built-in variable to SPIR-V built in decoration.
309spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
310{
311 switch (builtIn) {
312 case glslang::EbvPosition: return spv::BuiltInPosition;
313 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600314 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
315 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
316 case glslang::EbvVertexId: return spv::BuiltInVertexId;
317 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
318 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
319 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
320 case glslang::EbvLayer: return spv::BuiltInLayer;
321 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
322 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
323 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
324 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
325 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
326 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
327 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
328 case glslang::EbvFace: return spv::BuiltInFrontFacing;
329 case glslang::EbvSampleId: return spv::BuiltInSampleId;
330 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
331 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
332 case glslang::EbvFragColor: return spv::BuiltInFragColor;
333 case glslang::EbvFragData: return spv::BuiltInFragColor;
334 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
335 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
336 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
337 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
338 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
339 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
340 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
341 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
342 default: return (spv::BuiltIn)spv::BadValue;
343 }
344}
345
346//
347// Implement the TGlslangToSpvTraverser class.
348//
349
350TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
351 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
352 builder(GlslangMagic),
353 inMain(false), mainTerminated(false), linkageOnly(false),
354 glslangIntermediate(glslangIntermediate)
355{
356 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
357
358 builder.clearAccessChain();
359 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
360 stdBuiltins = builder.import("GLSL.std.450");
361 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
362 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600363 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600364
365 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600366 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
367 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 builder.addSourceExtension(it->c_str());
369
370 // Add the top-level modes for this shader.
371
372 if (glslangIntermediate->getXfbMode())
373 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
374
375 unsigned int mode;
376 switch (glslangIntermediate->getStage()) {
377 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600378 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600379 break;
380
381 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600382 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
384 break;
385
386 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600387 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600388 switch (glslangIntermediate->getInputPrimitive()) {
389 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
390 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
391 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
392 default: mode = spv::BadValue; break;
393 }
394 if (mode != spv::BadValue)
395 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
396
397 // TODO
398 //builder.addExecutionMode(spv::VertexSpacingMdName, glslangIntermediate->getVertexSpacing());
399 //builder.addExecutionMode(spv::VertexOrderMdName, glslangIntermediate->getVertexOrder());
400 //builder.addExecutionMode(spv::PointModeMdName, glslangIntermediate->getPointMode());
401 break;
402
403 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600404 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600405 switch (glslangIntermediate->getInputPrimitive()) {
406 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
407 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
408 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
409 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
410 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
411 default: mode = spv::BadValue; break;
412 }
413 if (mode != spv::BadValue)
414 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
415 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
416
417 switch (glslangIntermediate->getOutputPrimitive()) {
418 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
419 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
420 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
421 default: mode = spv::BadValue; break;
422 }
423 if (mode != spv::BadValue)
424 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
425 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
426 break;
427
428 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600429 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600430 if (glslangIntermediate->getPixelCenterInteger())
431 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
432 if (glslangIntermediate->getOriginUpperLeft())
433 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600434 else
435 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kessenich140f3df2015-06-26 16:58:36 -0600436 break;
437
438 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600439 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600440 break;
441
442 default:
443 break;
444 }
445
446}
447
448TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
449{
450 if (! mainTerminated) {
451 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
452 builder.setBuildPoint(lastMainBlock);
453 builder.leaveFunction(true);
454 }
455}
456
457//
458// Implement the traversal functions.
459//
460// Return true from interior nodes to have the external traversal
461// continue on to children. Return false if children were
462// already processed.
463//
464
465//
466// Symbols can turn into
467// - uniform/input reads
468// - output writes
469// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
470// - something simple that degenerates into the last bullet
471//
472void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
473{
474 // getSymbolId() will set up all the IO decorations on the first call.
475 // Formal function parameters were mapped during makeFunctions().
476 spv::Id id = getSymbolId(symbol);
477
478 if (! linkageOnly) {
479 // Prepare to generate code for the access
480
481 // L-value chains will be computed left to right. We're on the symbol now,
482 // which is the left-most part of the access chain, so now is "clear" time,
483 // followed by setting the base.
484 builder.clearAccessChain();
485
486 // For now, we consider all user variables as being in memory, so they are pointers,
487 // except for "const in" arguments to a function, which are an intermediate object.
488 // See comments in handleUserFunctionCall().
489 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
490 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
491 builder.setAccessChainRValue(id);
492 else
493 builder.setAccessChainLValue(id);
494 }
495}
496
497bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
498{
499 // First, handle special cases
500 switch (node->getOp()) {
501 case glslang::EOpAssign:
502 case glslang::EOpAddAssign:
503 case glslang::EOpSubAssign:
504 case glslang::EOpMulAssign:
505 case glslang::EOpVectorTimesMatrixAssign:
506 case glslang::EOpVectorTimesScalarAssign:
507 case glslang::EOpMatrixTimesScalarAssign:
508 case glslang::EOpMatrixTimesMatrixAssign:
509 case glslang::EOpDivAssign:
510 case glslang::EOpModAssign:
511 case glslang::EOpAndAssign:
512 case glslang::EOpInclusiveOrAssign:
513 case glslang::EOpExclusiveOrAssign:
514 case glslang::EOpLeftShiftAssign:
515 case glslang::EOpRightShiftAssign:
516 // A bin-op assign "a += b" means the same thing as "a = a + b"
517 // where a is evaluated before b. For a simple assignment, GLSL
518 // says to evaluate the left before the right. So, always, left
519 // node then right node.
520 {
521 // get the left l-value, save it away
522 builder.clearAccessChain();
523 node->getLeft()->traverse(this);
524 spv::Builder::AccessChain lValue = builder.getAccessChain();
525
526 // evaluate the right
527 builder.clearAccessChain();
528 node->getRight()->traverse(this);
529 spv::Id rValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
530
531 if (node->getOp() != glslang::EOpAssign) {
532 // the left is also an r-value
533 builder.setAccessChain(lValue);
534 spv::Id leftRValue = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
535
536 // do the operation
537 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
538 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
539 node->getType().getBasicType());
540
541 // these all need their counterparts in createBinaryOperation()
542 if (rValue == 0)
543 spv::MissingFunctionality("createBinaryOperation");
544 }
545
546 // store the result
547 builder.setAccessChain(lValue);
548 builder.accessChainStore(rValue);
549
550 // assignments are expressions having an rValue after they are evaluated...
551 builder.clearAccessChain();
552 builder.setAccessChainRValue(rValue);
553 }
554 return false;
555 case glslang::EOpIndexDirect:
556 case glslang::EOpIndexDirectStruct:
557 {
558 // Get the left part of the access chain.
559 node->getLeft()->traverse(this);
560
561 // Add the next element in the chain
562
563 int index = 0;
564 if (node->getRight()->getAsConstantUnion() == 0)
565 spv::MissingFunctionality("direct index without a constant node");
566 else
567 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
568
569 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
570 // This may be, e.g., an anonymous block-member selection, which generally need
571 // index remapping due to hidden members in anonymous blocks.
572 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
573 if (remapper.size() == 0)
574 spv::MissingFunctionality("block without member remapping");
575 else
576 index = remapper[index];
577 }
578
579 if (! node->getLeft()->getType().isArray() &&
580 node->getLeft()->getType().isVector() &&
581 node->getOp() == glslang::EOpIndexDirect) {
582 // This is essentially a hard-coded vector swizzle of size 1,
583 // so short circuit the access-chain stuff with a swizzle.
584 std::vector<unsigned> swizzle;
585 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
586 builder.accessChainPushSwizzle(swizzle);
587 } else {
588 // normal case for indexing array or structure or block
589 builder.accessChainPush(builder.makeIntConstant(index), convertGlslangToSpvType(node->getType()));
590 }
591 }
592 return false;
593 case glslang::EOpIndexIndirect:
594 {
595 // Structure or array or vector indirection.
596 // Will use native SPIR-V access-chain for struct and array indirection;
597 // matrices are arrays of vectors, so will also work for a matrix.
598 // Will use the access chain's 'component' for variable index into a vector.
599
600 // This adapter is building access chains left to right.
601 // Set up the access chain to the left.
602 node->getLeft()->traverse(this);
603
604 // save it so that computing the right side doesn't trash it
605 spv::Builder::AccessChain partial = builder.getAccessChain();
606
607 // compute the next index in the chain
608 builder.clearAccessChain();
609 node->getRight()->traverse(this);
610 spv::Id index = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
611
612 // restore the saved access chain
613 builder.setAccessChain(partial);
614
615 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
616 builder.accessChainPushComponent(index);
617 else
618 builder.accessChainPush(index, convertGlslangToSpvType(node->getType()));
619 }
620 return false;
621 case glslang::EOpVectorSwizzle:
622 {
623 node->getLeft()->traverse(this);
624 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
625 std::vector<unsigned> swizzle;
626 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
627 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
628 builder.accessChainPushSwizzle(swizzle);
629 }
630 return false;
631 default:
632 break;
633 }
634
635 // Assume generic binary op...
636
637 // Get the operands
638 builder.clearAccessChain();
639 node->getLeft()->traverse(this);
640 spv::Id left = builder.accessChainLoad(TranslatePrecisionDecoration(node->getLeft()->getType()));
641
642 builder.clearAccessChain();
643 node->getRight()->traverse(this);
644 spv::Id right = builder.accessChainLoad(TranslatePrecisionDecoration(node->getRight()->getType()));
645
646 spv::Id result;
647 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
648
649 result = createBinaryOperation(node->getOp(), precision,
650 convertGlslangToSpvType(node->getType()), left, right,
651 node->getLeft()->getType().getBasicType());
652
653 if (! result) {
654 spv::MissingFunctionality("glslang binary operation");
655 } else {
656 builder.clearAccessChain();
657 builder.setAccessChainRValue(result);
658
659 return false;
660 }
661
662 return true;
663}
664
665bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
666{
667 builder.clearAccessChain();
668 node->getOperand()->traverse(this);
669 spv::Id operand = builder.accessChainLoad(TranslatePrecisionDecoration(node->getOperand()->getType()));
670
671 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
672
673 // it could be a conversion
674 spv::Id result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
675
676 // if not, then possibly an operation
677 if (! result)
678 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getBasicType() == glslang::EbtFloat || node->getBasicType() == glslang::EbtDouble);
679
680 if (result) {
681 builder.clearAccessChain();
682 builder.setAccessChainRValue(result);
683
684 return false; // done with this node
685 }
686
687 // it must be a special case, check...
688 switch (node->getOp()) {
689 case glslang::EOpPostIncrement:
690 case glslang::EOpPostDecrement:
691 case glslang::EOpPreIncrement:
692 case glslang::EOpPreDecrement:
693 {
694 // we need the integer value "1" or the floating point "1.0" to add/subtract
695 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
696 builder.makeFloatConstant(1.0F) :
697 builder.makeIntConstant(1);
698 glslang::TOperator op;
699 if (node->getOp() == glslang::EOpPreIncrement ||
700 node->getOp() == glslang::EOpPostIncrement)
701 op = glslang::EOpAdd;
702 else
703 op = glslang::EOpSub;
704
705 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
706 convertGlslangToSpvType(node->getType()), operand, one,
707 node->getType().getBasicType());
708 if (result == 0)
709 spv::MissingFunctionality("createBinaryOperation for unary");
710
711 // The result of operation is always stored, but conditionally the
712 // consumed result. The consumed result is always an r-value.
713 builder.accessChainStore(result);
714 builder.clearAccessChain();
715 if (node->getOp() == glslang::EOpPreIncrement ||
716 node->getOp() == glslang::EOpPreDecrement)
717 builder.setAccessChainRValue(result);
718 else
719 builder.setAccessChainRValue(operand);
720 }
721
722 return false;
723
724 case glslang::EOpEmitStreamVertex:
725 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
726 return false;
727 case glslang::EOpEndStreamPrimitive:
728 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
729 return false;
730
John Kessenich426394d2015-07-23 10:22:48 -0600731 case glslang::EOpAtomicCounterIncrement:
732 case glslang::EOpAtomicCounterDecrement:
733 case glslang::EOpAtomicCounter:
734 {
735 // Handle all of the atomics in one place, in createAtomicOperation()
736 std::vector<spv::Id> operands;
737 operands.push_back(operand);
738 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands);
739 return false;
740 }
John Kessenich140f3df2015-06-26 16:58:36 -0600741 default:
742 spv::MissingFunctionality("glslang unary");
743 break;
744 }
745
746 return true;
747}
748
749bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
750{
751 spv::Id result;
752 glslang::TOperator binOp = glslang::EOpNull;
753 bool reduceComparison = true;
754 bool isMatrix = false;
755 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600756 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600757
758 assert(node->getOp());
759
760 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
761
762 switch (node->getOp()) {
763 case glslang::EOpSequence:
764 {
765 if (preVisit)
766 ++sequenceDepth;
767 else
768 --sequenceDepth;
769
770 if (sequenceDepth == 1) {
771 // If this is the parent node of all the functions, we want to see them
772 // early, so all call points have actual SPIR-V functions to reference.
773 // In all cases, still let the traverser visit the children for us.
774 makeFunctions(node->getAsAggregate()->getSequence());
775
776 // Also, we want all globals initializers to go into the entry of main(), before
777 // anything else gets there, so visit out of order, doing them all now.
778 makeGlobalInitializers(node->getAsAggregate()->getSequence());
779
780 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
781 // so do them manually.
782 visitFunctions(node->getAsAggregate()->getSequence());
783
784 return false;
785 }
786
787 return true;
788 }
789 case glslang::EOpLinkerObjects:
790 {
791 if (visit == glslang::EvPreVisit)
792 linkageOnly = true;
793 else
794 linkageOnly = false;
795
796 return true;
797 }
798 case glslang::EOpComma:
799 {
800 // processing from left to right naturally leaves the right-most
801 // lying around in the access chain
802 glslang::TIntermSequence& glslangOperands = node->getSequence();
803 for (int i = 0; i < (int)glslangOperands.size(); ++i)
804 glslangOperands[i]->traverse(this);
805
806 return false;
807 }
808 case glslang::EOpFunction:
809 if (visit == glslang::EvPreVisit) {
810 if (isShaderEntrypoint(node)) {
811 inMain = true;
812 builder.setBuildPoint(shaderEntry->getLastBlock());
813 } else {
814 handleFunctionEntry(node);
815 }
816 } else {
817 if (inMain)
818 mainTerminated = true;
819 builder.leaveFunction(inMain);
820 inMain = false;
821 }
822
823 return true;
824 case glslang::EOpParameters:
825 // Parameters will have been consumed by EOpFunction processing, but not
826 // the body, so we still visited the function node's children, making this
827 // child redundant.
828 return false;
829 case glslang::EOpFunctionCall:
830 {
831 if (node->isUserDefined())
832 result = handleUserFunctionCall(node);
833 else
834 result = handleBuiltInFunctionCall(node);
835
836 if (! result) {
837 spv::MissingFunctionality("glslang function call");
838 glslang::TConstUnionArray emptyConsts;
839 int nextConst = 0;
840 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
841 }
842 builder.clearAccessChain();
843 builder.setAccessChainRValue(result);
844
845 return false;
846 }
847 case glslang::EOpConstructMat2x2:
848 case glslang::EOpConstructMat2x3:
849 case glslang::EOpConstructMat2x4:
850 case glslang::EOpConstructMat3x2:
851 case glslang::EOpConstructMat3x3:
852 case glslang::EOpConstructMat3x4:
853 case glslang::EOpConstructMat4x2:
854 case glslang::EOpConstructMat4x3:
855 case glslang::EOpConstructMat4x4:
856 case glslang::EOpConstructDMat2x2:
857 case glslang::EOpConstructDMat2x3:
858 case glslang::EOpConstructDMat2x4:
859 case glslang::EOpConstructDMat3x2:
860 case glslang::EOpConstructDMat3x3:
861 case glslang::EOpConstructDMat3x4:
862 case glslang::EOpConstructDMat4x2:
863 case glslang::EOpConstructDMat4x3:
864 case glslang::EOpConstructDMat4x4:
865 isMatrix = true;
866 // fall through
867 case glslang::EOpConstructFloat:
868 case glslang::EOpConstructVec2:
869 case glslang::EOpConstructVec3:
870 case glslang::EOpConstructVec4:
871 case glslang::EOpConstructDouble:
872 case glslang::EOpConstructDVec2:
873 case glslang::EOpConstructDVec3:
874 case glslang::EOpConstructDVec4:
875 case glslang::EOpConstructBool:
876 case glslang::EOpConstructBVec2:
877 case glslang::EOpConstructBVec3:
878 case glslang::EOpConstructBVec4:
879 case glslang::EOpConstructInt:
880 case glslang::EOpConstructIVec2:
881 case glslang::EOpConstructIVec3:
882 case glslang::EOpConstructIVec4:
883 case glslang::EOpConstructUint:
884 case glslang::EOpConstructUVec2:
885 case glslang::EOpConstructUVec3:
886 case glslang::EOpConstructUVec4:
887 case glslang::EOpConstructStruct:
888 {
889 std::vector<spv::Id> arguments;
890 translateArguments(node->getSequence(), arguments);
891 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
892 spv::Id constructed;
893 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
894 std::vector<spv::Id> constituents;
895 for (int c = 0; c < (int)arguments.size(); ++c)
896 constituents.push_back(arguments[c]);
897 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
898 } else {
899 if (isMatrix)
900 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
901 else
902 constructed = builder.createConstructor(precision, arguments, resultTypeId);
903 }
904
905 builder.clearAccessChain();
906 builder.setAccessChainRValue(constructed);
907
908 return false;
909 }
910
911 // These six are component-wise compares with component-wise results.
912 // Forward on to createBinaryOperation(), requesting a vector result.
913 case glslang::EOpLessThan:
914 case glslang::EOpGreaterThan:
915 case glslang::EOpLessThanEqual:
916 case glslang::EOpGreaterThanEqual:
917 case glslang::EOpVectorEqual:
918 case glslang::EOpVectorNotEqual:
919 {
920 // Map the operation to a binary
921 binOp = node->getOp();
922 reduceComparison = false;
923 switch (node->getOp()) {
924 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
925 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
926 default: binOp = node->getOp(); break;
927 }
928
929 break;
930 }
931 case glslang::EOpMul:
932 // compontent-wise matrix multiply
933 binOp = glslang::EOpMul;
934 break;
935 case glslang::EOpOuterProduct:
936 // two vectors multiplied to make a matrix
937 binOp = glslang::EOpOuterProduct;
938 break;
939 case glslang::EOpDot:
940 {
941 // for scalar dot product, use multiply
942 glslang::TIntermSequence& glslangOperands = node->getSequence();
943 if (! glslangOperands[0]->getAsTyped()->isVector())
944 binOp = glslang::EOpMul;
945 break;
946 }
947 case glslang::EOpMod:
948 // when an aggregate, this is the floating-point mod built-in function,
949 // which can be emitted by the one in createBinaryOperation()
950 binOp = glslang::EOpMod;
951 break;
952 case glslang::EOpArrayLength:
953 {
954 glslang::TIntermTyped* typedNode = node->getSequence()[0]->getAsTyped();
955 assert(typedNode);
John Kessenich65c78a02015-08-10 17:08:55 -0600956 spv::Id length = builder.makeIntConstant(typedNode->getType().getOuterArraySize());
John Kessenich140f3df2015-06-26 16:58:36 -0600957
958 builder.clearAccessChain();
959 builder.setAccessChainRValue(length);
960
961 return false;
962 }
963 case glslang::EOpEmitVertex:
964 case glslang::EOpEndPrimitive:
965 case glslang::EOpBarrier:
966 case glslang::EOpMemoryBarrier:
967 case glslang::EOpMemoryBarrierAtomicCounter:
968 case glslang::EOpMemoryBarrierBuffer:
969 case glslang::EOpMemoryBarrierImage:
970 case glslang::EOpMemoryBarrierShared:
971 case glslang::EOpGroupMemoryBarrier:
972 noReturnValue = true;
973 // These all have 0 operands and will naturally finish up in the code below for 0 operands
974 break;
975
John Kessenich426394d2015-07-23 10:22:48 -0600976 case glslang::EOpAtomicAdd:
977 case glslang::EOpAtomicMin:
978 case glslang::EOpAtomicMax:
979 case glslang::EOpAtomicAnd:
980 case glslang::EOpAtomicOr:
981 case glslang::EOpAtomicXor:
982 case glslang::EOpAtomicExchange:
983 case glslang::EOpAtomicCompSwap:
984 atomic = true;
985 break;
986
John Kessenich140f3df2015-06-26 16:58:36 -0600987 default:
988 break;
989 }
990
991 //
992 // See if it maps to a regular operation.
993 //
John Kessenich140f3df2015-06-26 16:58:36 -0600994 if (binOp != glslang::EOpNull) {
995 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
996 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
997 assert(left && right);
998
999 builder.clearAccessChain();
1000 left->traverse(this);
1001 spv::Id leftId = builder.accessChainLoad(TranslatePrecisionDecoration(left->getType()));
1002
1003 builder.clearAccessChain();
1004 right->traverse(this);
1005 spv::Id rightId = builder.accessChainLoad(TranslatePrecisionDecoration(right->getType()));
1006
1007 result = createBinaryOperation(binOp, precision,
1008 convertGlslangToSpvType(node->getType()), leftId, rightId,
1009 left->getType().getBasicType(), reduceComparison);
1010
1011 // code above should only make binOp that exists in createBinaryOperation
1012 if (result == 0)
1013 spv::MissingFunctionality("createBinaryOperation for aggregate");
1014
1015 builder.clearAccessChain();
1016 builder.setAccessChainRValue(result);
1017
1018 return false;
1019 }
1020
John Kessenich426394d2015-07-23 10:22:48 -06001021 //
1022 // Create the list of operands.
1023 //
John Kessenich140f3df2015-06-26 16:58:36 -06001024 glslang::TIntermSequence& glslangOperands = node->getSequence();
1025 std::vector<spv::Id> operands;
1026 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1027 builder.clearAccessChain();
1028 glslangOperands[arg]->traverse(this);
1029
1030 // special case l-value operands; there are just a few
1031 bool lvalue = false;
1032 switch (node->getOp()) {
1033 //case glslang::EOpFrexp:
1034 case glslang::EOpModf:
1035 if (arg == 1)
1036 lvalue = true;
1037 break;
1038 //case glslang::EOpUAddCarry:
1039 //case glslang::EOpUSubBorrow:
1040 //case glslang::EOpUMulExtended:
1041 default:
1042 break;
1043 }
1044 if (lvalue)
1045 operands.push_back(builder.accessChainGetLValue());
1046 else
1047 operands.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangOperands[arg]->getAsTyped()->getType())));
1048 }
John Kessenich426394d2015-07-23 10:22:48 -06001049
1050 if (atomic) {
1051 // Handle all atomics
1052 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands);
1053 } else {
1054 // Pass through to generic operations.
1055 switch (glslangOperands.size()) {
1056 case 0:
1057 result = createNoArgOperation(node->getOp());
1058 break;
1059 case 1:
1060 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType() == glslang::EbtFloat || node->getType().getBasicType() == glslang::EbtDouble);
1061 break;
1062 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001063 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001064 break;
1065 }
John Kessenich140f3df2015-06-26 16:58:36 -06001066 }
1067
1068 if (noReturnValue)
1069 return false;
1070
1071 if (! result) {
1072 spv::MissingFunctionality("glslang aggregate");
1073 return true;
1074 } else {
1075 builder.clearAccessChain();
1076 builder.setAccessChainRValue(result);
1077 return false;
1078 }
1079}
1080
1081bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1082{
1083 // This path handles both if-then-else and ?:
1084 // The if-then-else has a node type of void, while
1085 // ?: has a non-void node type
1086 spv::Id result = 0;
1087 if (node->getBasicType() != glslang::EbtVoid) {
1088 // don't handle this as just on-the-fly temporaries, because there will be two names
1089 // and better to leave SSA to later passes
1090 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1091 }
1092
1093 // emit the condition before doing anything with selection
1094 node->getCondition()->traverse(this);
1095
1096 // make an "if" based on the value created by the condition
1097 spv::Builder::If ifBuilder(builder.accessChainLoad(spv::NoPrecision), builder);
1098
1099 if (node->getTrueBlock()) {
1100 // emit the "then" statement
1101 node->getTrueBlock()->traverse(this);
1102 if (result)
1103 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getTrueBlock()->getAsTyped()->getType())), result);
1104 }
1105
1106 if (node->getFalseBlock()) {
1107 ifBuilder.makeBeginElse();
1108 // emit the "else" statement
1109 node->getFalseBlock()->traverse(this);
1110 if (result)
1111 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getFalseBlock()->getAsTyped()->getType())), result);
1112 }
1113
1114 ifBuilder.makeEndIf();
1115
1116 if (result) {
1117 // GLSL only has r-values as the result of a :?, but
1118 // if we have an l-value, that can be more efficient if it will
1119 // become the base of a complex r-value expression, because the
1120 // next layer copies r-values into memory to use the access-chain mechanism
1121 builder.clearAccessChain();
1122 builder.setAccessChainLValue(result);
1123 }
1124
1125 return false;
1126}
1127
1128bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1129{
1130 // emit and get the condition before doing anything with switch
1131 node->getCondition()->traverse(this);
1132 spv::Id selector = builder.accessChainLoad(TranslatePrecisionDecoration(node->getCondition()->getAsTyped()->getType()));
1133
1134 // browse the children to sort out code segments
1135 int defaultSegment = -1;
1136 std::vector<TIntermNode*> codeSegments;
1137 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1138 std::vector<int> caseValues;
1139 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1140 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1141 TIntermNode* child = *c;
1142 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001143 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001144 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001145 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001146 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1147 } else
1148 codeSegments.push_back(child);
1149 }
1150
1151 // handle the case where the last code segment is missing, due to no code
1152 // statements between the last case and the end of the switch statement
1153 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1154 (int)codeSegments.size() == defaultSegment)
1155 codeSegments.push_back(nullptr);
1156
1157 // make the switch statement
1158 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001159 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001160
1161 // emit all the code in the segments
1162 breakForLoop.push(false);
1163 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1164 builder.nextSwitchSegment(segmentBlocks, s);
1165 if (codeSegments[s])
1166 codeSegments[s]->traverse(this);
1167 else
1168 builder.addSwitchBreak();
1169 }
1170 breakForLoop.pop();
1171
1172 builder.endSwitch(segmentBlocks);
1173
1174 return false;
1175}
1176
1177void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1178{
1179 int nextConst = 0;
1180 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1181
1182 builder.clearAccessChain();
1183 builder.setAccessChainRValue(constant);
1184}
1185
1186bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1187{
1188 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1189 loopTerminal.push(node->getTerminal());
1190
David Netoc22f37c2015-07-15 16:21:26 -04001191 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001192
1193 if (node->getTest()) {
1194 node->getTest()->traverse(this);
1195 // the AST only contained the test computation, not the branch, we have to add it
1196 spv::Id condition = builder.accessChainLoad(TranslatePrecisionDecoration(node->getTest()->getType()));
1197 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001198 } else {
1199 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001200 }
1201
David Netoc22f37c2015-07-15 16:21:26 -04001202 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001203 breakForLoop.push(true);
1204 node->getBody()->traverse(this);
1205 breakForLoop.pop();
1206 }
1207
1208 if (loopTerminal.top())
1209 loopTerminal.top()->traverse(this);
1210
1211 builder.closeLoop();
1212
1213 loopTerminal.pop();
1214
1215 return false;
1216}
1217
1218bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1219{
1220 if (node->getExpression())
1221 node->getExpression()->traverse(this);
1222
1223 switch (node->getFlowOp()) {
1224 case glslang::EOpKill:
1225 builder.makeDiscard();
1226 break;
1227 case glslang::EOpBreak:
1228 if (breakForLoop.top())
1229 builder.createLoopExit();
1230 else
1231 builder.addSwitchBreak();
1232 break;
1233 case glslang::EOpContinue:
1234 if (loopTerminal.top())
1235 loopTerminal.top()->traverse(this);
1236 builder.createLoopContinue();
1237 break;
1238 case glslang::EOpReturn:
1239 if (inMain)
1240 builder.makeMainReturn();
1241 else if (node->getExpression())
1242 builder.makeReturn(false, builder.accessChainLoad(TranslatePrecisionDecoration(node->getExpression()->getType())));
1243 else
1244 builder.makeReturn();
1245
1246 builder.clearAccessChain();
1247 break;
1248
1249 default:
1250 spv::MissingFunctionality("branch type");
1251 break;
1252 }
1253
1254 return false;
1255}
1256
1257spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1258{
1259 // First, steer off constants, which are not SPIR-V variables, but
1260 // can still have a mapping to a SPIR-V Id.
1261 if (node->getQualifier().storage == glslang::EvqConst) {
1262 int nextConst = 0;
1263 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1264 }
1265
1266 // Now, handle actual variables
1267 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1268 spv::Id spvType = convertGlslangToSpvType(node->getType());
1269
1270 const char* name = node->getName().c_str();
1271 if (glslang::IsAnonymous(name))
1272 name = "";
1273
1274 return builder.createVariable(storageClass, spvType, name);
1275}
1276
1277// Return type Id of the sampled type.
1278spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1279{
1280 switch (sampler.type) {
1281 case glslang::EbtFloat: return builder.makeFloatType(32);
1282 case glslang::EbtInt: return builder.makeIntType(32);
1283 case glslang::EbtUint: return builder.makeUintType(32);
1284 default:
1285 spv::MissingFunctionality("sampled type");
1286 return builder.makeFloatType(32);
1287 }
1288}
1289
1290// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1291spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1292{
1293 spv::Id spvType = 0;
1294
1295 switch (type.getBasicType()) {
1296 case glslang::EbtVoid:
1297 spvType = builder.makeVoidType();
1298 if (type.isArray())
1299 spv::MissingFunctionality("array of void");
1300 break;
1301 case glslang::EbtFloat:
1302 spvType = builder.makeFloatType(32);
1303 break;
1304 case glslang::EbtDouble:
1305 spvType = builder.makeFloatType(64);
1306 break;
1307 case glslang::EbtBool:
1308 spvType = builder.makeBoolType();
1309 break;
1310 case glslang::EbtInt:
1311 spvType = builder.makeIntType(32);
1312 break;
1313 case glslang::EbtUint:
1314 spvType = builder.makeUintType(32);
1315 break;
John Kessenich426394d2015-07-23 10:22:48 -06001316 case glslang::EbtAtomicUint:
1317 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1318 spvType = builder.makeUintType(32);
1319 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001320 case glslang::EbtSampler:
1321 {
1322 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001323 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1324 sampler.image ? 2 : 1, spv::ImageFormatUnknown); // TODO: translate format, needed for GLSL image ops
1325 // OpenGL "textures" need to be combined with a sampler
1326 if (! sampler.image)
1327 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001328 }
1329 break;
1330 case glslang::EbtStruct:
1331 case glslang::EbtBlock:
1332 {
1333 // If we've seen this struct type, return it
1334 const glslang::TTypeList* glslangStruct = type.getStruct();
1335 std::vector<spv::Id> structFields;
1336 spvType = structMap[glslangStruct];
1337 if (spvType)
1338 break;
1339
1340 // else, we haven't seen it...
1341
1342 // Create a vector of struct types for SPIR-V to consume
1343 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1344 if (type.getBasicType() == glslang::EbtBlock)
1345 memberRemapper[glslangStruct].resize(glslangStruct->size());
1346 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1347 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1348 if (glslangType.hiddenMember()) {
1349 ++memberDelta;
1350 if (type.getBasicType() == glslang::EbtBlock)
1351 memberRemapper[glslangStruct][i] = -1;
1352 } else {
1353 if (type.getBasicType() == glslang::EbtBlock)
1354 memberRemapper[glslangStruct][i] = i - memberDelta;
1355 structFields.push_back(convertGlslangToSpvType(glslangType));
1356 }
1357 }
1358
1359 // Make the SPIR-V type
1360 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1361 structMap[glslangStruct] = spvType;
1362
1363 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001364 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001365 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1366 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1367 int member = i;
1368 if (type.getBasicType() == glslang::EbtBlock)
1369 member = memberRemapper[glslangStruct][i];
1370 // using -1 above to indicate a hidden member
1371 if (member >= 0) {
1372 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1373 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1374 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1375 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1376 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1377 if (glslangType.getQualifier().hasLocation())
1378 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1379 if (glslangType.getQualifier().hasComponent())
1380 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1381 if (glslangType.getQualifier().hasXfbOffset())
1382 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001383 else {
1384 // figure out what to do with offset, which is accumulating
1385 int nextOffset;
1386 updateMemberOffset(type, glslangType, offset, nextOffset);
1387 if (offset >= 0)
1388 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutOffset);
1389 offset = nextOffset;
1390 }
John Kessenich140f3df2015-06-26 16:58:36 -06001391
1392 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001393 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1394 if (builtIn != spv::BadValue)
1395 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001396 }
1397 }
1398
1399 // Decorate the structure
1400 addDecoration(spvType, TranslateLayoutDecoration(type));
1401 addDecoration(spvType, TranslateBlockDecoration(type));
1402 if (type.getQualifier().hasStream())
1403 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1404 if (glslangIntermediate->getXfbMode()) {
1405 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001406 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001407 if (type.getQualifier().hasXfbBuffer())
1408 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1409 }
1410 }
1411 break;
1412 default:
1413 spv::MissingFunctionality("basic type");
1414 break;
1415 }
1416
1417 if (type.isMatrix())
1418 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1419 else {
1420 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1421 if (type.getVectorSize() > 1)
1422 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1423 }
1424
1425 if (type.isArray()) {
1426 unsigned arraySize;
1427 if (! type.isExplicitlySizedArray()) {
1428 spv::MissingFunctionality("Unsized array");
1429 arraySize = 8;
1430 } else
John Kessenich65c78a02015-08-10 17:08:55 -06001431 arraySize = type.getOuterArraySize();
John Kessenich140f3df2015-06-26 16:58:36 -06001432 spvType = builder.makeArrayType(spvType, arraySize);
1433 }
1434
1435 return spvType;
1436}
1437
John Kessenich5e4b1242015-08-06 22:53:06 -06001438// Given a member type of a struct, realign the current offset for it, and compute
1439// the next (not yet aligned) offset for the next member, which will get aligned
1440// on the next call.
1441// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1442// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1443// -1 means a non-forced member offset (no decoration needed).
1444void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1445{
1446 // this will get a positive value when deemed necessary
1447 nextOffset = -1;
1448
1449 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1450 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1451
1452 // override anything in currentOffset with user-set offset
1453 if (memberType.getQualifier().hasOffset())
1454 currentOffset = memberType.getQualifier().layoutOffset;
1455
1456 // It could be that current linker usage in glslang updated all the layoutOffset,
1457 // in which case the following code does not matter. But, that's not quite right
1458 // once cross-compilation unit GLSL validation is done, as the original user
1459 // settings are needed in layoutOffset, and then the following will come into play.
1460
1461 if (! forceOffset) {
1462 if (! memberType.getQualifier().hasOffset())
1463 currentOffset = -1;
1464
1465 return;
1466 }
1467
1468 // Getting this far means we are forcing offsets
1469 if (currentOffset < 0)
1470 currentOffset = 0;
1471
1472 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1473 // but possibly not yet correctly aligned.
1474
1475 int memberSize;
1476 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1477 glslang::RoundToPow2(currentOffset, memberAlignment);
1478 nextOffset = currentOffset + memberSize;
1479}
1480
John Kessenich140f3df2015-06-26 16:58:36 -06001481bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1482{
1483 return node->getName() == "main(";
1484}
1485
1486// Make all the functions, skeletally, without actually visiting their bodies.
1487void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1488{
1489 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1490 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1491 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1492 continue;
1493
1494 // We're on a user function. Set up the basic interface for the function now,
1495 // so that it's available to call.
1496 // Translating the body will happen later.
1497 //
1498 // Typically (except for a "const in" parameter), an address will be passed to the
1499 // function. What it is an address of varies:
1500 //
1501 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1502 // so that write needs to be to a copy, hence the address of a copy works.
1503 //
1504 // - "const in" parameters can just be the r-value, as no writes need occur.
1505 //
1506 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1507 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1508
1509 std::vector<spv::Id> paramTypes;
1510 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1511
1512 for (int p = 0; p < (int)parameters.size(); ++p) {
1513 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1514 spv::Id typeId = convertGlslangToSpvType(paramType);
1515 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1516 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1517 else
1518 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1519 paramTypes.push_back(typeId);
1520 }
1521
1522 spv::Block* functionBlock;
1523 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1524 paramTypes, &functionBlock);
1525
1526 // Track function to emit/call later
1527 functionMap[glslFunction->getName().c_str()] = function;
1528
1529 // Set the parameter id's
1530 for (int p = 0; p < (int)parameters.size(); ++p) {
1531 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1532 // give a name too
1533 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1534 }
1535 }
1536}
1537
1538// Process all the initializers, while skipping the functions and link objects
1539void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1540{
1541 builder.setBuildPoint(shaderEntry->getLastBlock());
1542 for (int i = 0; i < (int)initializers.size(); ++i) {
1543 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1544 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1545
1546 // We're on a top-level node that's not a function. Treat as an initializer, whose
1547 // code goes into the beginning of main.
1548 initializer->traverse(this);
1549 }
1550 }
1551}
1552
1553// Process all the functions, while skipping initializers.
1554void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1555{
1556 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1557 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1558 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1559 node->traverse(this);
1560 }
1561}
1562
1563void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1564{
1565 // SPIR-V functions should already be in the functionMap from the prepass
1566 // that called makeFunctions().
1567 spv::Function* function = functionMap[node->getName().c_str()];
1568 spv::Block* functionBlock = function->getEntryBlock();
1569 builder.setBuildPoint(functionBlock);
1570}
1571
1572void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments)
1573{
1574 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1575 builder.clearAccessChain();
1576 glslangArguments[i]->traverse(this);
1577 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArguments[i]->getAsTyped()->getType())));
1578 }
1579}
1580
1581spv::Id TGlslangToSpvTraverser::handleBuiltInFunctionCall(const glslang::TIntermAggregate* node)
1582{
1583 std::vector<spv::Id> arguments;
1584 translateArguments(node->getSequence(), arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001585 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1586
1587 if (node->getName() == "ftransform(") {
1588 spv::MissingFunctionality("ftransform()");
1589 //spv::Id vertex = builder.createVariable(spv::StorageShaderGlobal, spv::VectorType::get(spv::makeFloatType(), 4),
1590 // "gl_Vertex_sim");
1591 //spv::Id matrix = builder.createVariable(spv::StorageShaderGlobal, spv::VectorType::get(spv::makeFloatType(), 4),
1592 // "gl_ModelViewProjectionMatrix_sim");
1593 return 0;
1594 }
1595
1596 if (node->getName().substr(0, 7) == "texture" || node->getName().substr(0, 5) == "texel" || node->getName().substr(0, 6) == "shadow") {
1597 const glslang::TSampler sampler = node->getSequence()[0]->getAsTyped()->getType().getSampler();
1598 spv::Builder::TextureParameters params = { };
1599 params.sampler = arguments[0];
1600
1601 // special case size query
1602 if (node->getName().find("textureSize", 0) != std::string::npos) {
1603 if (arguments.size() > 1) {
1604 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001605 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001606 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001607 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001608 }
1609
1610 // special case the number of samples query
1611 if (node->getName().find("textureSamples", 0) != std::string::npos)
John Kessenich5e4b1242015-08-06 22:53:06 -06001612 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001613
1614 // special case the other queries
1615 if (node->getName().find("Query", 0) != std::string::npos) {
1616 if (node->getName().find("Levels", 0) != std::string::npos)
John Kessenich5e4b1242015-08-06 22:53:06 -06001617 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001618 else if (node->getName().find("Lod", 0) != std::string::npos) {
1619 params.coords = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001620 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001621 } else
1622 spv::MissingFunctionality("glslang texture query");
1623 }
1624
1625 // This is no longer a query....
1626
1627 bool lod = node->getName().find("Lod", 0) != std::string::npos;
1628 bool proj = node->getName().find("Proj", 0) != std::string::npos;
1629 bool offsets = node->getName().find("Offsets", 0) != std::string::npos;
1630 bool offset = ! offsets && node->getName().find("Offset", 0) != std::string::npos;
1631 bool fetch = node->getName().find("Fetch", 0) != std::string::npos;
1632 bool gather = node->getName().find("Gather", 0) != std::string::npos;
1633 bool grad = node->getName().find("Grad", 0) != std::string::npos;
1634
1635 if (fetch)
1636 spv::MissingFunctionality("texel fetch");
1637 if (gather)
1638 spv::MissingFunctionality("texture gather");
1639
1640 // check for bias argument
1641 bool bias = false;
1642 if (! lod && ! gather && ! grad && ! fetch) {
1643 int nonBiasArgCount = 2;
1644 if (offset)
1645 ++nonBiasArgCount;
1646 if (grad)
1647 nonBiasArgCount += 2;
1648
1649 if ((int)arguments.size() > nonBiasArgCount)
1650 bias = true;
1651 }
1652
1653 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1654
1655 // set the rest of the arguments
1656 params.coords = arguments[1];
1657 int extraArgs = 0;
1658 if (cubeCompare)
1659 params.Dref = arguments[2];
John Kessenich5e4b1242015-08-06 22:53:06 -06001660 else if (sampler.shadow) {
1661 std::vector<spv::Id> indexes;
1662 int comp;
1663 if (proj)
1664 comp = 3;
1665 else
1666 comp = builder.getNumComponents(params.coords) - 1;
1667 indexes.push_back(comp);
1668 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1669 }
John Kessenich140f3df2015-06-26 16:58:36 -06001670 if (lod) {
1671 params.lod = arguments[2];
1672 ++extraArgs;
1673 }
1674 if (grad) {
1675 params.gradX = arguments[2 + extraArgs];
1676 params.gradY = arguments[3 + extraArgs];
1677 extraArgs += 2;
1678 }
1679 //if (gather && compare) {
1680 // params.compare = arguments[2 + extraArgs];
1681 // ++extraArgs;
1682 //}
1683 if (offset | offsets) {
1684 params.offset = arguments[2 + extraArgs];
1685 ++extraArgs;
1686 }
1687 if (bias) {
1688 params.bias = arguments[2 + extraArgs];
1689 ++extraArgs;
1690 }
1691
1692 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), proj, params);
1693 }
1694
1695 spv::MissingFunctionality("built-in function call");
1696
1697 return 0;
1698}
1699
1700spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1701{
1702 // Grab the function's pointer from the previously created function
1703 spv::Function* function = functionMap[node->getName().c_str()];
1704 if (! function)
1705 return 0;
1706
1707 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1708 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1709
1710 // See comments in makeFunctions() for details about the semantics for parameter passing.
1711 //
1712 // These imply we need a four step process:
1713 // 1. Evaluate the arguments
1714 // 2. Allocate and make copies of in, out, and inout arguments
1715 // 3. Make the call
1716 // 4. Copy back the results
1717
1718 // 1. Evaluate the arguments
1719 std::vector<spv::Builder::AccessChain> lValues;
1720 std::vector<spv::Id> rValues;
1721 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1722 // build l-value
1723 builder.clearAccessChain();
1724 glslangArgs[a]->traverse(this);
1725 // keep outputs as l-values, evaluate input-only as r-values
1726 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1727 // save l-value
1728 lValues.push_back(builder.getAccessChain());
1729 } else {
1730 // process r-value
1731 rValues.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArgs[a]->getAsTyped()->getType())));
1732 }
1733 }
1734
1735 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1736 // copy the original into that space.
1737 //
1738 // Also, build up the list of actual arguments to pass in for the call
1739 int lValueCount = 0;
1740 int rValueCount = 0;
1741 std::vector<spv::Id> spvArgs;
1742 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1743 spv::Id arg;
1744 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1745 // need space to hold the copy
1746 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1747 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1748 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1749 // need to copy the input into output space
1750 builder.setAccessChain(lValues[lValueCount]);
1751 spv::Id copy = builder.accessChainLoad(spv::NoPrecision); // TODO: get precision
1752 builder.createStore(copy, arg);
1753 }
1754 ++lValueCount;
1755 } else {
1756 arg = rValues[rValueCount];
1757 ++rValueCount;
1758 }
1759 spvArgs.push_back(arg);
1760 }
1761
1762 // 3. Make the call.
1763 spv::Id result = builder.createFunctionCall(function, spvArgs);
1764
1765 // 4. Copy back out an "out" arguments.
1766 lValueCount = 0;
1767 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1768 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1769 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1770 spv::Id copy = builder.createLoad(spvArgs[a]);
1771 builder.setAccessChain(lValues[lValueCount]);
1772 builder.accessChainStore(copy);
1773 }
1774 ++lValueCount;
1775 }
1776 }
1777
1778 return result;
1779}
1780
1781// Translate AST operation to SPV operation, already having SPV-based operands/types.
1782spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
1783 spv::Id typeId, spv::Id left, spv::Id right,
1784 glslang::TBasicType typeProxy, bool reduceComparison)
1785{
1786 bool isUnsigned = typeProxy == glslang::EbtUint;
1787 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
1788
1789 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06001790 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06001791 bool comparison = false;
1792
1793 switch (op) {
1794 case glslang::EOpAdd:
1795 case glslang::EOpAddAssign:
1796 if (isFloat)
1797 binOp = spv::OpFAdd;
1798 else
1799 binOp = spv::OpIAdd;
1800 break;
1801 case glslang::EOpSub:
1802 case glslang::EOpSubAssign:
1803 if (isFloat)
1804 binOp = spv::OpFSub;
1805 else
1806 binOp = spv::OpISub;
1807 break;
1808 case glslang::EOpMul:
1809 case glslang::EOpMulAssign:
1810 if (isFloat)
1811 binOp = spv::OpFMul;
1812 else
1813 binOp = spv::OpIMul;
1814 break;
1815 case glslang::EOpVectorTimesScalar:
1816 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06001817 if (isFloat) {
1818 if (builder.isVector(right))
1819 std::swap(left, right);
1820 assert(builder.isScalar(right));
1821 needMatchingVectors = false;
1822 binOp = spv::OpVectorTimesScalar;
1823 } else
1824 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06001825 break;
1826 case glslang::EOpVectorTimesMatrix:
1827 case glslang::EOpVectorTimesMatrixAssign:
1828 assert(builder.isVector(left));
1829 assert(builder.isMatrix(right));
1830 binOp = spv::OpVectorTimesMatrix;
1831 break;
1832 case glslang::EOpMatrixTimesVector:
1833 assert(builder.isMatrix(left));
1834 assert(builder.isVector(right));
1835 binOp = spv::OpMatrixTimesVector;
1836 break;
1837 case glslang::EOpMatrixTimesScalar:
1838 case glslang::EOpMatrixTimesScalarAssign:
1839 if (builder.isMatrix(right))
1840 std::swap(left, right);
1841 assert(builder.isScalar(right));
1842 binOp = spv::OpMatrixTimesScalar;
1843 break;
1844 case glslang::EOpMatrixTimesMatrix:
1845 case glslang::EOpMatrixTimesMatrixAssign:
1846 assert(builder.isMatrix(left));
1847 assert(builder.isMatrix(right));
1848 binOp = spv::OpMatrixTimesMatrix;
1849 break;
1850 case glslang::EOpOuterProduct:
1851 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06001852 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001853 break;
1854
1855 case glslang::EOpDiv:
1856 case glslang::EOpDivAssign:
1857 if (isFloat)
1858 binOp = spv::OpFDiv;
1859 else if (isUnsigned)
1860 binOp = spv::OpUDiv;
1861 else
1862 binOp = spv::OpSDiv;
1863 break;
1864 case glslang::EOpMod:
1865 case glslang::EOpModAssign:
1866 if (isFloat)
1867 binOp = spv::OpFMod;
1868 else if (isUnsigned)
1869 binOp = spv::OpUMod;
1870 else
1871 binOp = spv::OpSMod;
1872 break;
1873 case glslang::EOpRightShift:
1874 case glslang::EOpRightShiftAssign:
1875 if (isUnsigned)
1876 binOp = spv::OpShiftRightLogical;
1877 else
1878 binOp = spv::OpShiftRightArithmetic;
1879 break;
1880 case glslang::EOpLeftShift:
1881 case glslang::EOpLeftShiftAssign:
1882 binOp = spv::OpShiftLeftLogical;
1883 break;
1884 case glslang::EOpAnd:
1885 case glslang::EOpAndAssign:
1886 binOp = spv::OpBitwiseAnd;
1887 break;
1888 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06001889 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001890 binOp = spv::OpLogicalAnd;
1891 break;
1892 case glslang::EOpInclusiveOr:
1893 case glslang::EOpInclusiveOrAssign:
1894 binOp = spv::OpBitwiseOr;
1895 break;
1896 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06001897 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001898 binOp = spv::OpLogicalOr;
1899 break;
1900 case glslang::EOpExclusiveOr:
1901 case glslang::EOpExclusiveOrAssign:
1902 binOp = spv::OpBitwiseXor;
1903 break;
1904 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06001905 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06001906 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06001907 break;
1908
1909 case glslang::EOpLessThan:
1910 case glslang::EOpGreaterThan:
1911 case glslang::EOpLessThanEqual:
1912 case glslang::EOpGreaterThanEqual:
1913 case glslang::EOpEqual:
1914 case glslang::EOpNotEqual:
1915 case glslang::EOpVectorEqual:
1916 case glslang::EOpVectorNotEqual:
1917 comparison = true;
1918 break;
1919 default:
1920 break;
1921 }
1922
1923 if (binOp != spv::OpNop) {
1924 if (builder.isMatrix(left) || builder.isMatrix(right)) {
1925 switch (binOp) {
1926 case spv::OpMatrixTimesScalar:
1927 case spv::OpVectorTimesMatrix:
1928 case spv::OpMatrixTimesVector:
1929 case spv::OpMatrixTimesMatrix:
1930 break;
1931 case spv::OpFDiv:
1932 // turn it into a multiply...
1933 assert(builder.isMatrix(left) && builder.isScalar(right));
1934 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
1935 binOp = spv::OpFMul;
1936 break;
1937 default:
1938 spv::MissingFunctionality("binary operation on matrix");
1939 break;
1940 }
1941
1942 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
1943 builder.setPrecision(id, precision);
1944
1945 return id;
1946 }
1947
1948 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06001949 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06001950 builder.promoteScalar(precision, left, right);
1951
1952 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
1953 builder.setPrecision(id, precision);
1954
1955 return id;
1956 }
1957
1958 if (! comparison)
1959 return 0;
1960
1961 // Comparison instructions
1962
1963 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
1964 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
1965
1966 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
1967 }
1968
1969 switch (op) {
1970 case glslang::EOpLessThan:
1971 if (isFloat)
1972 binOp = spv::OpFOrdLessThan;
1973 else if (isUnsigned)
1974 binOp = spv::OpULessThan;
1975 else
1976 binOp = spv::OpSLessThan;
1977 break;
1978 case glslang::EOpGreaterThan:
1979 if (isFloat)
1980 binOp = spv::OpFOrdGreaterThan;
1981 else if (isUnsigned)
1982 binOp = spv::OpUGreaterThan;
1983 else
1984 binOp = spv::OpSGreaterThan;
1985 break;
1986 case glslang::EOpLessThanEqual:
1987 if (isFloat)
1988 binOp = spv::OpFOrdLessThanEqual;
1989 else if (isUnsigned)
1990 binOp = spv::OpULessThanEqual;
1991 else
1992 binOp = spv::OpSLessThanEqual;
1993 break;
1994 case glslang::EOpGreaterThanEqual:
1995 if (isFloat)
1996 binOp = spv::OpFOrdGreaterThanEqual;
1997 else if (isUnsigned)
1998 binOp = spv::OpUGreaterThanEqual;
1999 else
2000 binOp = spv::OpSGreaterThanEqual;
2001 break;
2002 case glslang::EOpEqual:
2003 case glslang::EOpVectorEqual:
2004 if (isFloat)
2005 binOp = spv::OpFOrdEqual;
2006 else
2007 binOp = spv::OpIEqual;
2008 break;
2009 case glslang::EOpNotEqual:
2010 case glslang::EOpVectorNotEqual:
2011 if (isFloat)
2012 binOp = spv::OpFOrdNotEqual;
2013 else
2014 binOp = spv::OpINotEqual;
2015 break;
2016 default:
2017 break;
2018 }
2019
2020 if (binOp != spv::OpNop) {
2021 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2022 builder.setPrecision(id, precision);
2023
2024 return id;
2025 }
2026
2027 return 0;
2028}
2029
2030spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat)
2031{
2032 spv::Op unaryOp = spv::OpNop;
2033 int libCall = -1;
2034
2035 switch (op) {
2036 case glslang::EOpNegative:
2037 if (isFloat)
2038 unaryOp = spv::OpFNegate;
2039 else
2040 unaryOp = spv::OpSNegate;
2041 break;
2042
2043 case glslang::EOpLogicalNot:
2044 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002045 unaryOp = spv::OpLogicalNot;
2046 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002047 case glslang::EOpBitwiseNot:
2048 unaryOp = spv::OpNot;
2049 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002050
John Kessenich140f3df2015-06-26 16:58:36 -06002051 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002052 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002053 break;
2054 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002055 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002056 break;
2057 case glslang::EOpTranspose:
2058 unaryOp = spv::OpTranspose;
2059 break;
2060
2061 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002062 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002063 break;
2064 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002065 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002066 break;
2067 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002068 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002069 break;
2070 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002071 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002072 break;
2073 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002074 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002075 break;
2076 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002077 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002078 break;
2079 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002080 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002081 break;
2082 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002083 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002084 break;
2085
2086 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002087 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002088 break;
2089 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002090 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002091 break;
2092 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002093 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002094 break;
2095 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002096 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002097 break;
2098 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002099 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002100 break;
2101 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002102 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002103 break;
2104
2105 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002106 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002107 break;
2108 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002109 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002110 break;
2111
2112 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002113 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002114 break;
2115 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002116 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002117 break;
2118 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002119 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002120 break;
2121 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002122 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002123 break;
2124 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002125 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002126 break;
2127 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002128 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002129 break;
2130
2131 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002132 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002133 break;
2134 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002135 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002136 break;
2137 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002138 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002139 break;
2140 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002141 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002142 break;
2143 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002144 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002145 break;
2146 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002147 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002148 break;
2149
2150 case glslang::EOpIsNan:
2151 unaryOp = spv::OpIsNan;
2152 break;
2153 case glslang::EOpIsInf:
2154 unaryOp = spv::OpIsInf;
2155 break;
2156
John Kessenich140f3df2015-06-26 16:58:36 -06002157 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002158 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002159 break;
2160 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002161 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002162 break;
2163 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002164 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002165 break;
2166 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002167 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002168 break;
2169 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002170 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002171 break;
2172 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002173 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002174 break;
2175
2176 case glslang::EOpDPdx:
2177 unaryOp = spv::OpDPdx;
2178 break;
2179 case glslang::EOpDPdy:
2180 unaryOp = spv::OpDPdy;
2181 break;
2182 case glslang::EOpFwidth:
2183 unaryOp = spv::OpFwidth;
2184 break;
2185 case glslang::EOpDPdxFine:
2186 unaryOp = spv::OpDPdxFine;
2187 break;
2188 case glslang::EOpDPdyFine:
2189 unaryOp = spv::OpDPdyFine;
2190 break;
2191 case glslang::EOpFwidthFine:
2192 unaryOp = spv::OpFwidthFine;
2193 break;
2194 case glslang::EOpDPdxCoarse:
2195 unaryOp = spv::OpDPdxCoarse;
2196 break;
2197 case glslang::EOpDPdyCoarse:
2198 unaryOp = spv::OpDPdyCoarse;
2199 break;
2200 case glslang::EOpFwidthCoarse:
2201 unaryOp = spv::OpFwidthCoarse;
2202 break;
2203
2204 case glslang::EOpAny:
2205 unaryOp = spv::OpAny;
2206 break;
2207 case glslang::EOpAll:
2208 unaryOp = spv::OpAll;
2209 break;
2210
2211 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002212 if (isFloat)
2213 libCall = spv::GLSLstd450FAbs;
2214 else
2215 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002216 break;
2217 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002218 if (isFloat)
2219 libCall = spv::GLSLstd450FSign;
2220 else
2221 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002222 break;
2223
2224 default:
2225 return 0;
2226 }
2227
2228 spv::Id id;
2229 if (libCall >= 0) {
2230 std::vector<spv::Id> args;
2231 args.push_back(operand);
2232 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2233 } else
2234 id = builder.createUnaryOp(unaryOp, typeId, operand);
2235
2236 builder.setPrecision(id, precision);
2237
2238 return id;
2239}
2240
2241spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2242{
2243 spv::Op convOp = spv::OpNop;
2244 spv::Id zero = 0;
2245 spv::Id one = 0;
2246
2247 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2248
2249 switch (op) {
2250 case glslang::EOpConvIntToBool:
2251 case glslang::EOpConvUintToBool:
2252 zero = builder.makeUintConstant(0);
2253 zero = makeSmearedConstant(zero, vectorSize);
2254 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2255
2256 case glslang::EOpConvFloatToBool:
2257 zero = builder.makeFloatConstant(0.0F);
2258 zero = makeSmearedConstant(zero, vectorSize);
2259 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2260
2261 case glslang::EOpConvDoubleToBool:
2262 zero = builder.makeDoubleConstant(0.0);
2263 zero = makeSmearedConstant(zero, vectorSize);
2264 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2265
2266 case glslang::EOpConvBoolToFloat:
2267 convOp = spv::OpSelect;
2268 zero = builder.makeFloatConstant(0.0);
2269 one = builder.makeFloatConstant(1.0);
2270 break;
2271 case glslang::EOpConvBoolToDouble:
2272 convOp = spv::OpSelect;
2273 zero = builder.makeDoubleConstant(0.0);
2274 one = builder.makeDoubleConstant(1.0);
2275 break;
2276 case glslang::EOpConvBoolToInt:
2277 zero = builder.makeIntConstant(0);
2278 one = builder.makeIntConstant(1);
2279 convOp = spv::OpSelect;
2280 break;
2281 case glslang::EOpConvBoolToUint:
2282 zero = builder.makeUintConstant(0);
2283 one = builder.makeUintConstant(1);
2284 convOp = spv::OpSelect;
2285 break;
2286
2287 case glslang::EOpConvIntToFloat:
2288 case glslang::EOpConvIntToDouble:
2289 convOp = spv::OpConvertSToF;
2290 break;
2291
2292 case glslang::EOpConvUintToFloat:
2293 case glslang::EOpConvUintToDouble:
2294 convOp = spv::OpConvertUToF;
2295 break;
2296
2297 case glslang::EOpConvDoubleToFloat:
2298 case glslang::EOpConvFloatToDouble:
2299 convOp = spv::OpFConvert;
2300 break;
2301
2302 case glslang::EOpConvFloatToInt:
2303 case glslang::EOpConvDoubleToInt:
2304 convOp = spv::OpConvertFToS;
2305 break;
2306
2307 case glslang::EOpConvUintToInt:
2308 case glslang::EOpConvIntToUint:
2309 convOp = spv::OpBitcast;
2310 break;
2311
2312 case glslang::EOpConvFloatToUint:
2313 case glslang::EOpConvDoubleToUint:
2314 convOp = spv::OpConvertFToU;
2315 break;
2316 default:
2317 break;
2318 }
2319
2320 spv::Id result = 0;
2321 if (convOp == spv::OpNop)
2322 return result;
2323
2324 if (convOp == spv::OpSelect) {
2325 zero = makeSmearedConstant(zero, vectorSize);
2326 one = makeSmearedConstant(one, vectorSize);
2327 result = builder.createTriOp(convOp, destType, operand, one, zero);
2328 } else
2329 result = builder.createUnaryOp(convOp, destType, operand);
2330
2331 builder.setPrecision(result, precision);
2332
2333 return result;
2334}
2335
2336spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2337{
2338 if (vectorSize == 0)
2339 return constant;
2340
2341 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2342 std::vector<spv::Id> components;
2343 for (int c = 0; c < vectorSize; ++c)
2344 components.push_back(constant);
2345 return builder.makeCompositeConstant(vectorTypeId, components);
2346}
2347
John Kessenich426394d2015-07-23 10:22:48 -06002348// For glslang ops that map to SPV atomic opCodes
2349spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands)
2350{
2351 spv::Op opCode = spv::OpNop;
2352
2353 switch (op) {
2354 case glslang::EOpAtomicAdd:
2355 opCode = spv::OpAtomicIAdd;
2356 break;
2357 case glslang::EOpAtomicMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002358 opCode = spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002359 break;
2360 case glslang::EOpAtomicMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002361 opCode = spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002362 break;
2363 case glslang::EOpAtomicAnd:
2364 opCode = spv::OpAtomicAnd;
2365 break;
2366 case glslang::EOpAtomicOr:
2367 opCode = spv::OpAtomicOr;
2368 break;
2369 case glslang::EOpAtomicXor:
2370 opCode = spv::OpAtomicXor;
2371 break;
2372 case glslang::EOpAtomicExchange:
2373 opCode = spv::OpAtomicExchange;
2374 break;
2375 case glslang::EOpAtomicCompSwap:
2376 opCode = spv::OpAtomicCompareExchange;
2377 break;
2378 case glslang::EOpAtomicCounterIncrement:
2379 opCode = spv::OpAtomicIIncrement;
2380 break;
2381 case glslang::EOpAtomicCounterDecrement:
2382 opCode = spv::OpAtomicIDecrement;
2383 break;
2384 case glslang::EOpAtomicCounter:
2385 opCode = spv::OpAtomicLoad;
2386 break;
2387 default:
2388 spv::MissingFunctionality("missing nested atomic");
2389 break;
2390 }
2391
2392 // Sort out the operands
2393 // - mapping from glslang -> SPV
2394 // - there are extra SPV operands with no glslang source
2395 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2396 auto opIt = operands.begin(); // walk the glslang operands
2397 spvAtomicOperands.push_back(*(opIt++));
John Kessenich5e4b1242015-08-06 22:53:06 -06002398 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2399 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
John Kessenich426394d2015-07-23 10:22:48 -06002400
2401 // Add the rest of the operands, skipping the first one, which was dealt with above.
2402 // For some ops, there are none, for some 1, for compare-exchange, 2.
2403 for (; opIt != operands.end(); ++opIt)
2404 spvAtomicOperands.push_back(*opIt);
2405
2406 return builder.createOp(opCode, typeId, spvAtomicOperands);
2407}
2408
John Kessenich5e4b1242015-08-06 22:53:06 -06002409spv::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 -06002410{
John Kessenich5e4b1242015-08-06 22:53:06 -06002411 bool isUnsigned = typeProxy == glslang::EbtUint;
2412 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2413
John Kessenich140f3df2015-06-26 16:58:36 -06002414 spv::Op opCode = spv::OpNop;
2415 int libCall = -1;
2416
2417 switch (op) {
2418 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002419 if (isFloat)
2420 libCall = spv::GLSLstd450FMin;
2421 else if (isUnsigned)
2422 libCall = spv::GLSLstd450UMin;
2423 else
2424 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002425 break;
2426 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002427 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002428 break;
2429 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002430 if (isFloat)
2431 libCall = spv::GLSLstd450FMax;
2432 else if (isUnsigned)
2433 libCall = spv::GLSLstd450UMax;
2434 else
2435 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002436 break;
2437 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002438 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002439 break;
2440 case glslang::EOpDot:
2441 opCode = spv::OpDot;
2442 break;
2443 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002444 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002445 break;
2446
2447 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002448 if (isFloat)
2449 libCall = spv::GLSLstd450FClamp;
2450 else if (isUnsigned)
2451 libCall = spv::GLSLstd450UClamp;
2452 else
2453 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002454 break;
2455 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002456 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002457 break;
2458 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002459 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002460 break;
2461 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002462 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002463 break;
2464
2465 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002466 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002467 break;
2468 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002469 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002470 break;
2471 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002472 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002473 break;
2474 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002475 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002476 break;
2477 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002478 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002479 break;
John Kessenich426394d2015-07-23 10:22:48 -06002480
John Kessenich140f3df2015-06-26 16:58:36 -06002481 default:
2482 return 0;
2483 }
2484
2485 spv::Id id = 0;
2486 if (libCall >= 0)
2487 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2488 else {
2489 switch (operands.size()) {
2490 case 0:
2491 // should all be handled by visitAggregate and createNoArgOperation
2492 assert(0);
2493 return 0;
2494 case 1:
2495 // should all be handled by createUnaryOperation
2496 assert(0);
2497 return 0;
2498 case 2:
2499 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2500 break;
2501 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002502 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002503 break;
2504 default:
2505 // These do not exist yet
2506 assert(0 && "operation with more than 3 operands");
2507 break;
2508 }
2509 }
2510
2511 builder.setPrecision(id, precision);
2512
2513 return id;
2514}
2515
2516// Intrinsics with no arguments, no return value, and no precision.
2517spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2518{
2519 // TODO: get the barrier operands correct
2520
2521 switch (op) {
2522 case glslang::EOpEmitVertex:
2523 builder.createNoResultOp(spv::OpEmitVertex);
2524 return 0;
2525 case glslang::EOpEndPrimitive:
2526 builder.createNoResultOp(spv::OpEndPrimitive);
2527 return 0;
2528 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002529 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2530 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002531 return 0;
2532 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002533 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002534 return 0;
2535 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002536 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002537 return 0;
2538 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002539 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002540 return 0;
2541 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002542 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002543 return 0;
2544 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002545 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002546 return 0;
2547 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002548 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002549 return 0;
2550 default:
2551 spv::MissingFunctionality("operation with no arguments");
2552 return 0;
2553 }
2554}
2555
2556spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2557{
John Kessenich2f273362015-07-18 22:34:27 -06002558 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002559 spv::Id id;
2560 if (symbolValues.end() != iter) {
2561 id = iter->second;
2562 return id;
2563 }
2564
2565 // it was not found, create it
2566 id = createSpvVariable(symbol);
2567 symbolValues[symbol->getId()] = id;
2568
2569 if (! symbol->getType().isStruct()) {
2570 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2571 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2572 if (symbol->getQualifier().hasLocation())
2573 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2574 if (symbol->getQualifier().hasIndex())
2575 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2576 if (symbol->getQualifier().hasComponent())
2577 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2578 if (glslangIntermediate->getXfbMode()) {
2579 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002580 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002581 if (symbol->getQualifier().hasXfbBuffer())
2582 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2583 if (symbol->getQualifier().hasXfbOffset())
2584 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2585 }
2586 }
2587
2588 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2589 if (symbol->getQualifier().hasStream())
2590 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2591 if (symbol->getQualifier().hasSet())
2592 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2593 if (symbol->getQualifier().hasBinding())
2594 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2595 if (glslangIntermediate->getXfbMode()) {
2596 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002597 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002598 if (symbol->getQualifier().hasXfbBuffer())
2599 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2600 }
2601
2602 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002603 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002604 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002605 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002606
2607 if (linkageOnly)
2608 builder.addDecoration(id, spv::DecorationNoStaticUse);
2609
2610 return id;
2611}
2612
2613void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2614{
2615 if (dec != spv::BadValue)
2616 builder.addDecoration(id, dec);
2617}
2618
2619void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2620{
2621 if (dec != spv::BadValue)
2622 builder.addMemberDecoration(id, (unsigned)member, dec);
2623}
2624
2625// Use 'consts' as the flattened glslang source of scalar constants to recursively
2626// build the aggregate SPIR-V constant.
2627//
2628// If there are not enough elements present in 'consts', 0 will be substituted;
2629// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2630//
2631spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2632{
2633 // vector of constants for SPIR-V
2634 std::vector<spv::Id> spvConsts;
2635
2636 // Type is used for struct and array constants
2637 spv::Id typeId = convertGlslangToSpvType(glslangType);
2638
2639 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002640 glslang::TType elementType(glslangType, 0);
2641 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002642 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2643 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002644 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002645 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2646 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2647 } else if (glslangType.getStruct()) {
2648 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2649 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2650 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2651 } else if (glslangType.isVector()) {
2652 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2653 bool zero = nextConst >= consts.size();
2654 switch (glslangType.getBasicType()) {
2655 case glslang::EbtInt:
2656 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2657 break;
2658 case glslang::EbtUint:
2659 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2660 break;
2661 case glslang::EbtFloat:
2662 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2663 break;
2664 case glslang::EbtDouble:
2665 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2666 break;
2667 case glslang::EbtBool:
2668 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2669 break;
2670 default:
2671 spv::MissingFunctionality("constant vector type");
2672 break;
2673 }
2674 ++nextConst;
2675 }
2676 } else {
2677 // we have a non-aggregate (scalar) constant
2678 bool zero = nextConst >= consts.size();
2679 spv::Id scalar = 0;
2680 switch (glslangType.getBasicType()) {
2681 case glslang::EbtInt:
2682 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2683 break;
2684 case glslang::EbtUint:
2685 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2686 break;
2687 case glslang::EbtFloat:
2688 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2689 break;
2690 case glslang::EbtDouble:
2691 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2692 break;
2693 case glslang::EbtBool:
2694 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2695 break;
2696 default:
2697 spv::MissingFunctionality("constant scalar type");
2698 break;
2699 }
2700 ++nextConst;
2701 return scalar;
2702 }
2703
2704 return builder.makeCompositeConstant(typeId, spvConsts);
2705}
2706
2707}; // end anonymous namespace
2708
2709namespace glslang {
2710
John Kessenich68d78fd2015-07-12 19:28:10 -06002711void GetSpirvVersion(std::string& version)
2712{
John Kessenich9e55f632015-07-15 10:03:39 -06002713 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002714 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002715 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002716 version = buf;
2717}
2718
John Kessenich140f3df2015-06-26 16:58:36 -06002719// Write SPIR-V out to a binary file
2720void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
2721{
2722 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06002723 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06002724 for (int i = 0; i < (int)spirv.size(); ++i) {
2725 unsigned int word = spirv[i];
2726 out.write((const char*)&word, 4);
2727 }
2728 out.close();
2729}
2730
2731//
2732// Set up the glslang traversal
2733//
2734void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
2735{
2736 TIntermNode* root = intermediate.getTreeRoot();
2737
2738 if (root == 0)
2739 return;
2740
2741 glslang::GetThreadPoolAllocator().push();
2742
2743 TGlslangToSpvTraverser it(&intermediate);
2744
2745 root->traverse(&it);
2746
2747 it.dumpSpv(spirv);
2748
2749 glslang::GetThreadPoolAllocator().pop();
2750}
2751
2752}; // end namespace glslang