blob: 0a069c22f367d6dffb2666f2c99254c3b613283b [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);
John Kessenichfc51d282015-08-19 13:34:18 -060099 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
100 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
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{
John Kessenichfc51d282015-08-19 13:34:18 -0600667 spv::Id result = spv::NoResult;
668
669 // try texturing first
670 result = createImageTextureFunctionCall(node);
671 if (result != spv::NoResult) {
672 builder.clearAccessChain();
673 builder.setAccessChainRValue(result);
674
675 return false; // done with this node
676 }
677
678 // Non-texturing.
679 // Start by evaluating the operand
680
John Kessenich140f3df2015-06-26 16:58:36 -0600681 builder.clearAccessChain();
682 node->getOperand()->traverse(this);
683 spv::Id operand = builder.accessChainLoad(TranslatePrecisionDecoration(node->getOperand()->getType()));
684
685 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
686
687 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600688 if (! result)
689 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600690
691 // if not, then possibly an operation
692 if (! result)
John Kessenichfc51d282015-08-19 13:34:18 -0600693 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand,
694 node->getBasicType() == glslang::EbtFloat || node->getBasicType() == glslang::EbtDouble);
John Kessenich140f3df2015-06-26 16:58:36 -0600695
696 if (result) {
697 builder.clearAccessChain();
698 builder.setAccessChainRValue(result);
699
700 return false; // done with this node
701 }
702
703 // it must be a special case, check...
704 switch (node->getOp()) {
705 case glslang::EOpPostIncrement:
706 case glslang::EOpPostDecrement:
707 case glslang::EOpPreIncrement:
708 case glslang::EOpPreDecrement:
709 {
710 // we need the integer value "1" or the floating point "1.0" to add/subtract
711 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
712 builder.makeFloatConstant(1.0F) :
713 builder.makeIntConstant(1);
714 glslang::TOperator op;
715 if (node->getOp() == glslang::EOpPreIncrement ||
716 node->getOp() == glslang::EOpPostIncrement)
717 op = glslang::EOpAdd;
718 else
719 op = glslang::EOpSub;
720
721 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
722 convertGlslangToSpvType(node->getType()), operand, one,
723 node->getType().getBasicType());
724 if (result == 0)
725 spv::MissingFunctionality("createBinaryOperation for unary");
726
727 // The result of operation is always stored, but conditionally the
728 // consumed result. The consumed result is always an r-value.
729 builder.accessChainStore(result);
730 builder.clearAccessChain();
731 if (node->getOp() == glslang::EOpPreIncrement ||
732 node->getOp() == glslang::EOpPreDecrement)
733 builder.setAccessChainRValue(result);
734 else
735 builder.setAccessChainRValue(operand);
736 }
737
738 return false;
739
740 case glslang::EOpEmitStreamVertex:
741 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
742 return false;
743 case glslang::EOpEndStreamPrimitive:
744 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
745 return false;
746
747 default:
748 spv::MissingFunctionality("glslang unary");
749 break;
750 }
751
752 return true;
753}
754
755bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
756{
John Kessenichfc51d282015-08-19 13:34:18 -0600757 spv::Id result = spv::NoResult;
758
759 // try texturing
760 result = createImageTextureFunctionCall(node);
761 if (result != spv::NoResult) {
762 builder.clearAccessChain();
763 builder.setAccessChainRValue(result);
764
765 return false;
766 }
767
John Kessenich140f3df2015-06-26 16:58:36 -0600768 glslang::TOperator binOp = glslang::EOpNull;
769 bool reduceComparison = true;
770 bool isMatrix = false;
771 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600772 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600773
774 assert(node->getOp());
775
776 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
777
778 switch (node->getOp()) {
779 case glslang::EOpSequence:
780 {
781 if (preVisit)
782 ++sequenceDepth;
783 else
784 --sequenceDepth;
785
786 if (sequenceDepth == 1) {
787 // If this is the parent node of all the functions, we want to see them
788 // early, so all call points have actual SPIR-V functions to reference.
789 // In all cases, still let the traverser visit the children for us.
790 makeFunctions(node->getAsAggregate()->getSequence());
791
792 // Also, we want all globals initializers to go into the entry of main(), before
793 // anything else gets there, so visit out of order, doing them all now.
794 makeGlobalInitializers(node->getAsAggregate()->getSequence());
795
796 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
797 // so do them manually.
798 visitFunctions(node->getAsAggregate()->getSequence());
799
800 return false;
801 }
802
803 return true;
804 }
805 case glslang::EOpLinkerObjects:
806 {
807 if (visit == glslang::EvPreVisit)
808 linkageOnly = true;
809 else
810 linkageOnly = false;
811
812 return true;
813 }
814 case glslang::EOpComma:
815 {
816 // processing from left to right naturally leaves the right-most
817 // lying around in the access chain
818 glslang::TIntermSequence& glslangOperands = node->getSequence();
819 for (int i = 0; i < (int)glslangOperands.size(); ++i)
820 glslangOperands[i]->traverse(this);
821
822 return false;
823 }
824 case glslang::EOpFunction:
825 if (visit == glslang::EvPreVisit) {
826 if (isShaderEntrypoint(node)) {
827 inMain = true;
828 builder.setBuildPoint(shaderEntry->getLastBlock());
829 } else {
830 handleFunctionEntry(node);
831 }
832 } else {
833 if (inMain)
834 mainTerminated = true;
835 builder.leaveFunction(inMain);
836 inMain = false;
837 }
838
839 return true;
840 case glslang::EOpParameters:
841 // Parameters will have been consumed by EOpFunction processing, but not
842 // the body, so we still visited the function node's children, making this
843 // child redundant.
844 return false;
845 case glslang::EOpFunctionCall:
846 {
847 if (node->isUserDefined())
848 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600849
850 if (! result) {
851 spv::MissingFunctionality("glslang function call");
852 glslang::TConstUnionArray emptyConsts;
853 int nextConst = 0;
854 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
855 }
856 builder.clearAccessChain();
857 builder.setAccessChainRValue(result);
858
859 return false;
860 }
861 case glslang::EOpConstructMat2x2:
862 case glslang::EOpConstructMat2x3:
863 case glslang::EOpConstructMat2x4:
864 case glslang::EOpConstructMat3x2:
865 case glslang::EOpConstructMat3x3:
866 case glslang::EOpConstructMat3x4:
867 case glslang::EOpConstructMat4x2:
868 case glslang::EOpConstructMat4x3:
869 case glslang::EOpConstructMat4x4:
870 case glslang::EOpConstructDMat2x2:
871 case glslang::EOpConstructDMat2x3:
872 case glslang::EOpConstructDMat2x4:
873 case glslang::EOpConstructDMat3x2:
874 case glslang::EOpConstructDMat3x3:
875 case glslang::EOpConstructDMat3x4:
876 case glslang::EOpConstructDMat4x2:
877 case glslang::EOpConstructDMat4x3:
878 case glslang::EOpConstructDMat4x4:
879 isMatrix = true;
880 // fall through
881 case glslang::EOpConstructFloat:
882 case glslang::EOpConstructVec2:
883 case glslang::EOpConstructVec3:
884 case glslang::EOpConstructVec4:
885 case glslang::EOpConstructDouble:
886 case glslang::EOpConstructDVec2:
887 case glslang::EOpConstructDVec3:
888 case glslang::EOpConstructDVec4:
889 case glslang::EOpConstructBool:
890 case glslang::EOpConstructBVec2:
891 case glslang::EOpConstructBVec3:
892 case glslang::EOpConstructBVec4:
893 case glslang::EOpConstructInt:
894 case glslang::EOpConstructIVec2:
895 case glslang::EOpConstructIVec3:
896 case glslang::EOpConstructIVec4:
897 case glslang::EOpConstructUint:
898 case glslang::EOpConstructUVec2:
899 case glslang::EOpConstructUVec3:
900 case glslang::EOpConstructUVec4:
901 case glslang::EOpConstructStruct:
902 {
903 std::vector<spv::Id> arguments;
904 translateArguments(node->getSequence(), arguments);
905 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
906 spv::Id constructed;
907 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
908 std::vector<spv::Id> constituents;
909 for (int c = 0; c < (int)arguments.size(); ++c)
910 constituents.push_back(arguments[c]);
911 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
912 } else {
913 if (isMatrix)
914 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
915 else
916 constructed = builder.createConstructor(precision, arguments, resultTypeId);
917 }
918
919 builder.clearAccessChain();
920 builder.setAccessChainRValue(constructed);
921
922 return false;
923 }
924
925 // These six are component-wise compares with component-wise results.
926 // Forward on to createBinaryOperation(), requesting a vector result.
927 case glslang::EOpLessThan:
928 case glslang::EOpGreaterThan:
929 case glslang::EOpLessThanEqual:
930 case glslang::EOpGreaterThanEqual:
931 case glslang::EOpVectorEqual:
932 case glslang::EOpVectorNotEqual:
933 {
934 // Map the operation to a binary
935 binOp = node->getOp();
936 reduceComparison = false;
937 switch (node->getOp()) {
938 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
939 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
940 default: binOp = node->getOp(); break;
941 }
942
943 break;
944 }
945 case glslang::EOpMul:
946 // compontent-wise matrix multiply
947 binOp = glslang::EOpMul;
948 break;
949 case glslang::EOpOuterProduct:
950 // two vectors multiplied to make a matrix
951 binOp = glslang::EOpOuterProduct;
952 break;
953 case glslang::EOpDot:
954 {
955 // for scalar dot product, use multiply
956 glslang::TIntermSequence& glslangOperands = node->getSequence();
957 if (! glslangOperands[0]->getAsTyped()->isVector())
958 binOp = glslang::EOpMul;
959 break;
960 }
961 case glslang::EOpMod:
962 // when an aggregate, this is the floating-point mod built-in function,
963 // which can be emitted by the one in createBinaryOperation()
964 binOp = glslang::EOpMod;
965 break;
966 case glslang::EOpArrayLength:
967 {
968 glslang::TIntermTyped* typedNode = node->getSequence()[0]->getAsTyped();
969 assert(typedNode);
John Kessenich65c78a02015-08-10 17:08:55 -0600970 spv::Id length = builder.makeIntConstant(typedNode->getType().getOuterArraySize());
John Kessenich140f3df2015-06-26 16:58:36 -0600971
972 builder.clearAccessChain();
973 builder.setAccessChainRValue(length);
974
975 return false;
976 }
977 case glslang::EOpEmitVertex:
978 case glslang::EOpEndPrimitive:
979 case glslang::EOpBarrier:
980 case glslang::EOpMemoryBarrier:
981 case glslang::EOpMemoryBarrierAtomicCounter:
982 case glslang::EOpMemoryBarrierBuffer:
983 case glslang::EOpMemoryBarrierImage:
984 case glslang::EOpMemoryBarrierShared:
985 case glslang::EOpGroupMemoryBarrier:
986 noReturnValue = true;
987 // These all have 0 operands and will naturally finish up in the code below for 0 operands
988 break;
989
John Kessenich426394d2015-07-23 10:22:48 -0600990 case glslang::EOpAtomicAdd:
991 case glslang::EOpAtomicMin:
992 case glslang::EOpAtomicMax:
993 case glslang::EOpAtomicAnd:
994 case glslang::EOpAtomicOr:
995 case glslang::EOpAtomicXor:
996 case glslang::EOpAtomicExchange:
997 case glslang::EOpAtomicCompSwap:
998 atomic = true;
999 break;
1000
John Kessenichfc51d282015-08-19 13:34:18 -06001001 case glslang::EOpAddCarry:
1002 case glslang::EOpSubBorrow:
1003 case glslang::EOpUMulExtended:
1004 case glslang::EOpIMulExtended:
1005 case glslang::EOpBitfieldExtract:
1006 case glslang::EOpBitfieldInsert:
1007 spv::MissingFunctionality("integer aggregate");
1008 break;
1009
1010 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001011 case glslang::EOpFrexp:
1012 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001013 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1014 break;
1015
John Kessenich140f3df2015-06-26 16:58:36 -06001016 default:
1017 break;
1018 }
1019
1020 //
1021 // See if it maps to a regular operation.
1022 //
John Kessenich140f3df2015-06-26 16:58:36 -06001023 if (binOp != glslang::EOpNull) {
1024 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1025 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1026 assert(left && right);
1027
1028 builder.clearAccessChain();
1029 left->traverse(this);
1030 spv::Id leftId = builder.accessChainLoad(TranslatePrecisionDecoration(left->getType()));
1031
1032 builder.clearAccessChain();
1033 right->traverse(this);
1034 spv::Id rightId = builder.accessChainLoad(TranslatePrecisionDecoration(right->getType()));
1035
1036 result = createBinaryOperation(binOp, precision,
1037 convertGlslangToSpvType(node->getType()), leftId, rightId,
1038 left->getType().getBasicType(), reduceComparison);
1039
1040 // code above should only make binOp that exists in createBinaryOperation
1041 if (result == 0)
1042 spv::MissingFunctionality("createBinaryOperation for aggregate");
1043
1044 builder.clearAccessChain();
1045 builder.setAccessChainRValue(result);
1046
1047 return false;
1048 }
1049
John Kessenich426394d2015-07-23 10:22:48 -06001050 //
1051 // Create the list of operands.
1052 //
John Kessenich140f3df2015-06-26 16:58:36 -06001053 glslang::TIntermSequence& glslangOperands = node->getSequence();
1054 std::vector<spv::Id> operands;
1055 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1056 builder.clearAccessChain();
1057 glslangOperands[arg]->traverse(this);
1058
1059 // special case l-value operands; there are just a few
1060 bool lvalue = false;
1061 switch (node->getOp()) {
1062 //case glslang::EOpFrexp:
1063 case glslang::EOpModf:
1064 if (arg == 1)
1065 lvalue = true;
1066 break;
Rex Xud4782c12015-09-06 16:30:11 +08001067 case glslang::EOpAtomicAdd:
1068 case glslang::EOpAtomicMin:
1069 case glslang::EOpAtomicMax:
1070 case glslang::EOpAtomicAnd:
1071 case glslang::EOpAtomicOr:
1072 case glslang::EOpAtomicXor:
1073 case glslang::EOpAtomicExchange:
1074 case glslang::EOpAtomicCompSwap:
1075 if (arg == 0)
1076 lvalue = true;
1077 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001078 //case glslang::EOpUAddCarry:
1079 //case glslang::EOpUSubBorrow:
1080 //case glslang::EOpUMulExtended:
1081 default:
1082 break;
1083 }
1084 if (lvalue)
1085 operands.push_back(builder.accessChainGetLValue());
1086 else
1087 operands.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangOperands[arg]->getAsTyped()->getType())));
1088 }
John Kessenich426394d2015-07-23 10:22:48 -06001089
1090 if (atomic) {
1091 // Handle all atomics
1092 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands);
1093 } else {
1094 // Pass through to generic operations.
1095 switch (glslangOperands.size()) {
1096 case 0:
1097 result = createNoArgOperation(node->getOp());
1098 break;
1099 case 1:
1100 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType() == glslang::EbtFloat || node->getType().getBasicType() == glslang::EbtDouble);
1101 break;
1102 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001103 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001104 break;
1105 }
John Kessenich140f3df2015-06-26 16:58:36 -06001106 }
1107
1108 if (noReturnValue)
1109 return false;
1110
1111 if (! result) {
1112 spv::MissingFunctionality("glslang aggregate");
1113 return true;
1114 } else {
1115 builder.clearAccessChain();
1116 builder.setAccessChainRValue(result);
1117 return false;
1118 }
1119}
1120
1121bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1122{
1123 // This path handles both if-then-else and ?:
1124 // The if-then-else has a node type of void, while
1125 // ?: has a non-void node type
1126 spv::Id result = 0;
1127 if (node->getBasicType() != glslang::EbtVoid) {
1128 // don't handle this as just on-the-fly temporaries, because there will be two names
1129 // and better to leave SSA to later passes
1130 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1131 }
1132
1133 // emit the condition before doing anything with selection
1134 node->getCondition()->traverse(this);
1135
1136 // make an "if" based on the value created by the condition
1137 spv::Builder::If ifBuilder(builder.accessChainLoad(spv::NoPrecision), builder);
1138
1139 if (node->getTrueBlock()) {
1140 // emit the "then" statement
1141 node->getTrueBlock()->traverse(this);
1142 if (result)
1143 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getTrueBlock()->getAsTyped()->getType())), result);
1144 }
1145
1146 if (node->getFalseBlock()) {
1147 ifBuilder.makeBeginElse();
1148 // emit the "else" statement
1149 node->getFalseBlock()->traverse(this);
1150 if (result)
1151 builder.createStore(builder.accessChainLoad(TranslatePrecisionDecoration(node->getFalseBlock()->getAsTyped()->getType())), result);
1152 }
1153
1154 ifBuilder.makeEndIf();
1155
1156 if (result) {
1157 // GLSL only has r-values as the result of a :?, but
1158 // if we have an l-value, that can be more efficient if it will
1159 // become the base of a complex r-value expression, because the
1160 // next layer copies r-values into memory to use the access-chain mechanism
1161 builder.clearAccessChain();
1162 builder.setAccessChainLValue(result);
1163 }
1164
1165 return false;
1166}
1167
1168bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1169{
1170 // emit and get the condition before doing anything with switch
1171 node->getCondition()->traverse(this);
1172 spv::Id selector = builder.accessChainLoad(TranslatePrecisionDecoration(node->getCondition()->getAsTyped()->getType()));
1173
1174 // browse the children to sort out code segments
1175 int defaultSegment = -1;
1176 std::vector<TIntermNode*> codeSegments;
1177 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1178 std::vector<int> caseValues;
1179 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1180 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1181 TIntermNode* child = *c;
1182 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001183 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001184 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001185 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001186 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1187 } else
1188 codeSegments.push_back(child);
1189 }
1190
1191 // handle the case where the last code segment is missing, due to no code
1192 // statements between the last case and the end of the switch statement
1193 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1194 (int)codeSegments.size() == defaultSegment)
1195 codeSegments.push_back(nullptr);
1196
1197 // make the switch statement
1198 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001199 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001200
1201 // emit all the code in the segments
1202 breakForLoop.push(false);
1203 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1204 builder.nextSwitchSegment(segmentBlocks, s);
1205 if (codeSegments[s])
1206 codeSegments[s]->traverse(this);
1207 else
1208 builder.addSwitchBreak();
1209 }
1210 breakForLoop.pop();
1211
1212 builder.endSwitch(segmentBlocks);
1213
1214 return false;
1215}
1216
1217void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1218{
1219 int nextConst = 0;
1220 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1221
1222 builder.clearAccessChain();
1223 builder.setAccessChainRValue(constant);
1224}
1225
1226bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1227{
1228 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1229 loopTerminal.push(node->getTerminal());
1230
David Netoc22f37c2015-07-15 16:21:26 -04001231 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001232
1233 if (node->getTest()) {
1234 node->getTest()->traverse(this);
1235 // the AST only contained the test computation, not the branch, we have to add it
1236 spv::Id condition = builder.accessChainLoad(TranslatePrecisionDecoration(node->getTest()->getType()));
1237 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001238 } else {
1239 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001240 }
1241
David Netoc22f37c2015-07-15 16:21:26 -04001242 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001243 breakForLoop.push(true);
1244 node->getBody()->traverse(this);
1245 breakForLoop.pop();
1246 }
1247
1248 if (loopTerminal.top())
1249 loopTerminal.top()->traverse(this);
1250
1251 builder.closeLoop();
1252
1253 loopTerminal.pop();
1254
1255 return false;
1256}
1257
1258bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1259{
1260 if (node->getExpression())
1261 node->getExpression()->traverse(this);
1262
1263 switch (node->getFlowOp()) {
1264 case glslang::EOpKill:
1265 builder.makeDiscard();
1266 break;
1267 case glslang::EOpBreak:
1268 if (breakForLoop.top())
1269 builder.createLoopExit();
1270 else
1271 builder.addSwitchBreak();
1272 break;
1273 case glslang::EOpContinue:
1274 if (loopTerminal.top())
1275 loopTerminal.top()->traverse(this);
1276 builder.createLoopContinue();
1277 break;
1278 case glslang::EOpReturn:
1279 if (inMain)
1280 builder.makeMainReturn();
1281 else if (node->getExpression())
1282 builder.makeReturn(false, builder.accessChainLoad(TranslatePrecisionDecoration(node->getExpression()->getType())));
1283 else
1284 builder.makeReturn();
1285
1286 builder.clearAccessChain();
1287 break;
1288
1289 default:
1290 spv::MissingFunctionality("branch type");
1291 break;
1292 }
1293
1294 return false;
1295}
1296
1297spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1298{
1299 // First, steer off constants, which are not SPIR-V variables, but
1300 // can still have a mapping to a SPIR-V Id.
1301 if (node->getQualifier().storage == glslang::EvqConst) {
1302 int nextConst = 0;
1303 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1304 }
1305
1306 // Now, handle actual variables
1307 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1308 spv::Id spvType = convertGlslangToSpvType(node->getType());
1309
1310 const char* name = node->getName().c_str();
1311 if (glslang::IsAnonymous(name))
1312 name = "";
1313
1314 return builder.createVariable(storageClass, spvType, name);
1315}
1316
1317// Return type Id of the sampled type.
1318spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1319{
1320 switch (sampler.type) {
1321 case glslang::EbtFloat: return builder.makeFloatType(32);
1322 case glslang::EbtInt: return builder.makeIntType(32);
1323 case glslang::EbtUint: return builder.makeUintType(32);
1324 default:
1325 spv::MissingFunctionality("sampled type");
1326 return builder.makeFloatType(32);
1327 }
1328}
1329
1330// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1331spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1332{
1333 spv::Id spvType = 0;
1334
1335 switch (type.getBasicType()) {
1336 case glslang::EbtVoid:
1337 spvType = builder.makeVoidType();
1338 if (type.isArray())
1339 spv::MissingFunctionality("array of void");
1340 break;
1341 case glslang::EbtFloat:
1342 spvType = builder.makeFloatType(32);
1343 break;
1344 case glslang::EbtDouble:
1345 spvType = builder.makeFloatType(64);
1346 break;
1347 case glslang::EbtBool:
1348 spvType = builder.makeBoolType();
1349 break;
1350 case glslang::EbtInt:
1351 spvType = builder.makeIntType(32);
1352 break;
1353 case glslang::EbtUint:
1354 spvType = builder.makeUintType(32);
1355 break;
John Kessenich426394d2015-07-23 10:22:48 -06001356 case glslang::EbtAtomicUint:
1357 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1358 spvType = builder.makeUintType(32);
1359 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001360 case glslang::EbtSampler:
1361 {
1362 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001363 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1364 sampler.image ? 2 : 1, spv::ImageFormatUnknown); // TODO: translate format, needed for GLSL image ops
1365 // OpenGL "textures" need to be combined with a sampler
1366 if (! sampler.image)
1367 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001368 }
1369 break;
1370 case glslang::EbtStruct:
1371 case glslang::EbtBlock:
1372 {
1373 // If we've seen this struct type, return it
1374 const glslang::TTypeList* glslangStruct = type.getStruct();
1375 std::vector<spv::Id> structFields;
1376 spvType = structMap[glslangStruct];
1377 if (spvType)
1378 break;
1379
1380 // else, we haven't seen it...
1381
1382 // Create a vector of struct types for SPIR-V to consume
1383 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1384 if (type.getBasicType() == glslang::EbtBlock)
1385 memberRemapper[glslangStruct].resize(glslangStruct->size());
1386 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1387 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1388 if (glslangType.hiddenMember()) {
1389 ++memberDelta;
1390 if (type.getBasicType() == glslang::EbtBlock)
1391 memberRemapper[glslangStruct][i] = -1;
1392 } else {
1393 if (type.getBasicType() == glslang::EbtBlock)
1394 memberRemapper[glslangStruct][i] = i - memberDelta;
1395 structFields.push_back(convertGlslangToSpvType(glslangType));
1396 }
1397 }
1398
1399 // Make the SPIR-V type
1400 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1401 structMap[glslangStruct] = spvType;
1402
1403 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001404 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001405 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1406 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1407 int member = i;
1408 if (type.getBasicType() == glslang::EbtBlock)
1409 member = memberRemapper[glslangStruct][i];
1410 // using -1 above to indicate a hidden member
1411 if (member >= 0) {
1412 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1413 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1414 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1415 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1416 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1417 if (glslangType.getQualifier().hasLocation())
1418 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1419 if (glslangType.getQualifier().hasComponent())
1420 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1421 if (glslangType.getQualifier().hasXfbOffset())
1422 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001423 else {
1424 // figure out what to do with offset, which is accumulating
1425 int nextOffset;
1426 updateMemberOffset(type, glslangType, offset, nextOffset);
1427 if (offset >= 0)
1428 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutOffset);
1429 offset = nextOffset;
1430 }
John Kessenich140f3df2015-06-26 16:58:36 -06001431
1432 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001433 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1434 if (builtIn != spv::BadValue)
1435 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001436 }
1437 }
1438
1439 // Decorate the structure
1440 addDecoration(spvType, TranslateLayoutDecoration(type));
1441 addDecoration(spvType, TranslateBlockDecoration(type));
1442 if (type.getQualifier().hasStream())
1443 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1444 if (glslangIntermediate->getXfbMode()) {
1445 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001446 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001447 if (type.getQualifier().hasXfbBuffer())
1448 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1449 }
1450 }
1451 break;
1452 default:
1453 spv::MissingFunctionality("basic type");
1454 break;
1455 }
1456
1457 if (type.isMatrix())
1458 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1459 else {
1460 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1461 if (type.getVectorSize() > 1)
1462 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1463 }
1464
1465 if (type.isArray()) {
1466 unsigned arraySize;
1467 if (! type.isExplicitlySizedArray()) {
1468 spv::MissingFunctionality("Unsized array");
1469 arraySize = 8;
1470 } else
John Kessenich65c78a02015-08-10 17:08:55 -06001471 arraySize = type.getOuterArraySize();
John Kessenich140f3df2015-06-26 16:58:36 -06001472 spvType = builder.makeArrayType(spvType, arraySize);
1473 }
1474
1475 return spvType;
1476}
1477
John Kessenich5e4b1242015-08-06 22:53:06 -06001478// Given a member type of a struct, realign the current offset for it, and compute
1479// the next (not yet aligned) offset for the next member, which will get aligned
1480// on the next call.
1481// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1482// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1483// -1 means a non-forced member offset (no decoration needed).
1484void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1485{
1486 // this will get a positive value when deemed necessary
1487 nextOffset = -1;
1488
1489 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1490 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1491
1492 // override anything in currentOffset with user-set offset
1493 if (memberType.getQualifier().hasOffset())
1494 currentOffset = memberType.getQualifier().layoutOffset;
1495
1496 // It could be that current linker usage in glslang updated all the layoutOffset,
1497 // in which case the following code does not matter. But, that's not quite right
1498 // once cross-compilation unit GLSL validation is done, as the original user
1499 // settings are needed in layoutOffset, and then the following will come into play.
1500
1501 if (! forceOffset) {
1502 if (! memberType.getQualifier().hasOffset())
1503 currentOffset = -1;
1504
1505 return;
1506 }
1507
1508 // Getting this far means we are forcing offsets
1509 if (currentOffset < 0)
1510 currentOffset = 0;
1511
1512 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1513 // but possibly not yet correctly aligned.
1514
1515 int memberSize;
1516 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1517 glslang::RoundToPow2(currentOffset, memberAlignment);
1518 nextOffset = currentOffset + memberSize;
1519}
1520
John Kessenich140f3df2015-06-26 16:58:36 -06001521bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1522{
1523 return node->getName() == "main(";
1524}
1525
1526// Make all the functions, skeletally, without actually visiting their bodies.
1527void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1528{
1529 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1530 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1531 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1532 continue;
1533
1534 // We're on a user function. Set up the basic interface for the function now,
1535 // so that it's available to call.
1536 // Translating the body will happen later.
1537 //
1538 // Typically (except for a "const in" parameter), an address will be passed to the
1539 // function. What it is an address of varies:
1540 //
1541 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1542 // so that write needs to be to a copy, hence the address of a copy works.
1543 //
1544 // - "const in" parameters can just be the r-value, as no writes need occur.
1545 //
1546 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1547 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1548
1549 std::vector<spv::Id> paramTypes;
1550 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1551
1552 for (int p = 0; p < (int)parameters.size(); ++p) {
1553 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1554 spv::Id typeId = convertGlslangToSpvType(paramType);
1555 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1556 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1557 else
1558 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1559 paramTypes.push_back(typeId);
1560 }
1561
1562 spv::Block* functionBlock;
1563 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1564 paramTypes, &functionBlock);
1565
1566 // Track function to emit/call later
1567 functionMap[glslFunction->getName().c_str()] = function;
1568
1569 // Set the parameter id's
1570 for (int p = 0; p < (int)parameters.size(); ++p) {
1571 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1572 // give a name too
1573 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1574 }
1575 }
1576}
1577
1578// Process all the initializers, while skipping the functions and link objects
1579void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1580{
1581 builder.setBuildPoint(shaderEntry->getLastBlock());
1582 for (int i = 0; i < (int)initializers.size(); ++i) {
1583 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1584 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1585
1586 // We're on a top-level node that's not a function. Treat as an initializer, whose
1587 // code goes into the beginning of main.
1588 initializer->traverse(this);
1589 }
1590 }
1591}
1592
1593// Process all the functions, while skipping initializers.
1594void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1595{
1596 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1597 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1598 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1599 node->traverse(this);
1600 }
1601}
1602
1603void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1604{
1605 // SPIR-V functions should already be in the functionMap from the prepass
1606 // that called makeFunctions().
1607 spv::Function* function = functionMap[node->getName().c_str()];
1608 spv::Block* functionBlock = function->getEntryBlock();
1609 builder.setBuildPoint(functionBlock);
1610}
1611
1612void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments)
1613{
1614 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1615 builder.clearAccessChain();
1616 glslangArguments[i]->traverse(this);
1617 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArguments[i]->getAsTyped()->getType())));
1618 }
1619}
1620
John Kessenichfc51d282015-08-19 13:34:18 -06001621void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001622{
John Kessenichfc51d282015-08-19 13:34:18 -06001623 builder.clearAccessChain();
1624 node.getOperand()->traverse(this);
1625 arguments.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(node.getAsTyped()->getType())));
1626}
John Kessenich140f3df2015-06-26 16:58:36 -06001627
John Kessenichfc51d282015-08-19 13:34:18 -06001628spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1629{
1630 if (node->isImage()) {
1631 spv::MissingFunctionality("GLSL image function");
1632 return spv::NoResult;
1633 } else if (! node->isTexture()) {
1634 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001635 }
1636
John Kessenichfc51d282015-08-19 13:34:18 -06001637 // Process a GLSL texturing op (will be SPV image)
John Kessenich140f3df2015-06-26 16:58:36 -06001638
John Kessenichfc51d282015-08-19 13:34:18 -06001639 glslang::TCrackedTextureOp cracked;
1640 node->crackTexture(cracked);
1641
1642 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1643 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1644 std::vector<spv::Id> arguments;
1645 if (node->getAsAggregate())
1646 translateArguments(node->getAsAggregate()->getSequence(), arguments);
1647 else
1648 translateArguments(*node->getAsUnaryNode(), arguments);
1649 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1650
1651 spv::Builder::TextureParameters params = { };
1652 params.sampler = arguments[0];
1653
1654 // Check for queries
1655 if (cracked.query) {
1656 switch (node->getOp()) {
1657 case glslang::EOpImageQuerySize:
1658 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001659 if (arguments.size() > 1) {
1660 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001661 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001662 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001663 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001664 case glslang::EOpImageQuerySamples:
1665 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001666 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001667 case glslang::EOpTextureQueryLod:
1668 params.coords = arguments[1];
1669 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1670 case glslang::EOpTextureQueryLevels:
1671 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1672 default:
1673 assert(0);
1674 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001675 }
John Kessenich140f3df2015-06-26 16:58:36 -06001676 }
1677
John Kessenichfc51d282015-08-19 13:34:18 -06001678 // This is no longer a query....
John Kessenich140f3df2015-06-26 16:58:36 -06001679
John Kessenichfc51d282015-08-19 13:34:18 -06001680 if (cracked.fetch)
1681 spv::MissingFunctionality("texel fetch");
1682 if (cracked.gather)
1683 spv::MissingFunctionality("texture gather");
1684
1685 // check for bias argument
1686 bool bias = false;
1687 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1688 int nonBiasArgCount = 2;
1689 if (cracked.offset)
1690 ++nonBiasArgCount;
1691 if (cracked.grad)
1692 nonBiasArgCount += 2;
1693
1694 if ((int)arguments.size() > nonBiasArgCount)
1695 bias = true;
1696 }
1697
1698 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1699
1700 // set the rest of the arguments
1701 params.coords = arguments[1];
1702 int extraArgs = 0;
1703 if (cubeCompare)
1704 params.Dref = arguments[2];
1705 else if (sampler.shadow) {
1706 std::vector<spv::Id> indexes;
1707 int comp;
1708 if (cracked.proj)
1709 comp = 3;
1710 else
1711 comp = builder.getNumComponents(params.coords) - 1;
1712 indexes.push_back(comp);
1713 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1714 }
1715 if (cracked.lod) {
1716 params.lod = arguments[2];
1717 ++extraArgs;
1718 }
1719 if (cracked.grad) {
1720 params.gradX = arguments[2 + extraArgs];
1721 params.gradY = arguments[3 + extraArgs];
1722 extraArgs += 2;
1723 }
1724 //if (gather && compare) {
1725 // params.compare = arguments[2 + extraArgs];
1726 // ++extraArgs;
1727 //}
1728 if (cracked.offset || cracked.offsets) {
1729 params.offset = arguments[2 + extraArgs];
1730 ++extraArgs;
1731 }
1732 if (bias) {
1733 params.bias = arguments[2 + extraArgs];
1734 ++extraArgs;
1735 }
1736
1737 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001738}
1739
1740spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1741{
1742 // Grab the function's pointer from the previously created function
1743 spv::Function* function = functionMap[node->getName().c_str()];
1744 if (! function)
1745 return 0;
1746
1747 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1748 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1749
1750 // See comments in makeFunctions() for details about the semantics for parameter passing.
1751 //
1752 // These imply we need a four step process:
1753 // 1. Evaluate the arguments
1754 // 2. Allocate and make copies of in, out, and inout arguments
1755 // 3. Make the call
1756 // 4. Copy back the results
1757
1758 // 1. Evaluate the arguments
1759 std::vector<spv::Builder::AccessChain> lValues;
1760 std::vector<spv::Id> rValues;
1761 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1762 // build l-value
1763 builder.clearAccessChain();
1764 glslangArgs[a]->traverse(this);
1765 // keep outputs as l-values, evaluate input-only as r-values
1766 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1767 // save l-value
1768 lValues.push_back(builder.getAccessChain());
1769 } else {
1770 // process r-value
1771 rValues.push_back(builder.accessChainLoad(TranslatePrecisionDecoration(glslangArgs[a]->getAsTyped()->getType())));
1772 }
1773 }
1774
1775 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1776 // copy the original into that space.
1777 //
1778 // Also, build up the list of actual arguments to pass in for the call
1779 int lValueCount = 0;
1780 int rValueCount = 0;
1781 std::vector<spv::Id> spvArgs;
1782 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1783 spv::Id arg;
1784 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1785 // need space to hold the copy
1786 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1787 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1788 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1789 // need to copy the input into output space
1790 builder.setAccessChain(lValues[lValueCount]);
1791 spv::Id copy = builder.accessChainLoad(spv::NoPrecision); // TODO: get precision
1792 builder.createStore(copy, arg);
1793 }
1794 ++lValueCount;
1795 } else {
1796 arg = rValues[rValueCount];
1797 ++rValueCount;
1798 }
1799 spvArgs.push_back(arg);
1800 }
1801
1802 // 3. Make the call.
1803 spv::Id result = builder.createFunctionCall(function, spvArgs);
1804
1805 // 4. Copy back out an "out" arguments.
1806 lValueCount = 0;
1807 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1808 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1809 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1810 spv::Id copy = builder.createLoad(spvArgs[a]);
1811 builder.setAccessChain(lValues[lValueCount]);
1812 builder.accessChainStore(copy);
1813 }
1814 ++lValueCount;
1815 }
1816 }
1817
1818 return result;
1819}
1820
1821// Translate AST operation to SPV operation, already having SPV-based operands/types.
1822spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
1823 spv::Id typeId, spv::Id left, spv::Id right,
1824 glslang::TBasicType typeProxy, bool reduceComparison)
1825{
1826 bool isUnsigned = typeProxy == glslang::EbtUint;
1827 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
1828
1829 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06001830 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06001831 bool comparison = false;
1832
1833 switch (op) {
1834 case glslang::EOpAdd:
1835 case glslang::EOpAddAssign:
1836 if (isFloat)
1837 binOp = spv::OpFAdd;
1838 else
1839 binOp = spv::OpIAdd;
1840 break;
1841 case glslang::EOpSub:
1842 case glslang::EOpSubAssign:
1843 if (isFloat)
1844 binOp = spv::OpFSub;
1845 else
1846 binOp = spv::OpISub;
1847 break;
1848 case glslang::EOpMul:
1849 case glslang::EOpMulAssign:
1850 if (isFloat)
1851 binOp = spv::OpFMul;
1852 else
1853 binOp = spv::OpIMul;
1854 break;
1855 case glslang::EOpVectorTimesScalar:
1856 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06001857 if (isFloat) {
1858 if (builder.isVector(right))
1859 std::swap(left, right);
1860 assert(builder.isScalar(right));
1861 needMatchingVectors = false;
1862 binOp = spv::OpVectorTimesScalar;
1863 } else
1864 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06001865 break;
1866 case glslang::EOpVectorTimesMatrix:
1867 case glslang::EOpVectorTimesMatrixAssign:
1868 assert(builder.isVector(left));
1869 assert(builder.isMatrix(right));
1870 binOp = spv::OpVectorTimesMatrix;
1871 break;
1872 case glslang::EOpMatrixTimesVector:
1873 assert(builder.isMatrix(left));
1874 assert(builder.isVector(right));
1875 binOp = spv::OpMatrixTimesVector;
1876 break;
1877 case glslang::EOpMatrixTimesScalar:
1878 case glslang::EOpMatrixTimesScalarAssign:
1879 if (builder.isMatrix(right))
1880 std::swap(left, right);
1881 assert(builder.isScalar(right));
1882 binOp = spv::OpMatrixTimesScalar;
1883 break;
1884 case glslang::EOpMatrixTimesMatrix:
1885 case glslang::EOpMatrixTimesMatrixAssign:
1886 assert(builder.isMatrix(left));
1887 assert(builder.isMatrix(right));
1888 binOp = spv::OpMatrixTimesMatrix;
1889 break;
1890 case glslang::EOpOuterProduct:
1891 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06001892 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001893 break;
1894
1895 case glslang::EOpDiv:
1896 case glslang::EOpDivAssign:
1897 if (isFloat)
1898 binOp = spv::OpFDiv;
1899 else if (isUnsigned)
1900 binOp = spv::OpUDiv;
1901 else
1902 binOp = spv::OpSDiv;
1903 break;
1904 case glslang::EOpMod:
1905 case glslang::EOpModAssign:
1906 if (isFloat)
1907 binOp = spv::OpFMod;
1908 else if (isUnsigned)
1909 binOp = spv::OpUMod;
1910 else
1911 binOp = spv::OpSMod;
1912 break;
1913 case glslang::EOpRightShift:
1914 case glslang::EOpRightShiftAssign:
1915 if (isUnsigned)
1916 binOp = spv::OpShiftRightLogical;
1917 else
1918 binOp = spv::OpShiftRightArithmetic;
1919 break;
1920 case glslang::EOpLeftShift:
1921 case glslang::EOpLeftShiftAssign:
1922 binOp = spv::OpShiftLeftLogical;
1923 break;
1924 case glslang::EOpAnd:
1925 case glslang::EOpAndAssign:
1926 binOp = spv::OpBitwiseAnd;
1927 break;
1928 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06001929 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001930 binOp = spv::OpLogicalAnd;
1931 break;
1932 case glslang::EOpInclusiveOr:
1933 case glslang::EOpInclusiveOrAssign:
1934 binOp = spv::OpBitwiseOr;
1935 break;
1936 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06001937 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001938 binOp = spv::OpLogicalOr;
1939 break;
1940 case glslang::EOpExclusiveOr:
1941 case glslang::EOpExclusiveOrAssign:
1942 binOp = spv::OpBitwiseXor;
1943 break;
1944 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06001945 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06001946 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06001947 break;
1948
1949 case glslang::EOpLessThan:
1950 case glslang::EOpGreaterThan:
1951 case glslang::EOpLessThanEqual:
1952 case glslang::EOpGreaterThanEqual:
1953 case glslang::EOpEqual:
1954 case glslang::EOpNotEqual:
1955 case glslang::EOpVectorEqual:
1956 case glslang::EOpVectorNotEqual:
1957 comparison = true;
1958 break;
1959 default:
1960 break;
1961 }
1962
1963 if (binOp != spv::OpNop) {
1964 if (builder.isMatrix(left) || builder.isMatrix(right)) {
1965 switch (binOp) {
1966 case spv::OpMatrixTimesScalar:
1967 case spv::OpVectorTimesMatrix:
1968 case spv::OpMatrixTimesVector:
1969 case spv::OpMatrixTimesMatrix:
1970 break;
1971 case spv::OpFDiv:
1972 // turn it into a multiply...
1973 assert(builder.isMatrix(left) && builder.isScalar(right));
1974 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
1975 binOp = spv::OpFMul;
1976 break;
1977 default:
1978 spv::MissingFunctionality("binary operation on matrix");
1979 break;
1980 }
1981
1982 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
1983 builder.setPrecision(id, precision);
1984
1985 return id;
1986 }
1987
1988 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06001989 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06001990 builder.promoteScalar(precision, left, right);
1991
1992 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
1993 builder.setPrecision(id, precision);
1994
1995 return id;
1996 }
1997
1998 if (! comparison)
1999 return 0;
2000
2001 // Comparison instructions
2002
2003 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2004 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2005
2006 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2007 }
2008
2009 switch (op) {
2010 case glslang::EOpLessThan:
2011 if (isFloat)
2012 binOp = spv::OpFOrdLessThan;
2013 else if (isUnsigned)
2014 binOp = spv::OpULessThan;
2015 else
2016 binOp = spv::OpSLessThan;
2017 break;
2018 case glslang::EOpGreaterThan:
2019 if (isFloat)
2020 binOp = spv::OpFOrdGreaterThan;
2021 else if (isUnsigned)
2022 binOp = spv::OpUGreaterThan;
2023 else
2024 binOp = spv::OpSGreaterThan;
2025 break;
2026 case glslang::EOpLessThanEqual:
2027 if (isFloat)
2028 binOp = spv::OpFOrdLessThanEqual;
2029 else if (isUnsigned)
2030 binOp = spv::OpULessThanEqual;
2031 else
2032 binOp = spv::OpSLessThanEqual;
2033 break;
2034 case glslang::EOpGreaterThanEqual:
2035 if (isFloat)
2036 binOp = spv::OpFOrdGreaterThanEqual;
2037 else if (isUnsigned)
2038 binOp = spv::OpUGreaterThanEqual;
2039 else
2040 binOp = spv::OpSGreaterThanEqual;
2041 break;
2042 case glslang::EOpEqual:
2043 case glslang::EOpVectorEqual:
2044 if (isFloat)
2045 binOp = spv::OpFOrdEqual;
2046 else
2047 binOp = spv::OpIEqual;
2048 break;
2049 case glslang::EOpNotEqual:
2050 case glslang::EOpVectorNotEqual:
2051 if (isFloat)
2052 binOp = spv::OpFOrdNotEqual;
2053 else
2054 binOp = spv::OpINotEqual;
2055 break;
2056 default:
2057 break;
2058 }
2059
2060 if (binOp != spv::OpNop) {
2061 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2062 builder.setPrecision(id, precision);
2063
2064 return id;
2065 }
2066
2067 return 0;
2068}
2069
2070spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat)
2071{
2072 spv::Op unaryOp = spv::OpNop;
2073 int libCall = -1;
2074
2075 switch (op) {
2076 case glslang::EOpNegative:
2077 if (isFloat)
2078 unaryOp = spv::OpFNegate;
2079 else
2080 unaryOp = spv::OpSNegate;
2081 break;
2082
2083 case glslang::EOpLogicalNot:
2084 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002085 unaryOp = spv::OpLogicalNot;
2086 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002087 case glslang::EOpBitwiseNot:
2088 unaryOp = spv::OpNot;
2089 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002090
John Kessenich140f3df2015-06-26 16:58:36 -06002091 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002092 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002093 break;
2094 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002095 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002096 break;
2097 case glslang::EOpTranspose:
2098 unaryOp = spv::OpTranspose;
2099 break;
2100
2101 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002102 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002103 break;
2104 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002105 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002106 break;
2107 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002108 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002109 break;
2110 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002111 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002112 break;
2113 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002114 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002115 break;
2116 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002117 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002118 break;
2119 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002120 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002121 break;
2122 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002123 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002124 break;
2125
2126 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002127 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002128 break;
2129 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002130 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002131 break;
2132 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002133 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002134 break;
2135 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002136 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002137 break;
2138 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002139 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002140 break;
2141 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002142 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002143 break;
2144
2145 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002146 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002147 break;
2148 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002149 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002150 break;
2151
2152 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002153 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002154 break;
2155 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002156 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002157 break;
2158 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002159 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002160 break;
2161 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002162 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002163 break;
2164 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002165 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002166 break;
2167 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002168 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002169 break;
2170
2171 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002172 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002173 break;
2174 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002175 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002176 break;
2177 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002178 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002179 break;
2180 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002181 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002182 break;
2183 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002184 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002185 break;
2186 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002187 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002188 break;
2189
2190 case glslang::EOpIsNan:
2191 unaryOp = spv::OpIsNan;
2192 break;
2193 case glslang::EOpIsInf:
2194 unaryOp = spv::OpIsInf;
2195 break;
2196
John Kessenich140f3df2015-06-26 16:58:36 -06002197 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002198 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002199 break;
2200 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002201 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002202 break;
2203 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002204 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002205 break;
2206 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002207 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002208 break;
2209 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002210 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002211 break;
2212 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002213 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002214 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002215 case glslang::EOpPackSnorm4x8:
2216 libCall = spv::GLSLstd450PackSnorm4x8;
2217 break;
2218 case glslang::EOpUnpackSnorm4x8:
2219 libCall = spv::GLSLstd450UnpackSnorm4x8;
2220 break;
2221 case glslang::EOpPackUnorm4x8:
2222 libCall = spv::GLSLstd450PackUnorm4x8;
2223 break;
2224 case glslang::EOpUnpackUnorm4x8:
2225 libCall = spv::GLSLstd450UnpackUnorm4x8;
2226 break;
2227 case glslang::EOpPackDouble2x32:
2228 libCall = spv::GLSLstd450PackDouble2x32;
2229 break;
2230 case glslang::EOpUnpackDouble2x32:
2231 libCall = spv::GLSLstd450UnpackDouble2x32;
2232 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002233
2234 case glslang::EOpDPdx:
2235 unaryOp = spv::OpDPdx;
2236 break;
2237 case glslang::EOpDPdy:
2238 unaryOp = spv::OpDPdy;
2239 break;
2240 case glslang::EOpFwidth:
2241 unaryOp = spv::OpFwidth;
2242 break;
2243 case glslang::EOpDPdxFine:
2244 unaryOp = spv::OpDPdxFine;
2245 break;
2246 case glslang::EOpDPdyFine:
2247 unaryOp = spv::OpDPdyFine;
2248 break;
2249 case glslang::EOpFwidthFine:
2250 unaryOp = spv::OpFwidthFine;
2251 break;
2252 case glslang::EOpDPdxCoarse:
2253 unaryOp = spv::OpDPdxCoarse;
2254 break;
2255 case glslang::EOpDPdyCoarse:
2256 unaryOp = spv::OpDPdyCoarse;
2257 break;
2258 case glslang::EOpFwidthCoarse:
2259 unaryOp = spv::OpFwidthCoarse;
2260 break;
2261
2262 case glslang::EOpAny:
2263 unaryOp = spv::OpAny;
2264 break;
2265 case glslang::EOpAll:
2266 unaryOp = spv::OpAll;
2267 break;
2268
2269 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002270 if (isFloat)
2271 libCall = spv::GLSLstd450FAbs;
2272 else
2273 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002274 break;
2275 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002276 if (isFloat)
2277 libCall = spv::GLSLstd450FSign;
2278 else
2279 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002280 break;
2281
John Kessenichfc51d282015-08-19 13:34:18 -06002282 case glslang::EOpAtomicCounterIncrement:
2283 case glslang::EOpAtomicCounterDecrement:
2284 case glslang::EOpAtomicCounter:
2285 {
2286 // Handle all of the atomics in one place, in createAtomicOperation()
2287 std::vector<spv::Id> operands;
2288 operands.push_back(operand);
2289 return createAtomicOperation(op, precision, typeId, operands);
2290 }
2291
2292 case glslang::EOpImageLoad:
2293 unaryOp = spv::OpImageRead;
2294 break;
2295
2296 case glslang::EOpBitFieldReverse:
2297 unaryOp = spv::OpBitReverse;
2298 break;
2299 case glslang::EOpBitCount:
2300 unaryOp = spv::OpBitCount;
2301 break;
2302 case glslang::EOpFindLSB:
2303 libCall = spv::GLSLstd450FindILSB;
2304 break;
2305 case glslang::EOpFindMSB:
2306 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2307 libCall = spv::GLSLstd450FindSMSB;
2308 break;
2309
John Kessenich140f3df2015-06-26 16:58:36 -06002310 default:
2311 return 0;
2312 }
2313
2314 spv::Id id;
2315 if (libCall >= 0) {
2316 std::vector<spv::Id> args;
2317 args.push_back(operand);
2318 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2319 } else
2320 id = builder.createUnaryOp(unaryOp, typeId, operand);
2321
2322 builder.setPrecision(id, precision);
2323
2324 return id;
2325}
2326
2327spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2328{
2329 spv::Op convOp = spv::OpNop;
2330 spv::Id zero = 0;
2331 spv::Id one = 0;
2332
2333 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2334
2335 switch (op) {
2336 case glslang::EOpConvIntToBool:
2337 case glslang::EOpConvUintToBool:
2338 zero = builder.makeUintConstant(0);
2339 zero = makeSmearedConstant(zero, vectorSize);
2340 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2341
2342 case glslang::EOpConvFloatToBool:
2343 zero = builder.makeFloatConstant(0.0F);
2344 zero = makeSmearedConstant(zero, vectorSize);
2345 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2346
2347 case glslang::EOpConvDoubleToBool:
2348 zero = builder.makeDoubleConstant(0.0);
2349 zero = makeSmearedConstant(zero, vectorSize);
2350 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2351
2352 case glslang::EOpConvBoolToFloat:
2353 convOp = spv::OpSelect;
2354 zero = builder.makeFloatConstant(0.0);
2355 one = builder.makeFloatConstant(1.0);
2356 break;
2357 case glslang::EOpConvBoolToDouble:
2358 convOp = spv::OpSelect;
2359 zero = builder.makeDoubleConstant(0.0);
2360 one = builder.makeDoubleConstant(1.0);
2361 break;
2362 case glslang::EOpConvBoolToInt:
2363 zero = builder.makeIntConstant(0);
2364 one = builder.makeIntConstant(1);
2365 convOp = spv::OpSelect;
2366 break;
2367 case glslang::EOpConvBoolToUint:
2368 zero = builder.makeUintConstant(0);
2369 one = builder.makeUintConstant(1);
2370 convOp = spv::OpSelect;
2371 break;
2372
2373 case glslang::EOpConvIntToFloat:
2374 case glslang::EOpConvIntToDouble:
2375 convOp = spv::OpConvertSToF;
2376 break;
2377
2378 case glslang::EOpConvUintToFloat:
2379 case glslang::EOpConvUintToDouble:
2380 convOp = spv::OpConvertUToF;
2381 break;
2382
2383 case glslang::EOpConvDoubleToFloat:
2384 case glslang::EOpConvFloatToDouble:
2385 convOp = spv::OpFConvert;
2386 break;
2387
2388 case glslang::EOpConvFloatToInt:
2389 case glslang::EOpConvDoubleToInt:
2390 convOp = spv::OpConvertFToS;
2391 break;
2392
2393 case glslang::EOpConvUintToInt:
2394 case glslang::EOpConvIntToUint:
2395 convOp = spv::OpBitcast;
2396 break;
2397
2398 case glslang::EOpConvFloatToUint:
2399 case glslang::EOpConvDoubleToUint:
2400 convOp = spv::OpConvertFToU;
2401 break;
2402 default:
2403 break;
2404 }
2405
2406 spv::Id result = 0;
2407 if (convOp == spv::OpNop)
2408 return result;
2409
2410 if (convOp == spv::OpSelect) {
2411 zero = makeSmearedConstant(zero, vectorSize);
2412 one = makeSmearedConstant(one, vectorSize);
2413 result = builder.createTriOp(convOp, destType, operand, one, zero);
2414 } else
2415 result = builder.createUnaryOp(convOp, destType, operand);
2416
2417 builder.setPrecision(result, precision);
2418
2419 return result;
2420}
2421
2422spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2423{
2424 if (vectorSize == 0)
2425 return constant;
2426
2427 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2428 std::vector<spv::Id> components;
2429 for (int c = 0; c < vectorSize; ++c)
2430 components.push_back(constant);
2431 return builder.makeCompositeConstant(vectorTypeId, components);
2432}
2433
John Kessenich426394d2015-07-23 10:22:48 -06002434// For glslang ops that map to SPV atomic opCodes
2435spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands)
2436{
2437 spv::Op opCode = spv::OpNop;
2438
2439 switch (op) {
2440 case glslang::EOpAtomicAdd:
2441 opCode = spv::OpAtomicIAdd;
2442 break;
2443 case glslang::EOpAtomicMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002444 opCode = spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002445 break;
2446 case glslang::EOpAtomicMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002447 opCode = spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002448 break;
2449 case glslang::EOpAtomicAnd:
2450 opCode = spv::OpAtomicAnd;
2451 break;
2452 case glslang::EOpAtomicOr:
2453 opCode = spv::OpAtomicOr;
2454 break;
2455 case glslang::EOpAtomicXor:
2456 opCode = spv::OpAtomicXor;
2457 break;
2458 case glslang::EOpAtomicExchange:
2459 opCode = spv::OpAtomicExchange;
2460 break;
2461 case glslang::EOpAtomicCompSwap:
2462 opCode = spv::OpAtomicCompareExchange;
2463 break;
2464 case glslang::EOpAtomicCounterIncrement:
2465 opCode = spv::OpAtomicIIncrement;
2466 break;
2467 case glslang::EOpAtomicCounterDecrement:
2468 opCode = spv::OpAtomicIDecrement;
2469 break;
2470 case glslang::EOpAtomicCounter:
2471 opCode = spv::OpAtomicLoad;
2472 break;
2473 default:
2474 spv::MissingFunctionality("missing nested atomic");
2475 break;
2476 }
2477
2478 // Sort out the operands
2479 // - mapping from glslang -> SPV
2480 // - there are extra SPV operands with no glslang source
2481 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2482 auto opIt = operands.begin(); // walk the glslang operands
2483 spvAtomicOperands.push_back(*(opIt++));
Rex Xud4782c12015-09-06 16:30:11 +08002484 spvAtomicOperands.push_back(spv::ScopeDevice); // TBD: what is the correct scope?
2485 spvAtomicOperands.push_back(spv::MemorySemanticsMaskNone); // TBD: what are the correct memory semantics?
John Kessenich426394d2015-07-23 10:22:48 -06002486
2487 // Add the rest of the operands, skipping the first one, which was dealt with above.
2488 // For some ops, there are none, for some 1, for compare-exchange, 2.
2489 for (; opIt != operands.end(); ++opIt)
2490 spvAtomicOperands.push_back(*opIt);
2491
2492 return builder.createOp(opCode, typeId, spvAtomicOperands);
2493}
2494
John Kessenich5e4b1242015-08-06 22:53:06 -06002495spv::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 -06002496{
John Kessenich5e4b1242015-08-06 22:53:06 -06002497 bool isUnsigned = typeProxy == glslang::EbtUint;
2498 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2499
John Kessenich140f3df2015-06-26 16:58:36 -06002500 spv::Op opCode = spv::OpNop;
2501 int libCall = -1;
2502
2503 switch (op) {
2504 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002505 if (isFloat)
2506 libCall = spv::GLSLstd450FMin;
2507 else if (isUnsigned)
2508 libCall = spv::GLSLstd450UMin;
2509 else
2510 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002511 break;
2512 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002513 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002514 break;
2515 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002516 if (isFloat)
2517 libCall = spv::GLSLstd450FMax;
2518 else if (isUnsigned)
2519 libCall = spv::GLSLstd450UMax;
2520 else
2521 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002522 break;
2523 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002524 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002525 break;
2526 case glslang::EOpDot:
2527 opCode = spv::OpDot;
2528 break;
2529 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002530 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002531 break;
2532
2533 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002534 if (isFloat)
2535 libCall = spv::GLSLstd450FClamp;
2536 else if (isUnsigned)
2537 libCall = spv::GLSLstd450UClamp;
2538 else
2539 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002540 break;
2541 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002542 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002543 break;
2544 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002545 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002546 break;
2547 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002548 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002549 break;
2550
2551 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002552 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002553 break;
2554 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002555 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002556 break;
2557 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002558 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002559 break;
2560 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002561 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002562 break;
2563 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002564 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002565 break;
John Kessenich426394d2015-07-23 10:22:48 -06002566
John Kessenich140f3df2015-06-26 16:58:36 -06002567 default:
2568 return 0;
2569 }
2570
2571 spv::Id id = 0;
2572 if (libCall >= 0)
2573 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2574 else {
2575 switch (operands.size()) {
2576 case 0:
2577 // should all be handled by visitAggregate and createNoArgOperation
2578 assert(0);
2579 return 0;
2580 case 1:
2581 // should all be handled by createUnaryOperation
2582 assert(0);
2583 return 0;
2584 case 2:
2585 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2586 break;
2587 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002588 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002589 break;
2590 default:
2591 // These do not exist yet
2592 assert(0 && "operation with more than 3 operands");
2593 break;
2594 }
2595 }
2596
2597 builder.setPrecision(id, precision);
2598
2599 return id;
2600}
2601
2602// Intrinsics with no arguments, no return value, and no precision.
2603spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2604{
2605 // TODO: get the barrier operands correct
2606
2607 switch (op) {
2608 case glslang::EOpEmitVertex:
2609 builder.createNoResultOp(spv::OpEmitVertex);
2610 return 0;
2611 case glslang::EOpEndPrimitive:
2612 builder.createNoResultOp(spv::OpEndPrimitive);
2613 return 0;
2614 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002615 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2616 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002617 return 0;
2618 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002619 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002620 return 0;
2621 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002622 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002623 return 0;
2624 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002625 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002626 return 0;
2627 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002628 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002629 return 0;
2630 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002631 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002632 return 0;
2633 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002634 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002635 return 0;
2636 default:
2637 spv::MissingFunctionality("operation with no arguments");
2638 return 0;
2639 }
2640}
2641
2642spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2643{
John Kessenich2f273362015-07-18 22:34:27 -06002644 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002645 spv::Id id;
2646 if (symbolValues.end() != iter) {
2647 id = iter->second;
2648 return id;
2649 }
2650
2651 // it was not found, create it
2652 id = createSpvVariable(symbol);
2653 symbolValues[symbol->getId()] = id;
2654
2655 if (! symbol->getType().isStruct()) {
2656 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2657 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2658 if (symbol->getQualifier().hasLocation())
2659 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2660 if (symbol->getQualifier().hasIndex())
2661 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2662 if (symbol->getQualifier().hasComponent())
2663 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2664 if (glslangIntermediate->getXfbMode()) {
2665 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002666 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002667 if (symbol->getQualifier().hasXfbBuffer())
2668 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2669 if (symbol->getQualifier().hasXfbOffset())
2670 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2671 }
2672 }
2673
2674 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2675 if (symbol->getQualifier().hasStream())
2676 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2677 if (symbol->getQualifier().hasSet())
2678 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2679 if (symbol->getQualifier().hasBinding())
2680 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2681 if (glslangIntermediate->getXfbMode()) {
2682 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002683 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002684 if (symbol->getQualifier().hasXfbBuffer())
2685 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2686 }
2687
2688 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002689 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002690 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002691 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002692
2693 if (linkageOnly)
2694 builder.addDecoration(id, spv::DecorationNoStaticUse);
2695
2696 return id;
2697}
2698
2699void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2700{
2701 if (dec != spv::BadValue)
2702 builder.addDecoration(id, dec);
2703}
2704
2705void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2706{
2707 if (dec != spv::BadValue)
2708 builder.addMemberDecoration(id, (unsigned)member, dec);
2709}
2710
2711// Use 'consts' as the flattened glslang source of scalar constants to recursively
2712// build the aggregate SPIR-V constant.
2713//
2714// If there are not enough elements present in 'consts', 0 will be substituted;
2715// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2716//
2717spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2718{
2719 // vector of constants for SPIR-V
2720 std::vector<spv::Id> spvConsts;
2721
2722 // Type is used for struct and array constants
2723 spv::Id typeId = convertGlslangToSpvType(glslangType);
2724
2725 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002726 glslang::TType elementType(glslangType, 0);
2727 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002728 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2729 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002730 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002731 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2732 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2733 } else if (glslangType.getStruct()) {
2734 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2735 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2736 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2737 } else if (glslangType.isVector()) {
2738 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2739 bool zero = nextConst >= consts.size();
2740 switch (glslangType.getBasicType()) {
2741 case glslang::EbtInt:
2742 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2743 break;
2744 case glslang::EbtUint:
2745 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2746 break;
2747 case glslang::EbtFloat:
2748 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2749 break;
2750 case glslang::EbtDouble:
2751 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2752 break;
2753 case glslang::EbtBool:
2754 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2755 break;
2756 default:
2757 spv::MissingFunctionality("constant vector type");
2758 break;
2759 }
2760 ++nextConst;
2761 }
2762 } else {
2763 // we have a non-aggregate (scalar) constant
2764 bool zero = nextConst >= consts.size();
2765 spv::Id scalar = 0;
2766 switch (glslangType.getBasicType()) {
2767 case glslang::EbtInt:
2768 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2769 break;
2770 case glslang::EbtUint:
2771 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2772 break;
2773 case glslang::EbtFloat:
2774 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2775 break;
2776 case glslang::EbtDouble:
2777 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2778 break;
2779 case glslang::EbtBool:
2780 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2781 break;
2782 default:
2783 spv::MissingFunctionality("constant scalar type");
2784 break;
2785 }
2786 ++nextConst;
2787 return scalar;
2788 }
2789
2790 return builder.makeCompositeConstant(typeId, spvConsts);
2791}
2792
2793}; // end anonymous namespace
2794
2795namespace glslang {
2796
John Kessenich68d78fd2015-07-12 19:28:10 -06002797void GetSpirvVersion(std::string& version)
2798{
John Kessenich9e55f632015-07-15 10:03:39 -06002799 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002800 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002801 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002802 version = buf;
2803}
2804
John Kessenich140f3df2015-06-26 16:58:36 -06002805// Write SPIR-V out to a binary file
2806void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
2807{
2808 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06002809 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06002810 for (int i = 0; i < (int)spirv.size(); ++i) {
2811 unsigned int word = spirv[i];
2812 out.write((const char*)&word, 4);
2813 }
2814 out.close();
2815}
2816
2817//
2818// Set up the glslang traversal
2819//
2820void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
2821{
2822 TIntermNode* root = intermediate.getTreeRoot();
2823
2824 if (root == 0)
2825 return;
2826
2827 glslang::GetThreadPoolAllocator().push();
2828
2829 TGlslangToSpvTraverser it(&intermediate);
2830
2831 root->traverse(&it);
2832
2833 it.dumpSpv(spirv);
2834
2835 glslang::GetThreadPoolAllocator().pop();
2836}
2837
2838}; // end namespace glslang