blob: 0240dea096a503de30ad5e30f19f9e5d52e4e99f [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
2//Copyright (C) 2014 LunarG, Inc.
3//
4//All rights reserved.
5//
6//Redistribution and use in source and binary forms, with or without
7//modification, are permitted provided that the following conditions
8//are met:
9//
10// Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//
13// Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following
15// disclaimer in the documentation and/or other materials provided
16// with the distribution.
17//
18// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19// contributors may be used to endorse or promote products derived
20// from this software without specific prior written permission.
21//
22//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33//POSSIBILITY OF SUCH DAMAGE.
34
35//
36// Author: John Kessenich, LunarG
37//
38// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
46 #include "GLSL.std.450.h"
47}
John Kessenich140f3df2015-06-26 16:58:36 -060048
49// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020050#include "../glslang/MachineIndependent/localintermediate.h"
51#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060053
54#include <string>
55#include <map>
56#include <list>
57#include <vector>
58#include <stack>
59#include <fstream>
60
61namespace {
62
63const int GlslangMagic = 0x51a;
64
65//
66// The main holder of information for translating glslang to SPIR-V.
67//
68// Derives from the AST walking base class.
69//
70class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
71public:
72 TGlslangToSpvTraverser(const glslang::TIntermediate*);
73 virtual ~TGlslangToSpvTraverser();
74
75 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
76 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
77 void visitConstantUnion(glslang::TIntermConstantUnion*);
78 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
79 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
80 void visitSymbol(glslang::TIntermSymbol* symbol);
81 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
82 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
83 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
84
85 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
86
87protected:
88 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
89 spv::Id getSampledType(const glslang::TSampler&);
90 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich31ed4832015-09-09 17:51:38 -060091 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout);
92 bool requiresExplicitLayout(const glslang::TType& type) const;
Jason Ekstrand54aedf12015-09-05 09:50:58 -070093 int getArrayStride(const glslang::TType& arrayType);
94 int getMatrixStride(const glslang::TType& matrixType);
John Kessenich5e4b1242015-08-06 22:53:06 -060095 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060096
97 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
98 void makeFunctions(const glslang::TIntermSequence&);
99 void makeGlobalInitializers(const glslang::TIntermSequence&);
100 void visitFunctions(const glslang::TIntermSequence&);
101 void handleFunctionEntry(const glslang::TIntermAggregate* node);
102 void translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600103 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
104 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600105 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
106
107 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
108 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat);
109 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
110 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
John Kessenich426394d2015-07-23 10:22:48 -0600111 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600112 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600113 spv::Id createNoArgOperation(glslang::TOperator op);
114 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
115 void addDecoration(spv::Id id, spv::Decoration dec);
116 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
117 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
118
119 spv::Function* shaderEntry;
120 int sequenceDepth;
121
122 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
123 spv::Builder builder;
124 bool inMain;
125 bool mainTerminated;
126 bool linkageOnly;
127 const glslang::TIntermediate* glslangIntermediate;
128 spv::Id stdBuiltins;
129
John Kessenich2f273362015-07-18 22:34:27 -0600130 std::unordered_map<int, spv::Id> symbolValues;
131 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
132 std::unordered_map<std::string, spv::Function*> functionMap;
133 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap;
134 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 -0600135 std::stack<bool> breakForLoop; // false means break for switch
136 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
137};
138
139//
140// Helper functions for translating glslang representations to SPIR-V enumerants.
141//
142
143// Translate glslang profile to SPIR-V source language.
144spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
145{
146 switch (profile) {
147 case ENoProfile:
148 case ECoreProfile:
149 case ECompatibilityProfile:
150 return spv::SourceLanguageGLSL;
151 case EEsProfile:
152 return spv::SourceLanguageESSL;
153 default:
154 return spv::SourceLanguageUnknown;
155 }
156}
157
158// Translate glslang language (stage) to SPIR-V execution model.
159spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
160{
161 switch (stage) {
162 case EShLangVertex: return spv::ExecutionModelVertex;
163 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
164 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
165 case EShLangGeometry: return spv::ExecutionModelGeometry;
166 case EShLangFragment: return spv::ExecutionModelFragment;
167 case EShLangCompute: return spv::ExecutionModelGLCompute;
168 default:
169 spv::MissingFunctionality("GLSL stage");
170 return spv::ExecutionModelFragment;
171 }
172}
173
174// Translate glslang type to SPIR-V storage class.
175spv::StorageClass TranslateStorageClass(const glslang::TType& type)
176{
177 if (type.getQualifier().isPipeInput())
178 return spv::StorageClassInput;
179 else if (type.getQualifier().isPipeOutput())
180 return spv::StorageClassOutput;
181 else if (type.getQualifier().isUniformOrBuffer()) {
182 if (type.getBasicType() == glslang::EbtBlock)
183 return spv::StorageClassUniform;
184 else
185 return spv::StorageClassUniformConstant;
186 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
187 } else {
188 switch (type.getQualifier().storage) {
189 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
190 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
191 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
192 case glslang::EvqTemporary: return spv::StorageClassFunction;
193 default:
194 spv::MissingFunctionality("unknown glslang storage class");
195 return spv::StorageClassFunction;
196 }
197 }
198}
199
200// Translate glslang sampler type to SPIR-V dimensionality.
201spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
202{
203 switch (sampler.dim) {
204 case glslang::Esd1D: return spv::Dim1D;
205 case glslang::Esd2D: return spv::Dim2D;
206 case glslang::Esd3D: return spv::Dim3D;
207 case glslang::EsdCube: return spv::DimCube;
208 case glslang::EsdRect: return spv::DimRect;
209 case glslang::EsdBuffer: return spv::DimBuffer;
210 default:
211 spv::MissingFunctionality("unknown sampler dimension");
212 return spv::Dim2D;
213 }
214}
215
216// Translate glslang type to SPIR-V precision decorations.
217spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
218{
219 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600220 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
221 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
222 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600223 default:
224 return spv::NoPrecision;
225 }
226}
227
228// Translate glslang type to SPIR-V block decorations.
229spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
230{
231 if (type.getBasicType() == glslang::EbtBlock) {
232 switch (type.getQualifier().storage) {
233 case glslang::EvqUniform: return spv::DecorationBlock;
234 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
235 case glslang::EvqVaryingIn: return spv::DecorationBlock;
236 case glslang::EvqVaryingOut: return spv::DecorationBlock;
237 default:
238 spv::MissingFunctionality("kind of block");
239 break;
240 }
241 }
242
243 return (spv::Decoration)spv::BadValue;
244}
245
246// Translate glslang type to SPIR-V layout decorations.
247spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
248{
249 if (type.isMatrix()) {
250 switch (type.getQualifier().layoutMatrix) {
251 case glslang::ElmRowMajor:
252 return spv::DecorationRowMajor;
253 default:
254 return spv::DecorationColMajor;
255 }
256 } else {
257 switch (type.getBasicType()) {
258 default:
259 return (spv::Decoration)spv::BadValue;
260 break;
261 case glslang::EbtBlock:
262 switch (type.getQualifier().storage) {
263 case glslang::EvqUniform:
264 case glslang::EvqBuffer:
265 switch (type.getQualifier().layoutPacking) {
266 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600267 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
268 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600269 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600270 }
271 case glslang::EvqVaryingIn:
272 case glslang::EvqVaryingOut:
273 if (type.getQualifier().layoutPacking != glslang::ElpNone)
274 spv::MissingFunctionality("in/out block layout");
275 return (spv::Decoration)spv::BadValue;
276 default:
277 spv::MissingFunctionality("block storage qualification");
278 return (spv::Decoration)spv::BadValue;
279 }
280 }
281 }
282}
283
284// Translate glslang type to SPIR-V interpolation decorations.
285spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
286{
287 if (type.getQualifier().smooth)
288 return spv::DecorationSmooth;
289 if (type.getQualifier().nopersp)
290 return spv::DecorationNoperspective;
291 else if (type.getQualifier().patch)
292 return spv::DecorationPatch;
293 else if (type.getQualifier().flat)
294 return spv::DecorationFlat;
295 else if (type.getQualifier().centroid)
296 return spv::DecorationCentroid;
297 else if (type.getQualifier().sample)
298 return spv::DecorationSample;
299 else
300 return (spv::Decoration)spv::BadValue;
301}
302
303// If glslang type is invaraiant, return SPIR-V invariant decoration.
304spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
305{
306 if (type.getQualifier().invariant)
307 return spv::DecorationInvariant;
308 else
309 return (spv::Decoration)spv::BadValue;
310}
311
312// Translate glslang built-in variable to SPIR-V built in decoration.
313spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
314{
315 switch (builtIn) {
316 case glslang::EbvPosition: return spv::BuiltInPosition;
317 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600318 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
319 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
320 case glslang::EbvVertexId: return spv::BuiltInVertexId;
321 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
322 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
323 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
324 case glslang::EbvLayer: return spv::BuiltInLayer;
325 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
326 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
327 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
328 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
329 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
330 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
331 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
332 case glslang::EbvFace: return spv::BuiltInFrontFacing;
333 case glslang::EbvSampleId: return spv::BuiltInSampleId;
334 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
335 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
336 case glslang::EbvFragColor: return spv::BuiltInFragColor;
337 case glslang::EbvFragData: return spv::BuiltInFragColor;
338 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
339 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
340 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
341 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
342 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
343 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
344 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
345 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
346 default: return (spv::BuiltIn)spv::BadValue;
347 }
348}
349
350//
351// Implement the TGlslangToSpvTraverser class.
352//
353
354TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
355 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
356 builder(GlslangMagic),
357 inMain(false), mainTerminated(false), linkageOnly(false),
358 glslangIntermediate(glslangIntermediate)
359{
360 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
361
362 builder.clearAccessChain();
363 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
364 stdBuiltins = builder.import("GLSL.std.450");
365 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
366 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600367 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600368
369 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600370 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
371 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600372 builder.addSourceExtension(it->c_str());
373
374 // Add the top-level modes for this shader.
375
376 if (glslangIntermediate->getXfbMode())
377 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
378
379 unsigned int mode;
380 switch (glslangIntermediate->getStage()) {
381 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600382 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600383 break;
384
385 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600386 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600387 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
388 break;
389
390 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600391 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600392 switch (glslangIntermediate->getInputPrimitive()) {
393 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
394 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
395 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
396 default: mode = spv::BadValue; break;
397 }
398 if (mode != spv::BadValue)
399 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
400
401 // TODO
402 //builder.addExecutionMode(spv::VertexSpacingMdName, glslangIntermediate->getVertexSpacing());
403 //builder.addExecutionMode(spv::VertexOrderMdName, glslangIntermediate->getVertexOrder());
404 //builder.addExecutionMode(spv::PointModeMdName, glslangIntermediate->getPointMode());
405 break;
406
407 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600408 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600409 switch (glslangIntermediate->getInputPrimitive()) {
410 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
411 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
412 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
413 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
414 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
415 default: mode = spv::BadValue; break;
416 }
417 if (mode != spv::BadValue)
418 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
419 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
420
421 switch (glslangIntermediate->getOutputPrimitive()) {
422 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
423 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
424 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
425 default: mode = spv::BadValue; break;
426 }
427 if (mode != spv::BadValue)
428 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
429 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
430 break;
431
432 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600433 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600434 if (glslangIntermediate->getPixelCenterInteger())
435 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
436 if (glslangIntermediate->getOriginUpperLeft())
437 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600438 else
439 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kessenich140f3df2015-06-26 16:58:36 -0600440 break;
441
442 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600443 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600444 break;
445
446 default:
447 break;
448 }
449
450}
451
452TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
453{
454 if (! mainTerminated) {
455 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
456 builder.setBuildPoint(lastMainBlock);
457 builder.leaveFunction(true);
458 }
459}
460
461//
462// Implement the traversal functions.
463//
464// Return true from interior nodes to have the external traversal
465// continue on to children. Return false if children were
466// already processed.
467//
468
469//
470// Symbols can turn into
471// - uniform/input reads
472// - output writes
473// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
474// - something simple that degenerates into the last bullet
475//
476void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
477{
478 // getSymbolId() will set up all the IO decorations on the first call.
479 // Formal function parameters were mapped during makeFunctions().
480 spv::Id id = getSymbolId(symbol);
481
482 if (! linkageOnly) {
483 // Prepare to generate code for the access
484
485 // L-value chains will be computed left to right. We're on the symbol now,
486 // which is the left-most part of the access chain, so now is "clear" time,
487 // followed by setting the base.
488 builder.clearAccessChain();
489
490 // For now, we consider all user variables as being in memory, so they are pointers,
491 // except for "const in" arguments to a function, which are an intermediate object.
492 // See comments in handleUserFunctionCall().
493 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
494 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
495 builder.setAccessChainRValue(id);
496 else
497 builder.setAccessChainLValue(id);
498 }
499}
500
501bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
502{
503 // First, handle special cases
504 switch (node->getOp()) {
505 case glslang::EOpAssign:
506 case glslang::EOpAddAssign:
507 case glslang::EOpSubAssign:
508 case glslang::EOpMulAssign:
509 case glslang::EOpVectorTimesMatrixAssign:
510 case glslang::EOpVectorTimesScalarAssign:
511 case glslang::EOpMatrixTimesScalarAssign:
512 case glslang::EOpMatrixTimesMatrixAssign:
513 case glslang::EOpDivAssign:
514 case glslang::EOpModAssign:
515 case glslang::EOpAndAssign:
516 case glslang::EOpInclusiveOrAssign:
517 case glslang::EOpExclusiveOrAssign:
518 case glslang::EOpLeftShiftAssign:
519 case glslang::EOpRightShiftAssign:
520 // A bin-op assign "a += b" means the same thing as "a = a + b"
521 // where a is evaluated before b. For a simple assignment, GLSL
522 // says to evaluate the left before the right. So, always, left
523 // node then right node.
524 {
525 // get the left l-value, save it away
526 builder.clearAccessChain();
527 node->getLeft()->traverse(this);
528 spv::Builder::AccessChain lValue = builder.getAccessChain();
529
530 // evaluate the right
531 builder.clearAccessChain();
532 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600533 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600534
535 if (node->getOp() != glslang::EOpAssign) {
536 // the left is also an r-value
537 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600538 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600539
540 // do the operation
541 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
542 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
543 node->getType().getBasicType());
544
545 // these all need their counterparts in createBinaryOperation()
546 if (rValue == 0)
547 spv::MissingFunctionality("createBinaryOperation");
548 }
549
550 // store the result
551 builder.setAccessChain(lValue);
552 builder.accessChainStore(rValue);
553
554 // assignments are expressions having an rValue after they are evaluated...
555 builder.clearAccessChain();
556 builder.setAccessChainRValue(rValue);
557 }
558 return false;
559 case glslang::EOpIndexDirect:
560 case glslang::EOpIndexDirectStruct:
561 {
562 // Get the left part of the access chain.
563 node->getLeft()->traverse(this);
564
565 // Add the next element in the chain
566
567 int index = 0;
568 if (node->getRight()->getAsConstantUnion() == 0)
569 spv::MissingFunctionality("direct index without a constant node");
570 else
571 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
572
573 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
574 // This may be, e.g., an anonymous block-member selection, which generally need
575 // index remapping due to hidden members in anonymous blocks.
576 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
577 if (remapper.size() == 0)
578 spv::MissingFunctionality("block without member remapping");
579 else
580 index = remapper[index];
581 }
582
583 if (! node->getLeft()->getType().isArray() &&
584 node->getLeft()->getType().isVector() &&
585 node->getOp() == glslang::EOpIndexDirect) {
586 // This is essentially a hard-coded vector swizzle of size 1,
587 // so short circuit the access-chain stuff with a swizzle.
588 std::vector<unsigned> swizzle;
589 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600590 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600591 } else {
592 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600593 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600594 }
595 }
596 return false;
597 case glslang::EOpIndexIndirect:
598 {
599 // Structure or array or vector indirection.
600 // Will use native SPIR-V access-chain for struct and array indirection;
601 // matrices are arrays of vectors, so will also work for a matrix.
602 // Will use the access chain's 'component' for variable index into a vector.
603
604 // This adapter is building access chains left to right.
605 // Set up the access chain to the left.
606 node->getLeft()->traverse(this);
607
608 // save it so that computing the right side doesn't trash it
609 spv::Builder::AccessChain partial = builder.getAccessChain();
610
611 // compute the next index in the chain
612 builder.clearAccessChain();
613 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600614 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600615
616 // restore the saved access chain
617 builder.setAccessChain(partial);
618
619 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600620 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600621 else
John Kessenichfa668da2015-09-13 14:46:30 -0600622 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600623 }
624 return false;
625 case glslang::EOpVectorSwizzle:
626 {
627 node->getLeft()->traverse(this);
628 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
629 std::vector<unsigned> swizzle;
630 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
631 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600632 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600633 }
634 return false;
635 default:
636 break;
637 }
638
639 // Assume generic binary op...
640
641 // Get the operands
642 builder.clearAccessChain();
643 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600644 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600645
646 builder.clearAccessChain();
647 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600648 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600649
650 spv::Id result;
651 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
652
653 result = createBinaryOperation(node->getOp(), precision,
654 convertGlslangToSpvType(node->getType()), left, right,
655 node->getLeft()->getType().getBasicType());
656
657 if (! result) {
658 spv::MissingFunctionality("glslang binary operation");
659 } else {
660 builder.clearAccessChain();
661 builder.setAccessChainRValue(result);
662
663 return false;
664 }
665
666 return true;
667}
668
669bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
670{
John Kessenichfc51d282015-08-19 13:34:18 -0600671 spv::Id result = spv::NoResult;
672
673 // try texturing first
674 result = createImageTextureFunctionCall(node);
675 if (result != spv::NoResult) {
676 builder.clearAccessChain();
677 builder.setAccessChainRValue(result);
678
679 return false; // done with this node
680 }
681
682 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600683
684 if (node->getOp() == glslang::EOpArrayLength) {
685 // Quite special; won't want to evaluate the operand.
686
687 // Normal .length() would have been constant folded by the front-end.
688 // So, this has to be block.lastMember.length().
689 // SPV wants "block" as the operand, go get it.
690 assert(node->getOperand()->getType().isRuntimeSizedArray());
691 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
692 block->traverse(this);
693 spv::Id length = builder.createUnaryOp(spv::OpArrayLength, builder.makeIntType(32), builder.accessChainGetLValue());
694
695 builder.clearAccessChain();
696 builder.setAccessChainRValue(length);
697
698 return false;
699 }
700
John Kessenichfc51d282015-08-19 13:34:18 -0600701 // Start by evaluating the operand
702
John Kessenich140f3df2015-06-26 16:58:36 -0600703 builder.clearAccessChain();
704 node->getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600705 spv::Id operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600706
707 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
708
709 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600710 if (! result)
711 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600712
713 // if not, then possibly an operation
714 if (! result)
John Kessenichfc51d282015-08-19 13:34:18 -0600715 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand,
716 node->getBasicType() == glslang::EbtFloat || node->getBasicType() == glslang::EbtDouble);
John Kessenich140f3df2015-06-26 16:58:36 -0600717
718 if (result) {
719 builder.clearAccessChain();
720 builder.setAccessChainRValue(result);
721
722 return false; // done with this node
723 }
724
725 // it must be a special case, check...
726 switch (node->getOp()) {
727 case glslang::EOpPostIncrement:
728 case glslang::EOpPostDecrement:
729 case glslang::EOpPreIncrement:
730 case glslang::EOpPreDecrement:
731 {
732 // we need the integer value "1" or the floating point "1.0" to add/subtract
733 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
734 builder.makeFloatConstant(1.0F) :
735 builder.makeIntConstant(1);
736 glslang::TOperator op;
737 if (node->getOp() == glslang::EOpPreIncrement ||
738 node->getOp() == glslang::EOpPostIncrement)
739 op = glslang::EOpAdd;
740 else
741 op = glslang::EOpSub;
742
743 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
744 convertGlslangToSpvType(node->getType()), operand, one,
745 node->getType().getBasicType());
746 if (result == 0)
747 spv::MissingFunctionality("createBinaryOperation for unary");
748
749 // The result of operation is always stored, but conditionally the
750 // consumed result. The consumed result is always an r-value.
751 builder.accessChainStore(result);
752 builder.clearAccessChain();
753 if (node->getOp() == glslang::EOpPreIncrement ||
754 node->getOp() == glslang::EOpPreDecrement)
755 builder.setAccessChainRValue(result);
756 else
757 builder.setAccessChainRValue(operand);
758 }
759
760 return false;
761
762 case glslang::EOpEmitStreamVertex:
763 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
764 return false;
765 case glslang::EOpEndStreamPrimitive:
766 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
767 return false;
768
769 default:
770 spv::MissingFunctionality("glslang unary");
771 break;
772 }
773
774 return true;
775}
776
777bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
778{
John Kessenichfc51d282015-08-19 13:34:18 -0600779 spv::Id result = spv::NoResult;
780
781 // try texturing
782 result = createImageTextureFunctionCall(node);
783 if (result != spv::NoResult) {
784 builder.clearAccessChain();
785 builder.setAccessChainRValue(result);
786
787 return false;
788 }
789
John Kessenich140f3df2015-06-26 16:58:36 -0600790 glslang::TOperator binOp = glslang::EOpNull;
791 bool reduceComparison = true;
792 bool isMatrix = false;
793 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600794 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600795
796 assert(node->getOp());
797
798 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
799
800 switch (node->getOp()) {
801 case glslang::EOpSequence:
802 {
803 if (preVisit)
804 ++sequenceDepth;
805 else
806 --sequenceDepth;
807
808 if (sequenceDepth == 1) {
809 // If this is the parent node of all the functions, we want to see them
810 // early, so all call points have actual SPIR-V functions to reference.
811 // In all cases, still let the traverser visit the children for us.
812 makeFunctions(node->getAsAggregate()->getSequence());
813
814 // Also, we want all globals initializers to go into the entry of main(), before
815 // anything else gets there, so visit out of order, doing them all now.
816 makeGlobalInitializers(node->getAsAggregate()->getSequence());
817
818 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
819 // so do them manually.
820 visitFunctions(node->getAsAggregate()->getSequence());
821
822 return false;
823 }
824
825 return true;
826 }
827 case glslang::EOpLinkerObjects:
828 {
829 if (visit == glslang::EvPreVisit)
830 linkageOnly = true;
831 else
832 linkageOnly = false;
833
834 return true;
835 }
836 case glslang::EOpComma:
837 {
838 // processing from left to right naturally leaves the right-most
839 // lying around in the access chain
840 glslang::TIntermSequence& glslangOperands = node->getSequence();
841 for (int i = 0; i < (int)glslangOperands.size(); ++i)
842 glslangOperands[i]->traverse(this);
843
844 return false;
845 }
846 case glslang::EOpFunction:
847 if (visit == glslang::EvPreVisit) {
848 if (isShaderEntrypoint(node)) {
849 inMain = true;
850 builder.setBuildPoint(shaderEntry->getLastBlock());
851 } else {
852 handleFunctionEntry(node);
853 }
854 } else {
855 if (inMain)
856 mainTerminated = true;
857 builder.leaveFunction(inMain);
858 inMain = false;
859 }
860
861 return true;
862 case glslang::EOpParameters:
863 // Parameters will have been consumed by EOpFunction processing, but not
864 // the body, so we still visited the function node's children, making this
865 // child redundant.
866 return false;
867 case glslang::EOpFunctionCall:
868 {
869 if (node->isUserDefined())
870 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600871
872 if (! result) {
873 spv::MissingFunctionality("glslang function call");
874 glslang::TConstUnionArray emptyConsts;
875 int nextConst = 0;
876 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
877 }
878 builder.clearAccessChain();
879 builder.setAccessChainRValue(result);
880
881 return false;
882 }
883 case glslang::EOpConstructMat2x2:
884 case glslang::EOpConstructMat2x3:
885 case glslang::EOpConstructMat2x4:
886 case glslang::EOpConstructMat3x2:
887 case glslang::EOpConstructMat3x3:
888 case glslang::EOpConstructMat3x4:
889 case glslang::EOpConstructMat4x2:
890 case glslang::EOpConstructMat4x3:
891 case glslang::EOpConstructMat4x4:
892 case glslang::EOpConstructDMat2x2:
893 case glslang::EOpConstructDMat2x3:
894 case glslang::EOpConstructDMat2x4:
895 case glslang::EOpConstructDMat3x2:
896 case glslang::EOpConstructDMat3x3:
897 case glslang::EOpConstructDMat3x4:
898 case glslang::EOpConstructDMat4x2:
899 case glslang::EOpConstructDMat4x3:
900 case glslang::EOpConstructDMat4x4:
901 isMatrix = true;
902 // fall through
903 case glslang::EOpConstructFloat:
904 case glslang::EOpConstructVec2:
905 case glslang::EOpConstructVec3:
906 case glslang::EOpConstructVec4:
907 case glslang::EOpConstructDouble:
908 case glslang::EOpConstructDVec2:
909 case glslang::EOpConstructDVec3:
910 case glslang::EOpConstructDVec4:
911 case glslang::EOpConstructBool:
912 case glslang::EOpConstructBVec2:
913 case glslang::EOpConstructBVec3:
914 case glslang::EOpConstructBVec4:
915 case glslang::EOpConstructInt:
916 case glslang::EOpConstructIVec2:
917 case glslang::EOpConstructIVec3:
918 case glslang::EOpConstructIVec4:
919 case glslang::EOpConstructUint:
920 case glslang::EOpConstructUVec2:
921 case glslang::EOpConstructUVec3:
922 case glslang::EOpConstructUVec4:
923 case glslang::EOpConstructStruct:
924 {
925 std::vector<spv::Id> arguments;
926 translateArguments(node->getSequence(), arguments);
927 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
928 spv::Id constructed;
929 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
930 std::vector<spv::Id> constituents;
931 for (int c = 0; c < (int)arguments.size(); ++c)
932 constituents.push_back(arguments[c]);
933 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
934 } else {
935 if (isMatrix)
936 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
937 else
938 constructed = builder.createConstructor(precision, arguments, resultTypeId);
939 }
940
941 builder.clearAccessChain();
942 builder.setAccessChainRValue(constructed);
943
944 return false;
945 }
946
947 // These six are component-wise compares with component-wise results.
948 // Forward on to createBinaryOperation(), requesting a vector result.
949 case glslang::EOpLessThan:
950 case glslang::EOpGreaterThan:
951 case glslang::EOpLessThanEqual:
952 case glslang::EOpGreaterThanEqual:
953 case glslang::EOpVectorEqual:
954 case glslang::EOpVectorNotEqual:
955 {
956 // Map the operation to a binary
957 binOp = node->getOp();
958 reduceComparison = false;
959 switch (node->getOp()) {
960 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
961 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
962 default: binOp = node->getOp(); break;
963 }
964
965 break;
966 }
967 case glslang::EOpMul:
968 // compontent-wise matrix multiply
969 binOp = glslang::EOpMul;
970 break;
971 case glslang::EOpOuterProduct:
972 // two vectors multiplied to make a matrix
973 binOp = glslang::EOpOuterProduct;
974 break;
975 case glslang::EOpDot:
976 {
977 // for scalar dot product, use multiply
978 glslang::TIntermSequence& glslangOperands = node->getSequence();
979 if (! glslangOperands[0]->getAsTyped()->isVector())
980 binOp = glslang::EOpMul;
981 break;
982 }
983 case glslang::EOpMod:
984 // when an aggregate, this is the floating-point mod built-in function,
985 // which can be emitted by the one in createBinaryOperation()
986 binOp = glslang::EOpMod;
987 break;
John Kessenich140f3df2015-06-26 16:58:36 -0600988 case glslang::EOpEmitVertex:
989 case glslang::EOpEndPrimitive:
990 case glslang::EOpBarrier:
991 case glslang::EOpMemoryBarrier:
992 case glslang::EOpMemoryBarrierAtomicCounter:
993 case glslang::EOpMemoryBarrierBuffer:
994 case glslang::EOpMemoryBarrierImage:
995 case glslang::EOpMemoryBarrierShared:
996 case glslang::EOpGroupMemoryBarrier:
997 noReturnValue = true;
998 // These all have 0 operands and will naturally finish up in the code below for 0 operands
999 break;
1000
John Kessenich426394d2015-07-23 10:22:48 -06001001 case glslang::EOpAtomicAdd:
1002 case glslang::EOpAtomicMin:
1003 case glslang::EOpAtomicMax:
1004 case glslang::EOpAtomicAnd:
1005 case glslang::EOpAtomicOr:
1006 case glslang::EOpAtomicXor:
1007 case glslang::EOpAtomicExchange:
1008 case glslang::EOpAtomicCompSwap:
1009 atomic = true;
1010 break;
1011
John Kessenichfc51d282015-08-19 13:34:18 -06001012 case glslang::EOpAddCarry:
1013 case glslang::EOpSubBorrow:
1014 case glslang::EOpUMulExtended:
1015 case glslang::EOpIMulExtended:
1016 case glslang::EOpBitfieldExtract:
1017 case glslang::EOpBitfieldInsert:
1018 spv::MissingFunctionality("integer aggregate");
1019 break;
1020
1021 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001022 case glslang::EOpFrexp:
1023 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001024 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1025 break;
1026
John Kessenich140f3df2015-06-26 16:58:36 -06001027 default:
1028 break;
1029 }
1030
1031 //
1032 // See if it maps to a regular operation.
1033 //
John Kessenich140f3df2015-06-26 16:58:36 -06001034 if (binOp != glslang::EOpNull) {
1035 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1036 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1037 assert(left && right);
1038
1039 builder.clearAccessChain();
1040 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001041 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001042
1043 builder.clearAccessChain();
1044 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001045 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001046
1047 result = createBinaryOperation(binOp, precision,
1048 convertGlslangToSpvType(node->getType()), leftId, rightId,
1049 left->getType().getBasicType(), reduceComparison);
1050
1051 // code above should only make binOp that exists in createBinaryOperation
1052 if (result == 0)
1053 spv::MissingFunctionality("createBinaryOperation for aggregate");
1054
1055 builder.clearAccessChain();
1056 builder.setAccessChainRValue(result);
1057
1058 return false;
1059 }
1060
John Kessenich426394d2015-07-23 10:22:48 -06001061 //
1062 // Create the list of operands.
1063 //
John Kessenich140f3df2015-06-26 16:58:36 -06001064 glslang::TIntermSequence& glslangOperands = node->getSequence();
1065 std::vector<spv::Id> operands;
1066 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1067 builder.clearAccessChain();
1068 glslangOperands[arg]->traverse(this);
1069
1070 // special case l-value operands; there are just a few
1071 bool lvalue = false;
1072 switch (node->getOp()) {
1073 //case glslang::EOpFrexp:
1074 case glslang::EOpModf:
1075 if (arg == 1)
1076 lvalue = true;
1077 break;
1078 //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
John Kessenichfa668da2015-09-13 14:46:30 -06001087 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001088 }
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
John Kessenichfa668da2015-09-13 14:46:30 -06001137 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001138
1139 if (node->getTrueBlock()) {
1140 // emit the "then" statement
1141 node->getTrueBlock()->traverse(this);
1142 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001143 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001144 }
1145
1146 if (node->getFalseBlock()) {
1147 ifBuilder.makeBeginElse();
1148 // emit the "else" statement
1149 node->getFalseBlock()->traverse(this);
1150 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001151 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001152 }
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);
John Kessenichfa668da2015-09-13 14:46:30 -06001172 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001173
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
John Kessenichfa668da2015-09-13 14:46:30 -06001236 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001237 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())
John Kessenichfa668da2015-09-13 14:46:30 -06001282 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001283 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
John Kessenich31ed4832015-09-09 17:51:38 -06001330// Convert from a glslang type to an SPV type, by calling into
1331// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001332spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1333{
John Kessenich31ed4832015-09-09 17:51:38 -06001334 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1335}
1336
1337// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1338// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1339spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1340{
John Kessenich140f3df2015-06-26 16:58:36 -06001341 spv::Id spvType = 0;
1342
1343 switch (type.getBasicType()) {
1344 case glslang::EbtVoid:
1345 spvType = builder.makeVoidType();
1346 if (type.isArray())
1347 spv::MissingFunctionality("array of void");
1348 break;
1349 case glslang::EbtFloat:
1350 spvType = builder.makeFloatType(32);
1351 break;
1352 case glslang::EbtDouble:
1353 spvType = builder.makeFloatType(64);
1354 break;
1355 case glslang::EbtBool:
1356 spvType = builder.makeBoolType();
1357 break;
1358 case glslang::EbtInt:
1359 spvType = builder.makeIntType(32);
1360 break;
1361 case glslang::EbtUint:
1362 spvType = builder.makeUintType(32);
1363 break;
John Kessenich426394d2015-07-23 10:22:48 -06001364 case glslang::EbtAtomicUint:
1365 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1366 spvType = builder.makeUintType(32);
1367 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001368 case glslang::EbtSampler:
1369 {
1370 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001371 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1372 sampler.image ? 2 : 1, spv::ImageFormatUnknown); // TODO: translate format, needed for GLSL image ops
1373 // OpenGL "textures" need to be combined with a sampler
1374 if (! sampler.image)
1375 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001376 }
1377 break;
1378 case glslang::EbtStruct:
1379 case glslang::EbtBlock:
1380 {
1381 // If we've seen this struct type, return it
1382 const glslang::TTypeList* glslangStruct = type.getStruct();
1383 std::vector<spv::Id> structFields;
1384 spvType = structMap[glslangStruct];
1385 if (spvType)
1386 break;
1387
1388 // else, we haven't seen it...
1389
1390 // Create a vector of struct types for SPIR-V to consume
1391 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1392 if (type.getBasicType() == glslang::EbtBlock)
1393 memberRemapper[glslangStruct].resize(glslangStruct->size());
1394 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1395 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1396 if (glslangType.hiddenMember()) {
1397 ++memberDelta;
1398 if (type.getBasicType() == glslang::EbtBlock)
1399 memberRemapper[glslangStruct][i] = -1;
1400 } else {
1401 if (type.getBasicType() == glslang::EbtBlock)
1402 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001403 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001404 }
1405 }
1406
1407 // Make the SPIR-V type
1408 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1409 structMap[glslangStruct] = spvType;
1410
1411 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001412 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001413 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1414 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1415 int member = i;
1416 if (type.getBasicType() == glslang::EbtBlock)
1417 member = memberRemapper[glslangStruct][i];
1418 // using -1 above to indicate a hidden member
1419 if (member >= 0) {
1420 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1421 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1422 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1423 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1424 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1425 if (glslangType.getQualifier().hasLocation())
1426 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1427 if (glslangType.getQualifier().hasComponent())
1428 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1429 if (glslangType.getQualifier().hasXfbOffset())
1430 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001431 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001432 // figure out what to do with offset, which is accumulating
1433 int nextOffset;
1434 updateMemberOffset(type, glslangType, offset, nextOffset);
1435 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001436 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001437 offset = nextOffset;
1438 }
John Kessenich140f3df2015-06-26 16:58:36 -06001439
John Kessenich31ed4832015-09-09 17:51:38 -06001440 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001441 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1442 }
1443
John Kessenich140f3df2015-06-26 16:58:36 -06001444 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001445 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1446 if (builtIn != spv::BadValue)
1447 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001448 }
1449 }
1450
1451 // Decorate the structure
1452 addDecoration(spvType, TranslateLayoutDecoration(type));
1453 addDecoration(spvType, TranslateBlockDecoration(type));
1454 if (type.getQualifier().hasStream())
1455 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1456 if (glslangIntermediate->getXfbMode()) {
1457 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001458 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001459 if (type.getQualifier().hasXfbBuffer())
1460 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1461 }
1462 }
1463 break;
1464 default:
1465 spv::MissingFunctionality("basic type");
1466 break;
1467 }
1468
1469 if (type.isMatrix())
1470 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1471 else {
1472 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1473 if (type.getVectorSize() > 1)
1474 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1475 }
1476
1477 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001478 // Do all but the outer dimension
1479 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1480 assert(type.getArraySizes()->getDimSize(dim) > 0);
1481 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1482 }
John Kessenich31ed4832015-09-09 17:51:38 -06001483
John Kessenichc9a80832015-09-12 12:17:44 -06001484 // Do the outer dimension, which might not be known for a runtime-sized array
1485 if (type.isRuntimeSizedArray()) {
1486 spvType = builder.makeRuntimeArray(spvType);
1487 } else {
1488 assert(type.getOuterArraySize() > 0);
1489 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1490 }
1491
1492 // TODO: layout still needs to be done hierarchically for arrays of arrays, which
1493 // may still require additional "link time" support from the front-end
1494 // for arrays of arrays
John Kessenich31ed4832015-09-09 17:51:38 -06001495 if (explicitLayout)
1496 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001497 }
1498
1499 return spvType;
1500}
1501
John Kessenich31ed4832015-09-09 17:51:38 -06001502bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1503{
1504 return type.getBasicType() == glslang::EbtBlock &&
1505 type.getQualifier().layoutPacking != glslang::ElpShared &&
1506 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1507 (type.getQualifier().storage == glslang::EvqUniform ||
1508 type.getQualifier().storage == glslang::EvqBuffer);
1509}
1510
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001511// Given an array type, returns the integer stride required for that array
1512int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1513{
1514 glslang::TType derefType(arrayType, 0);
1515 int size;
1516 glslangIntermediate->getBaseAlignment(derefType, size, true);
1517 return size;
1518}
1519
1520// Given a matrix type, returns the integer stride required for that matrix
1521// when used as a member of an interface block
1522int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1523{
1524 int size;
1525 return glslangIntermediate->getBaseAlignment(matrixType, size, true);
1526}
1527
John Kessenich5e4b1242015-08-06 22:53:06 -06001528// Given a member type of a struct, realign the current offset for it, and compute
1529// the next (not yet aligned) offset for the next member, which will get aligned
1530// on the next call.
1531// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1532// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1533// -1 means a non-forced member offset (no decoration needed).
1534void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1535{
1536 // this will get a positive value when deemed necessary
1537 nextOffset = -1;
1538
1539 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1540 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1541
1542 // override anything in currentOffset with user-set offset
1543 if (memberType.getQualifier().hasOffset())
1544 currentOffset = memberType.getQualifier().layoutOffset;
1545
1546 // It could be that current linker usage in glslang updated all the layoutOffset,
1547 // in which case the following code does not matter. But, that's not quite right
1548 // once cross-compilation unit GLSL validation is done, as the original user
1549 // settings are needed in layoutOffset, and then the following will come into play.
1550
1551 if (! forceOffset) {
1552 if (! memberType.getQualifier().hasOffset())
1553 currentOffset = -1;
1554
1555 return;
1556 }
1557
1558 // Getting this far means we are forcing offsets
1559 if (currentOffset < 0)
1560 currentOffset = 0;
1561
1562 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1563 // but possibly not yet correctly aligned.
1564
1565 int memberSize;
1566 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1567 glslang::RoundToPow2(currentOffset, memberAlignment);
1568 nextOffset = currentOffset + memberSize;
1569}
1570
John Kessenich140f3df2015-06-26 16:58:36 -06001571bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1572{
1573 return node->getName() == "main(";
1574}
1575
1576// Make all the functions, skeletally, without actually visiting their bodies.
1577void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1578{
1579 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1580 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1581 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1582 continue;
1583
1584 // We're on a user function. Set up the basic interface for the function now,
1585 // so that it's available to call.
1586 // Translating the body will happen later.
1587 //
1588 // Typically (except for a "const in" parameter), an address will be passed to the
1589 // function. What it is an address of varies:
1590 //
1591 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1592 // so that write needs to be to a copy, hence the address of a copy works.
1593 //
1594 // - "const in" parameters can just be the r-value, as no writes need occur.
1595 //
1596 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1597 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1598
1599 std::vector<spv::Id> paramTypes;
1600 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1601
1602 for (int p = 0; p < (int)parameters.size(); ++p) {
1603 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1604 spv::Id typeId = convertGlslangToSpvType(paramType);
1605 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1606 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1607 else
1608 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1609 paramTypes.push_back(typeId);
1610 }
1611
1612 spv::Block* functionBlock;
1613 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1614 paramTypes, &functionBlock);
1615
1616 // Track function to emit/call later
1617 functionMap[glslFunction->getName().c_str()] = function;
1618
1619 // Set the parameter id's
1620 for (int p = 0; p < (int)parameters.size(); ++p) {
1621 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1622 // give a name too
1623 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1624 }
1625 }
1626}
1627
1628// Process all the initializers, while skipping the functions and link objects
1629void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1630{
1631 builder.setBuildPoint(shaderEntry->getLastBlock());
1632 for (int i = 0; i < (int)initializers.size(); ++i) {
1633 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1634 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1635
1636 // We're on a top-level node that's not a function. Treat as an initializer, whose
1637 // code goes into the beginning of main.
1638 initializer->traverse(this);
1639 }
1640 }
1641}
1642
1643// Process all the functions, while skipping initializers.
1644void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1645{
1646 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1647 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1648 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1649 node->traverse(this);
1650 }
1651}
1652
1653void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1654{
1655 // SPIR-V functions should already be in the functionMap from the prepass
1656 // that called makeFunctions().
1657 spv::Function* function = functionMap[node->getName().c_str()];
1658 spv::Block* functionBlock = function->getEntryBlock();
1659 builder.setBuildPoint(functionBlock);
1660}
1661
1662void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermSequence& glslangArguments, std::vector<spv::Id>& arguments)
1663{
1664 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1665 builder.clearAccessChain();
1666 glslangArguments[i]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001667 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001668 }
1669}
1670
John Kessenichfc51d282015-08-19 13:34:18 -06001671void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001672{
John Kessenichfc51d282015-08-19 13:34:18 -06001673 builder.clearAccessChain();
1674 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001675 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001676}
John Kessenich140f3df2015-06-26 16:58:36 -06001677
John Kessenichfc51d282015-08-19 13:34:18 -06001678spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1679{
1680 if (node->isImage()) {
1681 spv::MissingFunctionality("GLSL image function");
1682 return spv::NoResult;
1683 } else if (! node->isTexture()) {
1684 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001685 }
1686
John Kessenichfc51d282015-08-19 13:34:18 -06001687 // Process a GLSL texturing op (will be SPV image)
John Kessenich140f3df2015-06-26 16:58:36 -06001688
John Kessenichfc51d282015-08-19 13:34:18 -06001689 glslang::TCrackedTextureOp cracked;
1690 node->crackTexture(cracked);
1691
1692 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1693 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1694 std::vector<spv::Id> arguments;
1695 if (node->getAsAggregate())
1696 translateArguments(node->getAsAggregate()->getSequence(), arguments);
1697 else
1698 translateArguments(*node->getAsUnaryNode(), arguments);
1699 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1700
1701 spv::Builder::TextureParameters params = { };
1702 params.sampler = arguments[0];
1703
1704 // Check for queries
1705 if (cracked.query) {
1706 switch (node->getOp()) {
1707 case glslang::EOpImageQuerySize:
1708 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001709 if (arguments.size() > 1) {
1710 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001711 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001712 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001713 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001714 case glslang::EOpImageQuerySamples:
1715 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001716 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001717 case glslang::EOpTextureQueryLod:
1718 params.coords = arguments[1];
1719 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1720 case glslang::EOpTextureQueryLevels:
1721 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1722 default:
1723 assert(0);
1724 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001725 }
John Kessenich140f3df2015-06-26 16:58:36 -06001726 }
1727
John Kessenichfc51d282015-08-19 13:34:18 -06001728 // This is no longer a query....
John Kessenich140f3df2015-06-26 16:58:36 -06001729
John Kessenichfc51d282015-08-19 13:34:18 -06001730 if (cracked.gather)
1731 spv::MissingFunctionality("texture gather");
1732
1733 // check for bias argument
1734 bool bias = false;
1735 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1736 int nonBiasArgCount = 2;
1737 if (cracked.offset)
1738 ++nonBiasArgCount;
1739 if (cracked.grad)
1740 nonBiasArgCount += 2;
1741
1742 if ((int)arguments.size() > nonBiasArgCount)
1743 bias = true;
1744 }
1745
1746 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1747
1748 // set the rest of the arguments
1749 params.coords = arguments[1];
1750 int extraArgs = 0;
1751 if (cubeCompare)
1752 params.Dref = arguments[2];
1753 else if (sampler.shadow) {
1754 std::vector<spv::Id> indexes;
1755 int comp;
1756 if (cracked.proj)
1757 comp = 3;
1758 else
1759 comp = builder.getNumComponents(params.coords) - 1;
1760 indexes.push_back(comp);
1761 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1762 }
1763 if (cracked.lod) {
1764 params.lod = arguments[2];
1765 ++extraArgs;
1766 }
1767 if (cracked.grad) {
1768 params.gradX = arguments[2 + extraArgs];
1769 params.gradY = arguments[3 + extraArgs];
1770 extraArgs += 2;
1771 }
1772 //if (gather && compare) {
1773 // params.compare = arguments[2 + extraArgs];
1774 // ++extraArgs;
1775 //}
1776 if (cracked.offset || cracked.offsets) {
1777 params.offset = arguments[2 + extraArgs];
1778 ++extraArgs;
1779 }
1780 if (bias) {
1781 params.bias = arguments[2 + extraArgs];
1782 ++extraArgs;
1783 }
1784
Jason Ekstrand18b9fbd2015-09-05 14:14:48 -07001785 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001786}
1787
1788spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1789{
1790 // Grab the function's pointer from the previously created function
1791 spv::Function* function = functionMap[node->getName().c_str()];
1792 if (! function)
1793 return 0;
1794
1795 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1796 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1797
1798 // See comments in makeFunctions() for details about the semantics for parameter passing.
1799 //
1800 // These imply we need a four step process:
1801 // 1. Evaluate the arguments
1802 // 2. Allocate and make copies of in, out, and inout arguments
1803 // 3. Make the call
1804 // 4. Copy back the results
1805
1806 // 1. Evaluate the arguments
1807 std::vector<spv::Builder::AccessChain> lValues;
1808 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06001809 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06001810 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1811 // build l-value
1812 builder.clearAccessChain();
1813 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001814 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001815 // keep outputs as l-values, evaluate input-only as r-values
1816 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1817 // save l-value
1818 lValues.push_back(builder.getAccessChain());
1819 } else {
1820 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06001821 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06001822 }
1823 }
1824
1825 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1826 // copy the original into that space.
1827 //
1828 // Also, build up the list of actual arguments to pass in for the call
1829 int lValueCount = 0;
1830 int rValueCount = 0;
1831 std::vector<spv::Id> spvArgs;
1832 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1833 spv::Id arg;
1834 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1835 // need space to hold the copy
1836 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1837 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1838 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1839 // need to copy the input into output space
1840 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06001841 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06001842 builder.createStore(copy, arg);
1843 }
1844 ++lValueCount;
1845 } else {
1846 arg = rValues[rValueCount];
1847 ++rValueCount;
1848 }
1849 spvArgs.push_back(arg);
1850 }
1851
1852 // 3. Make the call.
1853 spv::Id result = builder.createFunctionCall(function, spvArgs);
1854
1855 // 4. Copy back out an "out" arguments.
1856 lValueCount = 0;
1857 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1858 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1859 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1860 spv::Id copy = builder.createLoad(spvArgs[a]);
1861 builder.setAccessChain(lValues[lValueCount]);
1862 builder.accessChainStore(copy);
1863 }
1864 ++lValueCount;
1865 }
1866 }
1867
1868 return result;
1869}
1870
1871// Translate AST operation to SPV operation, already having SPV-based operands/types.
1872spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
1873 spv::Id typeId, spv::Id left, spv::Id right,
1874 glslang::TBasicType typeProxy, bool reduceComparison)
1875{
1876 bool isUnsigned = typeProxy == glslang::EbtUint;
1877 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
1878
1879 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06001880 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06001881 bool comparison = false;
1882
1883 switch (op) {
1884 case glslang::EOpAdd:
1885 case glslang::EOpAddAssign:
1886 if (isFloat)
1887 binOp = spv::OpFAdd;
1888 else
1889 binOp = spv::OpIAdd;
1890 break;
1891 case glslang::EOpSub:
1892 case glslang::EOpSubAssign:
1893 if (isFloat)
1894 binOp = spv::OpFSub;
1895 else
1896 binOp = spv::OpISub;
1897 break;
1898 case glslang::EOpMul:
1899 case glslang::EOpMulAssign:
1900 if (isFloat)
1901 binOp = spv::OpFMul;
1902 else
1903 binOp = spv::OpIMul;
1904 break;
1905 case glslang::EOpVectorTimesScalar:
1906 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06001907 if (isFloat) {
1908 if (builder.isVector(right))
1909 std::swap(left, right);
1910 assert(builder.isScalar(right));
1911 needMatchingVectors = false;
1912 binOp = spv::OpVectorTimesScalar;
1913 } else
1914 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06001915 break;
1916 case glslang::EOpVectorTimesMatrix:
1917 case glslang::EOpVectorTimesMatrixAssign:
1918 assert(builder.isVector(left));
1919 assert(builder.isMatrix(right));
1920 binOp = spv::OpVectorTimesMatrix;
1921 break;
1922 case glslang::EOpMatrixTimesVector:
1923 assert(builder.isMatrix(left));
1924 assert(builder.isVector(right));
1925 binOp = spv::OpMatrixTimesVector;
1926 break;
1927 case glslang::EOpMatrixTimesScalar:
1928 case glslang::EOpMatrixTimesScalarAssign:
1929 if (builder.isMatrix(right))
1930 std::swap(left, right);
1931 assert(builder.isScalar(right));
1932 binOp = spv::OpMatrixTimesScalar;
1933 break;
1934 case glslang::EOpMatrixTimesMatrix:
1935 case glslang::EOpMatrixTimesMatrixAssign:
1936 assert(builder.isMatrix(left));
1937 assert(builder.isMatrix(right));
1938 binOp = spv::OpMatrixTimesMatrix;
1939 break;
1940 case glslang::EOpOuterProduct:
1941 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06001942 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001943 break;
1944
1945 case glslang::EOpDiv:
1946 case glslang::EOpDivAssign:
1947 if (isFloat)
1948 binOp = spv::OpFDiv;
1949 else if (isUnsigned)
1950 binOp = spv::OpUDiv;
1951 else
1952 binOp = spv::OpSDiv;
1953 break;
1954 case glslang::EOpMod:
1955 case glslang::EOpModAssign:
1956 if (isFloat)
1957 binOp = spv::OpFMod;
1958 else if (isUnsigned)
1959 binOp = spv::OpUMod;
1960 else
1961 binOp = spv::OpSMod;
1962 break;
1963 case glslang::EOpRightShift:
1964 case glslang::EOpRightShiftAssign:
1965 if (isUnsigned)
1966 binOp = spv::OpShiftRightLogical;
1967 else
1968 binOp = spv::OpShiftRightArithmetic;
1969 break;
1970 case glslang::EOpLeftShift:
1971 case glslang::EOpLeftShiftAssign:
1972 binOp = spv::OpShiftLeftLogical;
1973 break;
1974 case glslang::EOpAnd:
1975 case glslang::EOpAndAssign:
1976 binOp = spv::OpBitwiseAnd;
1977 break;
1978 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06001979 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001980 binOp = spv::OpLogicalAnd;
1981 break;
1982 case glslang::EOpInclusiveOr:
1983 case glslang::EOpInclusiveOrAssign:
1984 binOp = spv::OpBitwiseOr;
1985 break;
1986 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06001987 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001988 binOp = spv::OpLogicalOr;
1989 break;
1990 case glslang::EOpExclusiveOr:
1991 case glslang::EOpExclusiveOrAssign:
1992 binOp = spv::OpBitwiseXor;
1993 break;
1994 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06001995 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06001996 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06001997 break;
1998
1999 case glslang::EOpLessThan:
2000 case glslang::EOpGreaterThan:
2001 case glslang::EOpLessThanEqual:
2002 case glslang::EOpGreaterThanEqual:
2003 case glslang::EOpEqual:
2004 case glslang::EOpNotEqual:
2005 case glslang::EOpVectorEqual:
2006 case glslang::EOpVectorNotEqual:
2007 comparison = true;
2008 break;
2009 default:
2010 break;
2011 }
2012
2013 if (binOp != spv::OpNop) {
2014 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2015 switch (binOp) {
2016 case spv::OpMatrixTimesScalar:
2017 case spv::OpVectorTimesMatrix:
2018 case spv::OpMatrixTimesVector:
2019 case spv::OpMatrixTimesMatrix:
2020 break;
2021 case spv::OpFDiv:
2022 // turn it into a multiply...
2023 assert(builder.isMatrix(left) && builder.isScalar(right));
2024 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2025 binOp = spv::OpFMul;
2026 break;
2027 default:
2028 spv::MissingFunctionality("binary operation on matrix");
2029 break;
2030 }
2031
2032 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2033 builder.setPrecision(id, precision);
2034
2035 return id;
2036 }
2037
2038 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002039 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002040 builder.promoteScalar(precision, left, right);
2041
2042 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2043 builder.setPrecision(id, precision);
2044
2045 return id;
2046 }
2047
2048 if (! comparison)
2049 return 0;
2050
2051 // Comparison instructions
2052
2053 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2054 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2055
2056 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2057 }
2058
2059 switch (op) {
2060 case glslang::EOpLessThan:
2061 if (isFloat)
2062 binOp = spv::OpFOrdLessThan;
2063 else if (isUnsigned)
2064 binOp = spv::OpULessThan;
2065 else
2066 binOp = spv::OpSLessThan;
2067 break;
2068 case glslang::EOpGreaterThan:
2069 if (isFloat)
2070 binOp = spv::OpFOrdGreaterThan;
2071 else if (isUnsigned)
2072 binOp = spv::OpUGreaterThan;
2073 else
2074 binOp = spv::OpSGreaterThan;
2075 break;
2076 case glslang::EOpLessThanEqual:
2077 if (isFloat)
2078 binOp = spv::OpFOrdLessThanEqual;
2079 else if (isUnsigned)
2080 binOp = spv::OpULessThanEqual;
2081 else
2082 binOp = spv::OpSLessThanEqual;
2083 break;
2084 case glslang::EOpGreaterThanEqual:
2085 if (isFloat)
2086 binOp = spv::OpFOrdGreaterThanEqual;
2087 else if (isUnsigned)
2088 binOp = spv::OpUGreaterThanEqual;
2089 else
2090 binOp = spv::OpSGreaterThanEqual;
2091 break;
2092 case glslang::EOpEqual:
2093 case glslang::EOpVectorEqual:
2094 if (isFloat)
2095 binOp = spv::OpFOrdEqual;
2096 else
2097 binOp = spv::OpIEqual;
2098 break;
2099 case glslang::EOpNotEqual:
2100 case glslang::EOpVectorNotEqual:
2101 if (isFloat)
2102 binOp = spv::OpFOrdNotEqual;
2103 else
2104 binOp = spv::OpINotEqual;
2105 break;
2106 default:
2107 break;
2108 }
2109
2110 if (binOp != spv::OpNop) {
2111 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2112 builder.setPrecision(id, precision);
2113
2114 return id;
2115 }
2116
2117 return 0;
2118}
2119
2120spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, bool isFloat)
2121{
2122 spv::Op unaryOp = spv::OpNop;
2123 int libCall = -1;
2124
2125 switch (op) {
2126 case glslang::EOpNegative:
2127 if (isFloat)
2128 unaryOp = spv::OpFNegate;
2129 else
2130 unaryOp = spv::OpSNegate;
2131 break;
2132
2133 case glslang::EOpLogicalNot:
2134 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002135 unaryOp = spv::OpLogicalNot;
2136 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002137 case glslang::EOpBitwiseNot:
2138 unaryOp = spv::OpNot;
2139 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002140
John Kessenich140f3df2015-06-26 16:58:36 -06002141 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002142 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002143 break;
2144 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002145 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002146 break;
2147 case glslang::EOpTranspose:
2148 unaryOp = spv::OpTranspose;
2149 break;
2150
2151 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002152 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002153 break;
2154 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002155 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002156 break;
2157 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002158 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002159 break;
2160 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002161 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002162 break;
2163 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002164 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002165 break;
2166 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002167 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002168 break;
2169 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002170 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002171 break;
2172 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002173 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002174 break;
2175
2176 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002177 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002178 break;
2179 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002180 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002181 break;
2182 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002183 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002184 break;
2185 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002186 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002187 break;
2188 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002189 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002190 break;
2191 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002192 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002193 break;
2194
2195 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002196 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002197 break;
2198 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002199 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002200 break;
2201
2202 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002203 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002204 break;
2205 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002206 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002207 break;
2208 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002209 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002210 break;
2211 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002212 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002213 break;
2214 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002215 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002216 break;
2217 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002218 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002219 break;
2220
2221 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002222 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002223 break;
2224 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002225 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002226 break;
2227 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002228 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002229 break;
2230 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002231 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002232 break;
2233 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002234 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002235 break;
2236 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002237 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002238 break;
2239
2240 case glslang::EOpIsNan:
2241 unaryOp = spv::OpIsNan;
2242 break;
2243 case glslang::EOpIsInf:
2244 unaryOp = spv::OpIsInf;
2245 break;
2246
John Kessenich140f3df2015-06-26 16:58:36 -06002247 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002248 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002249 break;
2250 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002251 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002252 break;
2253 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002254 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002255 break;
2256 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002257 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002258 break;
2259 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002260 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002261 break;
2262 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002263 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002264 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002265 case glslang::EOpPackSnorm4x8:
2266 libCall = spv::GLSLstd450PackSnorm4x8;
2267 break;
2268 case glslang::EOpUnpackSnorm4x8:
2269 libCall = spv::GLSLstd450UnpackSnorm4x8;
2270 break;
2271 case glslang::EOpPackUnorm4x8:
2272 libCall = spv::GLSLstd450PackUnorm4x8;
2273 break;
2274 case glslang::EOpUnpackUnorm4x8:
2275 libCall = spv::GLSLstd450UnpackUnorm4x8;
2276 break;
2277 case glslang::EOpPackDouble2x32:
2278 libCall = spv::GLSLstd450PackDouble2x32;
2279 break;
2280 case glslang::EOpUnpackDouble2x32:
2281 libCall = spv::GLSLstd450UnpackDouble2x32;
2282 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002283
2284 case glslang::EOpDPdx:
2285 unaryOp = spv::OpDPdx;
2286 break;
2287 case glslang::EOpDPdy:
2288 unaryOp = spv::OpDPdy;
2289 break;
2290 case glslang::EOpFwidth:
2291 unaryOp = spv::OpFwidth;
2292 break;
2293 case glslang::EOpDPdxFine:
2294 unaryOp = spv::OpDPdxFine;
2295 break;
2296 case glslang::EOpDPdyFine:
2297 unaryOp = spv::OpDPdyFine;
2298 break;
2299 case glslang::EOpFwidthFine:
2300 unaryOp = spv::OpFwidthFine;
2301 break;
2302 case glslang::EOpDPdxCoarse:
2303 unaryOp = spv::OpDPdxCoarse;
2304 break;
2305 case glslang::EOpDPdyCoarse:
2306 unaryOp = spv::OpDPdyCoarse;
2307 break;
2308 case glslang::EOpFwidthCoarse:
2309 unaryOp = spv::OpFwidthCoarse;
2310 break;
2311
2312 case glslang::EOpAny:
2313 unaryOp = spv::OpAny;
2314 break;
2315 case glslang::EOpAll:
2316 unaryOp = spv::OpAll;
2317 break;
2318
2319 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002320 if (isFloat)
2321 libCall = spv::GLSLstd450FAbs;
2322 else
2323 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002324 break;
2325 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002326 if (isFloat)
2327 libCall = spv::GLSLstd450FSign;
2328 else
2329 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002330 break;
2331
John Kessenichfc51d282015-08-19 13:34:18 -06002332 case glslang::EOpAtomicCounterIncrement:
2333 case glslang::EOpAtomicCounterDecrement:
2334 case glslang::EOpAtomicCounter:
2335 {
2336 // Handle all of the atomics in one place, in createAtomicOperation()
2337 std::vector<spv::Id> operands;
2338 operands.push_back(operand);
2339 return createAtomicOperation(op, precision, typeId, operands);
2340 }
2341
2342 case glslang::EOpImageLoad:
2343 unaryOp = spv::OpImageRead;
2344 break;
2345
2346 case glslang::EOpBitFieldReverse:
2347 unaryOp = spv::OpBitReverse;
2348 break;
2349 case glslang::EOpBitCount:
2350 unaryOp = spv::OpBitCount;
2351 break;
2352 case glslang::EOpFindLSB:
2353 libCall = spv::GLSLstd450FindILSB;
2354 break;
2355 case glslang::EOpFindMSB:
2356 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2357 libCall = spv::GLSLstd450FindSMSB;
2358 break;
2359
John Kessenich140f3df2015-06-26 16:58:36 -06002360 default:
2361 return 0;
2362 }
2363
2364 spv::Id id;
2365 if (libCall >= 0) {
2366 std::vector<spv::Id> args;
2367 args.push_back(operand);
2368 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2369 } else
2370 id = builder.createUnaryOp(unaryOp, typeId, operand);
2371
2372 builder.setPrecision(id, precision);
2373
2374 return id;
2375}
2376
2377spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2378{
2379 spv::Op convOp = spv::OpNop;
2380 spv::Id zero = 0;
2381 spv::Id one = 0;
2382
2383 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2384
2385 switch (op) {
2386 case glslang::EOpConvIntToBool:
2387 case glslang::EOpConvUintToBool:
2388 zero = builder.makeUintConstant(0);
2389 zero = makeSmearedConstant(zero, vectorSize);
2390 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2391
2392 case glslang::EOpConvFloatToBool:
2393 zero = builder.makeFloatConstant(0.0F);
2394 zero = makeSmearedConstant(zero, vectorSize);
2395 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2396
2397 case glslang::EOpConvDoubleToBool:
2398 zero = builder.makeDoubleConstant(0.0);
2399 zero = makeSmearedConstant(zero, vectorSize);
2400 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2401
2402 case glslang::EOpConvBoolToFloat:
2403 convOp = spv::OpSelect;
2404 zero = builder.makeFloatConstant(0.0);
2405 one = builder.makeFloatConstant(1.0);
2406 break;
2407 case glslang::EOpConvBoolToDouble:
2408 convOp = spv::OpSelect;
2409 zero = builder.makeDoubleConstant(0.0);
2410 one = builder.makeDoubleConstant(1.0);
2411 break;
2412 case glslang::EOpConvBoolToInt:
2413 zero = builder.makeIntConstant(0);
2414 one = builder.makeIntConstant(1);
2415 convOp = spv::OpSelect;
2416 break;
2417 case glslang::EOpConvBoolToUint:
2418 zero = builder.makeUintConstant(0);
2419 one = builder.makeUintConstant(1);
2420 convOp = spv::OpSelect;
2421 break;
2422
2423 case glslang::EOpConvIntToFloat:
2424 case glslang::EOpConvIntToDouble:
2425 convOp = spv::OpConvertSToF;
2426 break;
2427
2428 case glslang::EOpConvUintToFloat:
2429 case glslang::EOpConvUintToDouble:
2430 convOp = spv::OpConvertUToF;
2431 break;
2432
2433 case glslang::EOpConvDoubleToFloat:
2434 case glslang::EOpConvFloatToDouble:
2435 convOp = spv::OpFConvert;
2436 break;
2437
2438 case glslang::EOpConvFloatToInt:
2439 case glslang::EOpConvDoubleToInt:
2440 convOp = spv::OpConvertFToS;
2441 break;
2442
2443 case glslang::EOpConvUintToInt:
2444 case glslang::EOpConvIntToUint:
2445 convOp = spv::OpBitcast;
2446 break;
2447
2448 case glslang::EOpConvFloatToUint:
2449 case glslang::EOpConvDoubleToUint:
2450 convOp = spv::OpConvertFToU;
2451 break;
2452 default:
2453 break;
2454 }
2455
2456 spv::Id result = 0;
2457 if (convOp == spv::OpNop)
2458 return result;
2459
2460 if (convOp == spv::OpSelect) {
2461 zero = makeSmearedConstant(zero, vectorSize);
2462 one = makeSmearedConstant(one, vectorSize);
2463 result = builder.createTriOp(convOp, destType, operand, one, zero);
2464 } else
2465 result = builder.createUnaryOp(convOp, destType, operand);
2466
2467 builder.setPrecision(result, precision);
2468
2469 return result;
2470}
2471
2472spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2473{
2474 if (vectorSize == 0)
2475 return constant;
2476
2477 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2478 std::vector<spv::Id> components;
2479 for (int c = 0; c < vectorSize; ++c)
2480 components.push_back(constant);
2481 return builder.makeCompositeConstant(vectorTypeId, components);
2482}
2483
John Kessenich426394d2015-07-23 10:22:48 -06002484// For glslang ops that map to SPV atomic opCodes
2485spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands)
2486{
2487 spv::Op opCode = spv::OpNop;
2488
2489 switch (op) {
2490 case glslang::EOpAtomicAdd:
2491 opCode = spv::OpAtomicIAdd;
2492 break;
2493 case glslang::EOpAtomicMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002494 opCode = spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002495 break;
2496 case glslang::EOpAtomicMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002497 opCode = spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002498 break;
2499 case glslang::EOpAtomicAnd:
2500 opCode = spv::OpAtomicAnd;
2501 break;
2502 case glslang::EOpAtomicOr:
2503 opCode = spv::OpAtomicOr;
2504 break;
2505 case glslang::EOpAtomicXor:
2506 opCode = spv::OpAtomicXor;
2507 break;
2508 case glslang::EOpAtomicExchange:
2509 opCode = spv::OpAtomicExchange;
2510 break;
2511 case glslang::EOpAtomicCompSwap:
2512 opCode = spv::OpAtomicCompareExchange;
2513 break;
2514 case glslang::EOpAtomicCounterIncrement:
2515 opCode = spv::OpAtomicIIncrement;
2516 break;
2517 case glslang::EOpAtomicCounterDecrement:
2518 opCode = spv::OpAtomicIDecrement;
2519 break;
2520 case glslang::EOpAtomicCounter:
2521 opCode = spv::OpAtomicLoad;
2522 break;
2523 default:
2524 spv::MissingFunctionality("missing nested atomic");
2525 break;
2526 }
2527
2528 // Sort out the operands
2529 // - mapping from glslang -> SPV
2530 // - there are extra SPV operands with no glslang source
2531 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2532 auto opIt = operands.begin(); // walk the glslang operands
2533 spvAtomicOperands.push_back(*(opIt++));
John Kessenich5e4b1242015-08-06 22:53:06 -06002534 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2535 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
John Kessenich426394d2015-07-23 10:22:48 -06002536
2537 // Add the rest of the operands, skipping the first one, which was dealt with above.
2538 // For some ops, there are none, for some 1, for compare-exchange, 2.
2539 for (; opIt != operands.end(); ++opIt)
2540 spvAtomicOperands.push_back(*opIt);
2541
2542 return builder.createOp(opCode, typeId, spvAtomicOperands);
2543}
2544
John Kessenich5e4b1242015-08-06 22:53:06 -06002545spv::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 -06002546{
John Kessenich5e4b1242015-08-06 22:53:06 -06002547 bool isUnsigned = typeProxy == glslang::EbtUint;
2548 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2549
John Kessenich140f3df2015-06-26 16:58:36 -06002550 spv::Op opCode = spv::OpNop;
2551 int libCall = -1;
2552
2553 switch (op) {
2554 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002555 if (isFloat)
2556 libCall = spv::GLSLstd450FMin;
2557 else if (isUnsigned)
2558 libCall = spv::GLSLstd450UMin;
2559 else
2560 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002561 break;
2562 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002563 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002564 break;
2565 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002566 if (isFloat)
2567 libCall = spv::GLSLstd450FMax;
2568 else if (isUnsigned)
2569 libCall = spv::GLSLstd450UMax;
2570 else
2571 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002572 break;
2573 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002574 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002575 break;
2576 case glslang::EOpDot:
2577 opCode = spv::OpDot;
2578 break;
2579 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002580 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002581 break;
2582
2583 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002584 if (isFloat)
2585 libCall = spv::GLSLstd450FClamp;
2586 else if (isUnsigned)
2587 libCall = spv::GLSLstd450UClamp;
2588 else
2589 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002590 break;
2591 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002592 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002593 break;
2594 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002595 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002596 break;
2597 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002598 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002599 break;
2600
2601 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002602 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002603 break;
2604 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002605 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002606 break;
2607 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002608 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002609 break;
2610 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002611 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002612 break;
2613 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002614 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002615 break;
John Kessenich426394d2015-07-23 10:22:48 -06002616
John Kessenich140f3df2015-06-26 16:58:36 -06002617 default:
2618 return 0;
2619 }
2620
2621 spv::Id id = 0;
2622 if (libCall >= 0)
2623 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2624 else {
2625 switch (operands.size()) {
2626 case 0:
2627 // should all be handled by visitAggregate and createNoArgOperation
2628 assert(0);
2629 return 0;
2630 case 1:
2631 // should all be handled by createUnaryOperation
2632 assert(0);
2633 return 0;
2634 case 2:
2635 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2636 break;
2637 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002638 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002639 break;
2640 default:
2641 // These do not exist yet
2642 assert(0 && "operation with more than 3 operands");
2643 break;
2644 }
2645 }
2646
2647 builder.setPrecision(id, precision);
2648
2649 return id;
2650}
2651
2652// Intrinsics with no arguments, no return value, and no precision.
2653spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2654{
2655 // TODO: get the barrier operands correct
2656
2657 switch (op) {
2658 case glslang::EOpEmitVertex:
2659 builder.createNoResultOp(spv::OpEmitVertex);
2660 return 0;
2661 case glslang::EOpEndPrimitive:
2662 builder.createNoResultOp(spv::OpEndPrimitive);
2663 return 0;
2664 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002665 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2666 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002667 return 0;
2668 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002669 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002670 return 0;
2671 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002672 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002673 return 0;
2674 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002675 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002676 return 0;
2677 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002678 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002679 return 0;
2680 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002681 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002682 return 0;
2683 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002684 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002685 return 0;
2686 default:
2687 spv::MissingFunctionality("operation with no arguments");
2688 return 0;
2689 }
2690}
2691
2692spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2693{
John Kessenich2f273362015-07-18 22:34:27 -06002694 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002695 spv::Id id;
2696 if (symbolValues.end() != iter) {
2697 id = iter->second;
2698 return id;
2699 }
2700
2701 // it was not found, create it
2702 id = createSpvVariable(symbol);
2703 symbolValues[symbol->getId()] = id;
2704
2705 if (! symbol->getType().isStruct()) {
2706 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2707 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2708 if (symbol->getQualifier().hasLocation())
2709 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2710 if (symbol->getQualifier().hasIndex())
2711 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2712 if (symbol->getQualifier().hasComponent())
2713 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2714 if (glslangIntermediate->getXfbMode()) {
2715 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002716 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002717 if (symbol->getQualifier().hasXfbBuffer())
2718 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2719 if (symbol->getQualifier().hasXfbOffset())
2720 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2721 }
2722 }
2723
2724 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2725 if (symbol->getQualifier().hasStream())
2726 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2727 if (symbol->getQualifier().hasSet())
2728 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2729 if (symbol->getQualifier().hasBinding())
2730 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2731 if (glslangIntermediate->getXfbMode()) {
2732 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002733 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002734 if (symbol->getQualifier().hasXfbBuffer())
2735 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2736 }
2737
2738 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002739 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002740 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002741 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002742
2743 if (linkageOnly)
2744 builder.addDecoration(id, spv::DecorationNoStaticUse);
2745
2746 return id;
2747}
2748
2749void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2750{
2751 if (dec != spv::BadValue)
2752 builder.addDecoration(id, dec);
2753}
2754
2755void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2756{
2757 if (dec != spv::BadValue)
2758 builder.addMemberDecoration(id, (unsigned)member, dec);
2759}
2760
2761// Use 'consts' as the flattened glslang source of scalar constants to recursively
2762// build the aggregate SPIR-V constant.
2763//
2764// If there are not enough elements present in 'consts', 0 will be substituted;
2765// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2766//
2767spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2768{
2769 // vector of constants for SPIR-V
2770 std::vector<spv::Id> spvConsts;
2771
2772 // Type is used for struct and array constants
2773 spv::Id typeId = convertGlslangToSpvType(glslangType);
2774
2775 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002776 glslang::TType elementType(glslangType, 0);
2777 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002778 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2779 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002780 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002781 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2782 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2783 } else if (glslangType.getStruct()) {
2784 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2785 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2786 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2787 } else if (glslangType.isVector()) {
2788 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2789 bool zero = nextConst >= consts.size();
2790 switch (glslangType.getBasicType()) {
2791 case glslang::EbtInt:
2792 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2793 break;
2794 case glslang::EbtUint:
2795 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2796 break;
2797 case glslang::EbtFloat:
2798 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2799 break;
2800 case glslang::EbtDouble:
2801 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2802 break;
2803 case glslang::EbtBool:
2804 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2805 break;
2806 default:
2807 spv::MissingFunctionality("constant vector type");
2808 break;
2809 }
2810 ++nextConst;
2811 }
2812 } else {
2813 // we have a non-aggregate (scalar) constant
2814 bool zero = nextConst >= consts.size();
2815 spv::Id scalar = 0;
2816 switch (glslangType.getBasicType()) {
2817 case glslang::EbtInt:
2818 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2819 break;
2820 case glslang::EbtUint:
2821 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2822 break;
2823 case glslang::EbtFloat:
2824 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2825 break;
2826 case glslang::EbtDouble:
2827 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2828 break;
2829 case glslang::EbtBool:
2830 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2831 break;
2832 default:
2833 spv::MissingFunctionality("constant scalar type");
2834 break;
2835 }
2836 ++nextConst;
2837 return scalar;
2838 }
2839
2840 return builder.makeCompositeConstant(typeId, spvConsts);
2841}
2842
2843}; // end anonymous namespace
2844
2845namespace glslang {
2846
John Kessenich68d78fd2015-07-12 19:28:10 -06002847void GetSpirvVersion(std::string& version)
2848{
John Kessenich9e55f632015-07-15 10:03:39 -06002849 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002850 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002851 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002852 version = buf;
2853}
2854
John Kessenich140f3df2015-06-26 16:58:36 -06002855// Write SPIR-V out to a binary file
2856void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
2857{
2858 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06002859 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06002860 for (int i = 0; i < (int)spirv.size(); ++i) {
2861 unsigned int word = spirv[i];
2862 out.write((const char*)&word, 4);
2863 }
2864 out.close();
2865}
2866
2867//
2868// Set up the glslang traversal
2869//
2870void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
2871{
2872 TIntermNode* root = intermediate.getTreeRoot();
2873
2874 if (root == 0)
2875 return;
2876
2877 glslang::GetThreadPoolAllocator().push();
2878
2879 TGlslangToSpvTraverser it(&intermediate);
2880
2881 root->traverse(&it);
2882
2883 it.dumpSpv(spirv);
2884
2885 glslang::GetThreadPoolAllocator().pop();
2886}
2887
2888}; // end namespace glslang