blob: be8d65962403ecbfe2441ee8a8e2d9bc8a8db61c [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
2//Copyright (C) 2014 LunarG, Inc.
3//
4//All rights reserved.
5//
6//Redistribution and use in source and binary forms, with or without
7//modification, are permitted provided that the following conditions
8//are met:
9//
10// Redistributions of source code must retain the above copyright
11// notice, this list of conditions and the following disclaimer.
12//
13// Redistributions in binary form must reproduce the above
14// copyright notice, this list of conditions and the following
15// disclaimer in the documentation and/or other materials provided
16// with the distribution.
17//
18// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
19// contributors may be used to endorse or promote products derived
20// from this software without specific prior written permission.
21//
22//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
23//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
24//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
25//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
26//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
27//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
29//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
30//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
32//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33//POSSIBILITY OF SUCH DAMAGE.
34
35//
36// Author: John Kessenich, LunarG
37//
38// Visit the nodes in the glslang intermediate tree representation to
39// translate them to SPIR-V.
40//
41
John Kessenich5e4b1242015-08-06 22:53:06 -060042#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060043#include "GlslangToSpv.h"
44#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060045namespace spv {
46 #include "GLSL.std.450.h"
47}
John Kessenich140f3df2015-06-26 16:58:36 -060048
49// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020050#include "../glslang/MachineIndependent/localintermediate.h"
51#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060052#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060053
54#include <string>
55#include <map>
56#include <list>
57#include <vector>
58#include <stack>
59#include <fstream>
60
61namespace {
62
63const int GlslangMagic = 0x51a;
64
65//
66// The main holder of information for translating glslang to SPIR-V.
67//
68// Derives from the AST walking base class.
69//
70class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
71public:
72 TGlslangToSpvTraverser(const glslang::TIntermediate*);
73 virtual ~TGlslangToSpvTraverser();
74
75 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
76 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
77 void visitConstantUnion(glslang::TIntermConstantUnion*);
78 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
79 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
80 void visitSymbol(glslang::TIntermSymbol* symbol);
81 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
82 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
83 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
84
85 void dumpSpv(std::vector<unsigned int>& out) { builder.dump(out); }
86
87protected:
88 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
89 spv::Id getSampledType(const glslang::TSampler&);
90 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich31ed4832015-09-09 17:51:38 -060091 spv::Id convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout);
92 bool requiresExplicitLayout(const glslang::TType& type) const;
Jason Ekstrand54aedf12015-09-05 09:50:58 -070093 int getArrayStride(const glslang::TType& arrayType);
94 int getMatrixStride(const glslang::TType& matrixType);
John Kessenich5e4b1242015-08-06 22:53:06 -060095 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset);
John Kessenich140f3df2015-06-26 16:58:36 -060096
97 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
98 void makeFunctions(const glslang::TIntermSequence&);
99 void makeGlobalInitializers(const glslang::TIntermSequence&);
100 void visitFunctions(const glslang::TIntermSequence&);
101 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800102 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600103 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
104 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600105 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
106
107 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
Rex Xu04db3f52015-09-16 11:44:02 +0800108 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600109 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
110 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800111 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600112 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600113 spv::Id createNoArgOperation(glslang::TOperator op);
114 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
115 void addDecoration(spv::Id id, spv::Decoration dec);
116 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
117 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst);
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;
Rex Xufc618912015-09-09 16:42:49 +0800184 else if (type.getBasicType() == glslang::EbtAtomicUint)
185 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600186 else
187 return spv::StorageClassUniformConstant;
188 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
189 } else {
190 switch (type.getQualifier().storage) {
191 case glslang::EvqShared: return spv::StorageClassWorkgroupLocal; break;
192 case glslang::EvqGlobal: return spv::StorageClassPrivateGlobal;
193 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
194 case glslang::EvqTemporary: return spv::StorageClassFunction;
195 default:
196 spv::MissingFunctionality("unknown glslang storage class");
197 return spv::StorageClassFunction;
198 }
199 }
200}
201
202// Translate glslang sampler type to SPIR-V dimensionality.
203spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
204{
205 switch (sampler.dim) {
206 case glslang::Esd1D: return spv::Dim1D;
207 case glslang::Esd2D: return spv::Dim2D;
208 case glslang::Esd3D: return spv::Dim3D;
209 case glslang::EsdCube: return spv::DimCube;
210 case glslang::EsdRect: return spv::DimRect;
211 case glslang::EsdBuffer: return spv::DimBuffer;
212 default:
213 spv::MissingFunctionality("unknown sampler dimension");
214 return spv::Dim2D;
215 }
216}
217
218// Translate glslang type to SPIR-V precision decorations.
219spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
220{
221 switch (type.getQualifier().precision) {
John Kessenich5e4b1242015-08-06 22:53:06 -0600222 case glslang::EpqLow: return spv::DecorationRelaxedPrecision; // TODO: Map instead to 16-bit types?
223 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
224 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600225 default:
226 return spv::NoPrecision;
227 }
228}
229
230// Translate glslang type to SPIR-V block decorations.
231spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
232{
233 if (type.getBasicType() == glslang::EbtBlock) {
234 switch (type.getQualifier().storage) {
235 case glslang::EvqUniform: return spv::DecorationBlock;
236 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
237 case glslang::EvqVaryingIn: return spv::DecorationBlock;
238 case glslang::EvqVaryingOut: return spv::DecorationBlock;
239 default:
240 spv::MissingFunctionality("kind of block");
241 break;
242 }
243 }
244
245 return (spv::Decoration)spv::BadValue;
246}
247
248// Translate glslang type to SPIR-V layout decorations.
249spv::Decoration TranslateLayoutDecoration(const glslang::TType& type)
250{
251 if (type.isMatrix()) {
252 switch (type.getQualifier().layoutMatrix) {
253 case glslang::ElmRowMajor:
254 return spv::DecorationRowMajor;
255 default:
256 return spv::DecorationColMajor;
257 }
258 } else {
259 switch (type.getBasicType()) {
260 default:
261 return (spv::Decoration)spv::BadValue;
262 break;
263 case glslang::EbtBlock:
264 switch (type.getQualifier().storage) {
265 case glslang::EvqUniform:
266 case glslang::EvqBuffer:
267 switch (type.getQualifier().layoutPacking) {
268 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600269 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
270 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600271 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 }
273 case glslang::EvqVaryingIn:
274 case glslang::EvqVaryingOut:
275 if (type.getQualifier().layoutPacking != glslang::ElpNone)
276 spv::MissingFunctionality("in/out block layout");
277 return (spv::Decoration)spv::BadValue;
278 default:
279 spv::MissingFunctionality("block storage qualification");
280 return (spv::Decoration)spv::BadValue;
281 }
282 }
283 }
284}
285
286// Translate glslang type to SPIR-V interpolation decorations.
287spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
288{
289 if (type.getQualifier().smooth)
290 return spv::DecorationSmooth;
291 if (type.getQualifier().nopersp)
292 return spv::DecorationNoperspective;
293 else if (type.getQualifier().patch)
294 return spv::DecorationPatch;
295 else if (type.getQualifier().flat)
296 return spv::DecorationFlat;
297 else if (type.getQualifier().centroid)
298 return spv::DecorationCentroid;
299 else if (type.getQualifier().sample)
300 return spv::DecorationSample;
301 else
302 return (spv::Decoration)spv::BadValue;
303}
304
305// If glslang type is invaraiant, return SPIR-V invariant decoration.
306spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
307{
308 if (type.getQualifier().invariant)
309 return spv::DecorationInvariant;
310 else
311 return (spv::Decoration)spv::BadValue;
312}
313
314// Translate glslang built-in variable to SPIR-V built in decoration.
315spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
316{
317 switch (builtIn) {
318 case glslang::EbvPosition: return spv::BuiltInPosition;
319 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600320 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
321 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
322 case glslang::EbvVertexId: return spv::BuiltInVertexId;
323 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
324 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
325 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
326 case glslang::EbvLayer: return spv::BuiltInLayer;
327 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
328 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
329 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
330 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
331 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
332 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
333 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
334 case glslang::EbvFace: return spv::BuiltInFrontFacing;
335 case glslang::EbvSampleId: return spv::BuiltInSampleId;
336 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
337 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
338 case glslang::EbvFragColor: return spv::BuiltInFragColor;
339 case glslang::EbvFragData: return spv::BuiltInFragColor;
340 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
341 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
342 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
343 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
344 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
345 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
346 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
347 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
348 default: return (spv::BuiltIn)spv::BadValue;
349 }
350}
351
Rex Xufc618912015-09-09 16:42:49 +0800352// Translate glslang image layout format to SPIR-V image format.
353spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
354{
355 assert(type.getBasicType() == glslang::EbtSampler);
356
357 switch (type.getQualifier().layoutFormat) {
358 case glslang::ElfNone: return spv::ImageFormatUnknown;
359 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
360 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
361 case glslang::ElfR32f: return spv::ImageFormatR32f;
362 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
363 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
364 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
365 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
366 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
367 case glslang::ElfR16f: return spv::ImageFormatR16f;
368 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
369 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
370 case glslang::ElfRg16: return spv::ImageFormatRg16;
371 case glslang::ElfRg8: return spv::ImageFormatRg8;
372 case glslang::ElfR16: return spv::ImageFormatR16;
373 case glslang::ElfR8: return spv::ImageFormatR8;
374 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
375 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
376 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
377 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
378 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
379 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
380 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
381 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
382 case glslang::ElfR32i: return spv::ImageFormatR32i;
383 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
384 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
385 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
386 case glslang::ElfR16i: return spv::ImageFormatR16i;
387 case glslang::ElfR8i: return spv::ImageFormatR8i;
388 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
389 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
390 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
391 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
392 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
393 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
394 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
395 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
396 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
397 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
398 default: return (spv::ImageFormat)spv::BadValue;
399 }
400}
401
John Kessenich140f3df2015-06-26 16:58:36 -0600402//
403// Implement the TGlslangToSpvTraverser class.
404//
405
406TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
407 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
408 builder(GlslangMagic),
409 inMain(false), mainTerminated(false), linkageOnly(false),
410 glslangIntermediate(glslangIntermediate)
411{
412 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
413
414 builder.clearAccessChain();
415 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
416 stdBuiltins = builder.import("GLSL.std.450");
417 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
418 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600419 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600420
421 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600422 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
423 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600424 builder.addSourceExtension(it->c_str());
425
426 // Add the top-level modes for this shader.
427
428 if (glslangIntermediate->getXfbMode())
429 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
430
431 unsigned int mode;
432 switch (glslangIntermediate->getStage()) {
433 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600434 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600435 break;
436
437 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600438 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600439 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
440 break;
441
442 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600443 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600444 switch (glslangIntermediate->getInputPrimitive()) {
445 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
446 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
447 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600448 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600449 }
450 if (mode != spv::BadValue)
451 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
452
John Kesseniche6903322015-10-13 16:29:02 -0600453 switch (glslangIntermediate->getVertexSpacing()) {
454 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
455 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
456 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
457 default: mode = spv::BadValue; break;
458 }
459 if (mode != spv::BadValue)
460 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
461
462 switch (glslangIntermediate->getVertexOrder()) {
463 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
464 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
465 default: mode = spv::BadValue; break;
466 }
467 if (mode != spv::BadValue)
468 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
469
470 if (glslangIntermediate->getPointMode())
471 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600472 break;
473
474 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600475 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600476 switch (glslangIntermediate->getInputPrimitive()) {
477 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
478 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
479 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
480 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
481 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
482 default: mode = spv::BadValue; break;
483 }
484 if (mode != spv::BadValue)
485 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600486
John Kessenich140f3df2015-06-26 16:58:36 -0600487 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
488
489 switch (glslangIntermediate->getOutputPrimitive()) {
490 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
491 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
492 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
493 default: mode = spv::BadValue; break;
494 }
495 if (mode != spv::BadValue)
496 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
497 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
498 break;
499
500 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600501 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600502 if (glslangIntermediate->getPixelCenterInteger())
503 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600504
John Kessenich140f3df2015-06-26 16:58:36 -0600505 if (glslangIntermediate->getOriginUpperLeft())
506 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600507 else
508 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600509
510 if (glslangIntermediate->getEarlyFragmentTests())
511 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
512
513 switch(glslangIntermediate->getDepth()) {
514 case glslang::EldAny: mode = spv::ExecutionModeDepthAny; break;
515 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
516 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
517 default: mode = spv::BadValue; break;
518 }
519 if (mode != spv::BadValue)
520 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
521
522 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
523 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600524 break;
525
526 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600527 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600528 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
529 glslangIntermediate->getLocalSize(1),
530 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600531 break;
532
533 default:
534 break;
535 }
536
537}
538
539TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
540{
541 if (! mainTerminated) {
542 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
543 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600544 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600545 }
546}
547
548//
549// Implement the traversal functions.
550//
551// Return true from interior nodes to have the external traversal
552// continue on to children. Return false if children were
553// already processed.
554//
555
556//
557// Symbols can turn into
558// - uniform/input reads
559// - output writes
560// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
561// - something simple that degenerates into the last bullet
562//
563void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
564{
565 // getSymbolId() will set up all the IO decorations on the first call.
566 // Formal function parameters were mapped during makeFunctions().
567 spv::Id id = getSymbolId(symbol);
568
569 if (! linkageOnly) {
570 // Prepare to generate code for the access
571
572 // L-value chains will be computed left to right. We're on the symbol now,
573 // which is the left-most part of the access chain, so now is "clear" time,
574 // followed by setting the base.
575 builder.clearAccessChain();
576
577 // For now, we consider all user variables as being in memory, so they are pointers,
578 // except for "const in" arguments to a function, which are an intermediate object.
579 // See comments in handleUserFunctionCall().
580 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
581 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
582 builder.setAccessChainRValue(id);
583 else
584 builder.setAccessChainLValue(id);
585 }
586}
587
588bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
589{
590 // First, handle special cases
591 switch (node->getOp()) {
592 case glslang::EOpAssign:
593 case glslang::EOpAddAssign:
594 case glslang::EOpSubAssign:
595 case glslang::EOpMulAssign:
596 case glslang::EOpVectorTimesMatrixAssign:
597 case glslang::EOpVectorTimesScalarAssign:
598 case glslang::EOpMatrixTimesScalarAssign:
599 case glslang::EOpMatrixTimesMatrixAssign:
600 case glslang::EOpDivAssign:
601 case glslang::EOpModAssign:
602 case glslang::EOpAndAssign:
603 case glslang::EOpInclusiveOrAssign:
604 case glslang::EOpExclusiveOrAssign:
605 case glslang::EOpLeftShiftAssign:
606 case glslang::EOpRightShiftAssign:
607 // A bin-op assign "a += b" means the same thing as "a = a + b"
608 // where a is evaluated before b. For a simple assignment, GLSL
609 // says to evaluate the left before the right. So, always, left
610 // node then right node.
611 {
612 // get the left l-value, save it away
613 builder.clearAccessChain();
614 node->getLeft()->traverse(this);
615 spv::Builder::AccessChain lValue = builder.getAccessChain();
616
617 // evaluate the right
618 builder.clearAccessChain();
619 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600620 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600621
622 if (node->getOp() != glslang::EOpAssign) {
623 // the left is also an r-value
624 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600625 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600626
627 // do the operation
628 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
629 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
630 node->getType().getBasicType());
631
632 // these all need their counterparts in createBinaryOperation()
633 if (rValue == 0)
634 spv::MissingFunctionality("createBinaryOperation");
635 }
636
637 // store the result
638 builder.setAccessChain(lValue);
639 builder.accessChainStore(rValue);
640
641 // assignments are expressions having an rValue after they are evaluated...
642 builder.clearAccessChain();
643 builder.setAccessChainRValue(rValue);
644 }
645 return false;
646 case glslang::EOpIndexDirect:
647 case glslang::EOpIndexDirectStruct:
648 {
649 // Get the left part of the access chain.
650 node->getLeft()->traverse(this);
651
652 // Add the next element in the chain
653
654 int index = 0;
655 if (node->getRight()->getAsConstantUnion() == 0)
656 spv::MissingFunctionality("direct index without a constant node");
657 else
658 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
659
660 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
661 // This may be, e.g., an anonymous block-member selection, which generally need
662 // index remapping due to hidden members in anonymous blocks.
663 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
664 if (remapper.size() == 0)
665 spv::MissingFunctionality("block without member remapping");
666 else
667 index = remapper[index];
668 }
669
670 if (! node->getLeft()->getType().isArray() &&
671 node->getLeft()->getType().isVector() &&
672 node->getOp() == glslang::EOpIndexDirect) {
673 // This is essentially a hard-coded vector swizzle of size 1,
674 // so short circuit the access-chain stuff with a swizzle.
675 std::vector<unsigned> swizzle;
676 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600677 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600678 } else {
679 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600680 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600681 }
682 }
683 return false;
684 case glslang::EOpIndexIndirect:
685 {
686 // Structure or array or vector indirection.
687 // Will use native SPIR-V access-chain for struct and array indirection;
688 // matrices are arrays of vectors, so will also work for a matrix.
689 // Will use the access chain's 'component' for variable index into a vector.
690
691 // This adapter is building access chains left to right.
692 // Set up the access chain to the left.
693 node->getLeft()->traverse(this);
694
695 // save it so that computing the right side doesn't trash it
696 spv::Builder::AccessChain partial = builder.getAccessChain();
697
698 // compute the next index in the chain
699 builder.clearAccessChain();
700 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600701 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600702
703 // restore the saved access chain
704 builder.setAccessChain(partial);
705
706 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600707 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600708 else
John Kessenichfa668da2015-09-13 14:46:30 -0600709 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600710 }
711 return false;
712 case glslang::EOpVectorSwizzle:
713 {
714 node->getLeft()->traverse(this);
715 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
716 std::vector<unsigned> swizzle;
717 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
718 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600719 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600720 }
721 return false;
722 default:
723 break;
724 }
725
726 // Assume generic binary op...
727
728 // Get the operands
729 builder.clearAccessChain();
730 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600731 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600732
733 builder.clearAccessChain();
734 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600735 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600736
737 spv::Id result;
738 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
739
740 result = createBinaryOperation(node->getOp(), precision,
741 convertGlslangToSpvType(node->getType()), left, right,
742 node->getLeft()->getType().getBasicType());
743
744 if (! result) {
745 spv::MissingFunctionality("glslang binary operation");
746 } else {
747 builder.clearAccessChain();
748 builder.setAccessChainRValue(result);
749
750 return false;
751 }
752
753 return true;
754}
755
756bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
757{
John Kessenichfc51d282015-08-19 13:34:18 -0600758 spv::Id result = spv::NoResult;
759
760 // try texturing first
761 result = createImageTextureFunctionCall(node);
762 if (result != spv::NoResult) {
763 builder.clearAccessChain();
764 builder.setAccessChainRValue(result);
765
766 return false; // done with this node
767 }
768
769 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600770
771 if (node->getOp() == glslang::EOpArrayLength) {
772 // Quite special; won't want to evaluate the operand.
773
774 // Normal .length() would have been constant folded by the front-end.
775 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600776 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600777 assert(node->getOperand()->getType().isRuntimeSizedArray());
778 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
779 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600780 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
781 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600782
783 builder.clearAccessChain();
784 builder.setAccessChainRValue(length);
785
786 return false;
787 }
788
John Kessenichfc51d282015-08-19 13:34:18 -0600789 // Start by evaluating the operand
790
John Kessenich140f3df2015-06-26 16:58:36 -0600791 builder.clearAccessChain();
792 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800793
Rex Xufc618912015-09-09 16:42:49 +0800794 spv::Id operand = spv::NoResult;
795
796 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
797 node->getOp() == glslang::EOpAtomicCounterDecrement ||
798 node->getOp() == glslang::EOpAtomicCounter)
799 operand = builder.accessChainGetLValue(); // Special case l-value operands
800 else
Rex Xu30f92582015-09-14 10:38:56 +0800801 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600802
803 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
804
805 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600806 if (! result)
807 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600808
809 // if not, then possibly an operation
810 if (! result)
Rex Xu04db3f52015-09-16 11:44:02 +0800811 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600812
813 if (result) {
814 builder.clearAccessChain();
815 builder.setAccessChainRValue(result);
816
817 return false; // done with this node
818 }
819
820 // it must be a special case, check...
821 switch (node->getOp()) {
822 case glslang::EOpPostIncrement:
823 case glslang::EOpPostDecrement:
824 case glslang::EOpPreIncrement:
825 case glslang::EOpPreDecrement:
826 {
827 // we need the integer value "1" or the floating point "1.0" to add/subtract
828 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
829 builder.makeFloatConstant(1.0F) :
830 builder.makeIntConstant(1);
831 glslang::TOperator op;
832 if (node->getOp() == glslang::EOpPreIncrement ||
833 node->getOp() == glslang::EOpPostIncrement)
834 op = glslang::EOpAdd;
835 else
836 op = glslang::EOpSub;
837
838 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
839 convertGlslangToSpvType(node->getType()), operand, one,
840 node->getType().getBasicType());
841 if (result == 0)
842 spv::MissingFunctionality("createBinaryOperation for unary");
843
844 // The result of operation is always stored, but conditionally the
845 // consumed result. The consumed result is always an r-value.
846 builder.accessChainStore(result);
847 builder.clearAccessChain();
848 if (node->getOp() == glslang::EOpPreIncrement ||
849 node->getOp() == glslang::EOpPreDecrement)
850 builder.setAccessChainRValue(result);
851 else
852 builder.setAccessChainRValue(operand);
853 }
854
855 return false;
856
857 case glslang::EOpEmitStreamVertex:
858 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
859 return false;
860 case glslang::EOpEndStreamPrimitive:
861 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
862 return false;
863
864 default:
865 spv::MissingFunctionality("glslang unary");
866 break;
867 }
868
869 return true;
870}
871
872bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
873{
John Kessenichfc51d282015-08-19 13:34:18 -0600874 spv::Id result = spv::NoResult;
875
876 // try texturing
877 result = createImageTextureFunctionCall(node);
878 if (result != spv::NoResult) {
879 builder.clearAccessChain();
880 builder.setAccessChainRValue(result);
881
882 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600883 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800884 // "imageStore" is a special case, which has no result
885 return false;
886 }
John Kessenichfc51d282015-08-19 13:34:18 -0600887
John Kessenich140f3df2015-06-26 16:58:36 -0600888 glslang::TOperator binOp = glslang::EOpNull;
889 bool reduceComparison = true;
890 bool isMatrix = false;
891 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600892 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600893
894 assert(node->getOp());
895
896 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
897
898 switch (node->getOp()) {
899 case glslang::EOpSequence:
900 {
901 if (preVisit)
902 ++sequenceDepth;
903 else
904 --sequenceDepth;
905
906 if (sequenceDepth == 1) {
907 // If this is the parent node of all the functions, we want to see them
908 // early, so all call points have actual SPIR-V functions to reference.
909 // In all cases, still let the traverser visit the children for us.
910 makeFunctions(node->getAsAggregate()->getSequence());
911
912 // Also, we want all globals initializers to go into the entry of main(), before
913 // anything else gets there, so visit out of order, doing them all now.
914 makeGlobalInitializers(node->getAsAggregate()->getSequence());
915
916 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
917 // so do them manually.
918 visitFunctions(node->getAsAggregate()->getSequence());
919
920 return false;
921 }
922
923 return true;
924 }
925 case glslang::EOpLinkerObjects:
926 {
927 if (visit == glslang::EvPreVisit)
928 linkageOnly = true;
929 else
930 linkageOnly = false;
931
932 return true;
933 }
934 case glslang::EOpComma:
935 {
936 // processing from left to right naturally leaves the right-most
937 // lying around in the access chain
938 glslang::TIntermSequence& glslangOperands = node->getSequence();
939 for (int i = 0; i < (int)glslangOperands.size(); ++i)
940 glslangOperands[i]->traverse(this);
941
942 return false;
943 }
944 case glslang::EOpFunction:
945 if (visit == glslang::EvPreVisit) {
946 if (isShaderEntrypoint(node)) {
947 inMain = true;
948 builder.setBuildPoint(shaderEntry->getLastBlock());
949 } else {
950 handleFunctionEntry(node);
951 }
952 } else {
953 if (inMain)
954 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600955 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600956 inMain = false;
957 }
958
959 return true;
960 case glslang::EOpParameters:
961 // Parameters will have been consumed by EOpFunction processing, but not
962 // the body, so we still visited the function node's children, making this
963 // child redundant.
964 return false;
965 case glslang::EOpFunctionCall:
966 {
967 if (node->isUserDefined())
968 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600969
970 if (! result) {
971 spv::MissingFunctionality("glslang function call");
972 glslang::TConstUnionArray emptyConsts;
973 int nextConst = 0;
974 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
975 }
976 builder.clearAccessChain();
977 builder.setAccessChainRValue(result);
978
979 return false;
980 }
981 case glslang::EOpConstructMat2x2:
982 case glslang::EOpConstructMat2x3:
983 case glslang::EOpConstructMat2x4:
984 case glslang::EOpConstructMat3x2:
985 case glslang::EOpConstructMat3x3:
986 case glslang::EOpConstructMat3x4:
987 case glslang::EOpConstructMat4x2:
988 case glslang::EOpConstructMat4x3:
989 case glslang::EOpConstructMat4x4:
990 case glslang::EOpConstructDMat2x2:
991 case glslang::EOpConstructDMat2x3:
992 case glslang::EOpConstructDMat2x4:
993 case glslang::EOpConstructDMat3x2:
994 case glslang::EOpConstructDMat3x3:
995 case glslang::EOpConstructDMat3x4:
996 case glslang::EOpConstructDMat4x2:
997 case glslang::EOpConstructDMat4x3:
998 case glslang::EOpConstructDMat4x4:
999 isMatrix = true;
1000 // fall through
1001 case glslang::EOpConstructFloat:
1002 case glslang::EOpConstructVec2:
1003 case glslang::EOpConstructVec3:
1004 case glslang::EOpConstructVec4:
1005 case glslang::EOpConstructDouble:
1006 case glslang::EOpConstructDVec2:
1007 case glslang::EOpConstructDVec3:
1008 case glslang::EOpConstructDVec4:
1009 case glslang::EOpConstructBool:
1010 case glslang::EOpConstructBVec2:
1011 case glslang::EOpConstructBVec3:
1012 case glslang::EOpConstructBVec4:
1013 case glslang::EOpConstructInt:
1014 case glslang::EOpConstructIVec2:
1015 case glslang::EOpConstructIVec3:
1016 case glslang::EOpConstructIVec4:
1017 case glslang::EOpConstructUint:
1018 case glslang::EOpConstructUVec2:
1019 case glslang::EOpConstructUVec3:
1020 case glslang::EOpConstructUVec4:
1021 case glslang::EOpConstructStruct:
1022 {
1023 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001024 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001025 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1026 spv::Id constructed;
1027 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1028 std::vector<spv::Id> constituents;
1029 for (int c = 0; c < (int)arguments.size(); ++c)
1030 constituents.push_back(arguments[c]);
1031 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
1032 } else {
1033 if (isMatrix)
1034 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1035 else
1036 constructed = builder.createConstructor(precision, arguments, resultTypeId);
1037 }
1038
1039 builder.clearAccessChain();
1040 builder.setAccessChainRValue(constructed);
1041
1042 return false;
1043 }
1044
1045 // These six are component-wise compares with component-wise results.
1046 // Forward on to createBinaryOperation(), requesting a vector result.
1047 case glslang::EOpLessThan:
1048 case glslang::EOpGreaterThan:
1049 case glslang::EOpLessThanEqual:
1050 case glslang::EOpGreaterThanEqual:
1051 case glslang::EOpVectorEqual:
1052 case glslang::EOpVectorNotEqual:
1053 {
1054 // Map the operation to a binary
1055 binOp = node->getOp();
1056 reduceComparison = false;
1057 switch (node->getOp()) {
1058 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1059 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1060 default: binOp = node->getOp(); break;
1061 }
1062
1063 break;
1064 }
1065 case glslang::EOpMul:
1066 // compontent-wise matrix multiply
1067 binOp = glslang::EOpMul;
1068 break;
1069 case glslang::EOpOuterProduct:
1070 // two vectors multiplied to make a matrix
1071 binOp = glslang::EOpOuterProduct;
1072 break;
1073 case glslang::EOpDot:
1074 {
1075 // for scalar dot product, use multiply
1076 glslang::TIntermSequence& glslangOperands = node->getSequence();
1077 if (! glslangOperands[0]->getAsTyped()->isVector())
1078 binOp = glslang::EOpMul;
1079 break;
1080 }
1081 case glslang::EOpMod:
1082 // when an aggregate, this is the floating-point mod built-in function,
1083 // which can be emitted by the one in createBinaryOperation()
1084 binOp = glslang::EOpMod;
1085 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001086 case glslang::EOpEmitVertex:
1087 case glslang::EOpEndPrimitive:
1088 case glslang::EOpBarrier:
1089 case glslang::EOpMemoryBarrier:
1090 case glslang::EOpMemoryBarrierAtomicCounter:
1091 case glslang::EOpMemoryBarrierBuffer:
1092 case glslang::EOpMemoryBarrierImage:
1093 case glslang::EOpMemoryBarrierShared:
1094 case glslang::EOpGroupMemoryBarrier:
1095 noReturnValue = true;
1096 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1097 break;
1098
John Kessenich426394d2015-07-23 10:22:48 -06001099 case glslang::EOpAtomicAdd:
1100 case glslang::EOpAtomicMin:
1101 case glslang::EOpAtomicMax:
1102 case glslang::EOpAtomicAnd:
1103 case glslang::EOpAtomicOr:
1104 case glslang::EOpAtomicXor:
1105 case glslang::EOpAtomicExchange:
1106 case glslang::EOpAtomicCompSwap:
1107 atomic = true;
1108 break;
1109
John Kessenichfc51d282015-08-19 13:34:18 -06001110 case glslang::EOpAddCarry:
1111 case glslang::EOpSubBorrow:
1112 case glslang::EOpUMulExtended:
1113 case glslang::EOpIMulExtended:
1114 case glslang::EOpBitfieldExtract:
1115 case glslang::EOpBitfieldInsert:
1116 spv::MissingFunctionality("integer aggregate");
1117 break;
1118
1119 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001120 case glslang::EOpFrexp:
1121 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001122 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1123 break;
1124
John Kessenich140f3df2015-06-26 16:58:36 -06001125 default:
1126 break;
1127 }
1128
1129 //
1130 // See if it maps to a regular operation.
1131 //
John Kessenich140f3df2015-06-26 16:58:36 -06001132 if (binOp != glslang::EOpNull) {
1133 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1134 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1135 assert(left && right);
1136
1137 builder.clearAccessChain();
1138 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001139 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001140
1141 builder.clearAccessChain();
1142 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001143 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001144
1145 result = createBinaryOperation(binOp, precision,
1146 convertGlslangToSpvType(node->getType()), leftId, rightId,
1147 left->getType().getBasicType(), reduceComparison);
1148
1149 // code above should only make binOp that exists in createBinaryOperation
1150 if (result == 0)
1151 spv::MissingFunctionality("createBinaryOperation for aggregate");
1152
1153 builder.clearAccessChain();
1154 builder.setAccessChainRValue(result);
1155
1156 return false;
1157 }
1158
John Kessenich426394d2015-07-23 10:22:48 -06001159 //
1160 // Create the list of operands.
1161 //
John Kessenich140f3df2015-06-26 16:58:36 -06001162 glslang::TIntermSequence& glslangOperands = node->getSequence();
1163 std::vector<spv::Id> operands;
1164 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1165 builder.clearAccessChain();
1166 glslangOperands[arg]->traverse(this);
1167
1168 // special case l-value operands; there are just a few
1169 bool lvalue = false;
1170 switch (node->getOp()) {
1171 //case glslang::EOpFrexp:
1172 case glslang::EOpModf:
1173 if (arg == 1)
1174 lvalue = true;
1175 break;
Rex Xud4782c12015-09-06 16:30:11 +08001176 case glslang::EOpAtomicAdd:
1177 case glslang::EOpAtomicMin:
1178 case glslang::EOpAtomicMax:
1179 case glslang::EOpAtomicAnd:
1180 case glslang::EOpAtomicOr:
1181 case glslang::EOpAtomicXor:
1182 case glslang::EOpAtomicExchange:
1183 case glslang::EOpAtomicCompSwap:
1184 if (arg == 0)
1185 lvalue = true;
1186 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001187 //case glslang::EOpUAddCarry:
1188 //case glslang::EOpUSubBorrow:
1189 //case glslang::EOpUMulExtended:
1190 default:
1191 break;
1192 }
1193 if (lvalue)
1194 operands.push_back(builder.accessChainGetLValue());
1195 else
John Kessenichfa668da2015-09-13 14:46:30 -06001196 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001197 }
John Kessenich426394d2015-07-23 10:22:48 -06001198
1199 if (atomic) {
1200 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001201 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001202 } else {
1203 // Pass through to generic operations.
1204 switch (glslangOperands.size()) {
1205 case 0:
1206 result = createNoArgOperation(node->getOp());
1207 break;
1208 case 1:
Rex Xu04db3f52015-09-16 11:44:02 +08001209 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001210 break;
1211 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001212 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001213 break;
1214 }
John Kessenich140f3df2015-06-26 16:58:36 -06001215 }
1216
1217 if (noReturnValue)
1218 return false;
1219
1220 if (! result) {
1221 spv::MissingFunctionality("glslang aggregate");
1222 return true;
1223 } else {
1224 builder.clearAccessChain();
1225 builder.setAccessChainRValue(result);
1226 return false;
1227 }
1228}
1229
1230bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1231{
1232 // This path handles both if-then-else and ?:
1233 // The if-then-else has a node type of void, while
1234 // ?: has a non-void node type
1235 spv::Id result = 0;
1236 if (node->getBasicType() != glslang::EbtVoid) {
1237 // don't handle this as just on-the-fly temporaries, because there will be two names
1238 // and better to leave SSA to later passes
1239 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1240 }
1241
1242 // emit the condition before doing anything with selection
1243 node->getCondition()->traverse(this);
1244
1245 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001246 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001247
1248 if (node->getTrueBlock()) {
1249 // emit the "then" statement
1250 node->getTrueBlock()->traverse(this);
1251 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001252 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001253 }
1254
1255 if (node->getFalseBlock()) {
1256 ifBuilder.makeBeginElse();
1257 // emit the "else" statement
1258 node->getFalseBlock()->traverse(this);
1259 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001260 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001261 }
1262
1263 ifBuilder.makeEndIf();
1264
1265 if (result) {
1266 // GLSL only has r-values as the result of a :?, but
1267 // if we have an l-value, that can be more efficient if it will
1268 // become the base of a complex r-value expression, because the
1269 // next layer copies r-values into memory to use the access-chain mechanism
1270 builder.clearAccessChain();
1271 builder.setAccessChainLValue(result);
1272 }
1273
1274 return false;
1275}
1276
1277bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1278{
1279 // emit and get the condition before doing anything with switch
1280 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001281 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001282
1283 // browse the children to sort out code segments
1284 int defaultSegment = -1;
1285 std::vector<TIntermNode*> codeSegments;
1286 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1287 std::vector<int> caseValues;
1288 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1289 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1290 TIntermNode* child = *c;
1291 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001292 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001293 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001294 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001295 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1296 } else
1297 codeSegments.push_back(child);
1298 }
1299
1300 // handle the case where the last code segment is missing, due to no code
1301 // statements between the last case and the end of the switch statement
1302 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1303 (int)codeSegments.size() == defaultSegment)
1304 codeSegments.push_back(nullptr);
1305
1306 // make the switch statement
1307 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001308 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001309
1310 // emit all the code in the segments
1311 breakForLoop.push(false);
1312 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1313 builder.nextSwitchSegment(segmentBlocks, s);
1314 if (codeSegments[s])
1315 codeSegments[s]->traverse(this);
1316 else
1317 builder.addSwitchBreak();
1318 }
1319 breakForLoop.pop();
1320
1321 builder.endSwitch(segmentBlocks);
1322
1323 return false;
1324}
1325
1326void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1327{
1328 int nextConst = 0;
1329 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1330
1331 builder.clearAccessChain();
1332 builder.setAccessChainRValue(constant);
1333}
1334
1335bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1336{
1337 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1338 loopTerminal.push(node->getTerminal());
1339
David Netoc22f37c2015-07-15 16:21:26 -04001340 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001341
1342 if (node->getTest()) {
1343 node->getTest()->traverse(this);
1344 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001345 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001346 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001347 } else {
1348 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001349 }
1350
David Netoc22f37c2015-07-15 16:21:26 -04001351 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001352 breakForLoop.push(true);
1353 node->getBody()->traverse(this);
1354 breakForLoop.pop();
1355 }
1356
1357 if (loopTerminal.top())
1358 loopTerminal.top()->traverse(this);
1359
1360 builder.closeLoop();
1361
1362 loopTerminal.pop();
1363
1364 return false;
1365}
1366
1367bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1368{
1369 if (node->getExpression())
1370 node->getExpression()->traverse(this);
1371
1372 switch (node->getFlowOp()) {
1373 case glslang::EOpKill:
1374 builder.makeDiscard();
1375 break;
1376 case glslang::EOpBreak:
1377 if (breakForLoop.top())
1378 builder.createLoopExit();
1379 else
1380 builder.addSwitchBreak();
1381 break;
1382 case glslang::EOpContinue:
1383 if (loopTerminal.top())
1384 loopTerminal.top()->traverse(this);
1385 builder.createLoopContinue();
1386 break;
1387 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001388 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001389 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001390 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001391 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001392
1393 builder.clearAccessChain();
1394 break;
1395
1396 default:
1397 spv::MissingFunctionality("branch type");
1398 break;
1399 }
1400
1401 return false;
1402}
1403
1404spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1405{
1406 // First, steer off constants, which are not SPIR-V variables, but
1407 // can still have a mapping to a SPIR-V Id.
1408 if (node->getQualifier().storage == glslang::EvqConst) {
1409 int nextConst = 0;
1410 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1411 }
1412
1413 // Now, handle actual variables
1414 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1415 spv::Id spvType = convertGlslangToSpvType(node->getType());
1416
1417 const char* name = node->getName().c_str();
1418 if (glslang::IsAnonymous(name))
1419 name = "";
1420
1421 return builder.createVariable(storageClass, spvType, name);
1422}
1423
1424// Return type Id of the sampled type.
1425spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1426{
1427 switch (sampler.type) {
1428 case glslang::EbtFloat: return builder.makeFloatType(32);
1429 case glslang::EbtInt: return builder.makeIntType(32);
1430 case glslang::EbtUint: return builder.makeUintType(32);
1431 default:
1432 spv::MissingFunctionality("sampled type");
1433 return builder.makeFloatType(32);
1434 }
1435}
1436
John Kessenich31ed4832015-09-09 17:51:38 -06001437// Convert from a glslang type to an SPV type, by calling into
1438// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001439spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1440{
John Kessenich31ed4832015-09-09 17:51:38 -06001441 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1442}
1443
1444// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1445// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1446spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1447{
John Kessenich140f3df2015-06-26 16:58:36 -06001448 spv::Id spvType = 0;
1449
1450 switch (type.getBasicType()) {
1451 case glslang::EbtVoid:
1452 spvType = builder.makeVoidType();
1453 if (type.isArray())
1454 spv::MissingFunctionality("array of void");
1455 break;
1456 case glslang::EbtFloat:
1457 spvType = builder.makeFloatType(32);
1458 break;
1459 case glslang::EbtDouble:
1460 spvType = builder.makeFloatType(64);
1461 break;
1462 case glslang::EbtBool:
1463 spvType = builder.makeBoolType();
1464 break;
1465 case glslang::EbtInt:
1466 spvType = builder.makeIntType(32);
1467 break;
1468 case glslang::EbtUint:
1469 spvType = builder.makeUintType(32);
1470 break;
John Kessenich426394d2015-07-23 10:22:48 -06001471 case glslang::EbtAtomicUint:
1472 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1473 spvType = builder.makeUintType(32);
1474 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001475 case glslang::EbtSampler:
1476 {
1477 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001478 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
Rex Xufc618912015-09-09 16:42:49 +08001479 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich5e4b1242015-08-06 22:53:06 -06001480 // OpenGL "textures" need to be combined with a sampler
1481 if (! sampler.image)
1482 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001483 }
1484 break;
1485 case glslang::EbtStruct:
1486 case glslang::EbtBlock:
1487 {
1488 // If we've seen this struct type, return it
1489 const glslang::TTypeList* glslangStruct = type.getStruct();
1490 std::vector<spv::Id> structFields;
1491 spvType = structMap[glslangStruct];
1492 if (spvType)
1493 break;
1494
1495 // else, we haven't seen it...
1496
1497 // Create a vector of struct types for SPIR-V to consume
1498 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1499 if (type.getBasicType() == glslang::EbtBlock)
1500 memberRemapper[glslangStruct].resize(glslangStruct->size());
1501 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1502 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1503 if (glslangType.hiddenMember()) {
1504 ++memberDelta;
1505 if (type.getBasicType() == glslang::EbtBlock)
1506 memberRemapper[glslangStruct][i] = -1;
1507 } else {
1508 if (type.getBasicType() == glslang::EbtBlock)
1509 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001510 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001511 }
1512 }
1513
1514 // Make the SPIR-V type
1515 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1516 structMap[glslangStruct] = spvType;
1517
1518 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001519 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001520 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1521 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1522 int member = i;
1523 if (type.getBasicType() == glslang::EbtBlock)
1524 member = memberRemapper[glslangStruct][i];
1525 // using -1 above to indicate a hidden member
1526 if (member >= 0) {
1527 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1528 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1529 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1530 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1531 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1532 if (glslangType.getQualifier().hasLocation())
1533 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1534 if (glslangType.getQualifier().hasComponent())
1535 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1536 if (glslangType.getQualifier().hasXfbOffset())
1537 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001538 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001539 // figure out what to do with offset, which is accumulating
1540 int nextOffset;
1541 updateMemberOffset(type, glslangType, offset, nextOffset);
1542 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001543 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001544 offset = nextOffset;
1545 }
John Kessenich140f3df2015-06-26 16:58:36 -06001546
John Kessenich31ed4832015-09-09 17:51:38 -06001547 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001548 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1549 }
1550
John Kessenich140f3df2015-06-26 16:58:36 -06001551 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001552 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1553 if (builtIn != spv::BadValue)
1554 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001555 }
1556 }
1557
1558 // Decorate the structure
1559 addDecoration(spvType, TranslateLayoutDecoration(type));
1560 addDecoration(spvType, TranslateBlockDecoration(type));
1561 if (type.getQualifier().hasStream())
1562 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1563 if (glslangIntermediate->getXfbMode()) {
1564 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001565 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001566 if (type.getQualifier().hasXfbBuffer())
1567 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1568 }
1569 }
1570 break;
1571 default:
1572 spv::MissingFunctionality("basic type");
1573 break;
1574 }
1575
1576 if (type.isMatrix())
1577 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1578 else {
1579 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1580 if (type.getVectorSize() > 1)
1581 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1582 }
1583
1584 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001585 // Do all but the outer dimension
1586 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1587 assert(type.getArraySizes()->getDimSize(dim) > 0);
1588 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1589 }
John Kessenich31ed4832015-09-09 17:51:38 -06001590
John Kessenichc9a80832015-09-12 12:17:44 -06001591 // Do the outer dimension, which might not be known for a runtime-sized array
1592 if (type.isRuntimeSizedArray()) {
1593 spvType = builder.makeRuntimeArray(spvType);
1594 } else {
1595 assert(type.getOuterArraySize() > 0);
1596 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1597 }
1598
1599 // TODO: layout still needs to be done hierarchically for arrays of arrays, which
1600 // may still require additional "link time" support from the front-end
1601 // for arrays of arrays
John Kessenich31ed4832015-09-09 17:51:38 -06001602 if (explicitLayout)
1603 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001604 }
1605
1606 return spvType;
1607}
1608
John Kessenich31ed4832015-09-09 17:51:38 -06001609bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1610{
1611 return type.getBasicType() == glslang::EbtBlock &&
1612 type.getQualifier().layoutPacking != glslang::ElpShared &&
1613 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1614 (type.getQualifier().storage == glslang::EvqUniform ||
1615 type.getQualifier().storage == glslang::EvqBuffer);
1616}
1617
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001618// Given an array type, returns the integer stride required for that array
1619int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1620{
1621 glslang::TType derefType(arrayType, 0);
1622 int size;
1623 glslangIntermediate->getBaseAlignment(derefType, size, true);
1624 return size;
1625}
1626
1627// Given a matrix type, returns the integer stride required for that matrix
1628// when used as a member of an interface block
1629int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1630{
1631 int size;
1632 return glslangIntermediate->getBaseAlignment(matrixType, size, true);
1633}
1634
John Kessenich5e4b1242015-08-06 22:53:06 -06001635// Given a member type of a struct, realign the current offset for it, and compute
1636// the next (not yet aligned) offset for the next member, which will get aligned
1637// on the next call.
1638// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1639// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1640// -1 means a non-forced member offset (no decoration needed).
1641void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1642{
1643 // this will get a positive value when deemed necessary
1644 nextOffset = -1;
1645
1646 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1647 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1648
1649 // override anything in currentOffset with user-set offset
1650 if (memberType.getQualifier().hasOffset())
1651 currentOffset = memberType.getQualifier().layoutOffset;
1652
1653 // It could be that current linker usage in glslang updated all the layoutOffset,
1654 // in which case the following code does not matter. But, that's not quite right
1655 // once cross-compilation unit GLSL validation is done, as the original user
1656 // settings are needed in layoutOffset, and then the following will come into play.
1657
1658 if (! forceOffset) {
1659 if (! memberType.getQualifier().hasOffset())
1660 currentOffset = -1;
1661
1662 return;
1663 }
1664
1665 // Getting this far means we are forcing offsets
1666 if (currentOffset < 0)
1667 currentOffset = 0;
1668
1669 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1670 // but possibly not yet correctly aligned.
1671
1672 int memberSize;
1673 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1674 glslang::RoundToPow2(currentOffset, memberAlignment);
1675 nextOffset = currentOffset + memberSize;
1676}
1677
John Kessenich140f3df2015-06-26 16:58:36 -06001678bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1679{
1680 return node->getName() == "main(";
1681}
1682
1683// Make all the functions, skeletally, without actually visiting their bodies.
1684void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1685{
1686 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1687 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1688 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1689 continue;
1690
1691 // We're on a user function. Set up the basic interface for the function now,
1692 // so that it's available to call.
1693 // Translating the body will happen later.
1694 //
1695 // Typically (except for a "const in" parameter), an address will be passed to the
1696 // function. What it is an address of varies:
1697 //
1698 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1699 // so that write needs to be to a copy, hence the address of a copy works.
1700 //
1701 // - "const in" parameters can just be the r-value, as no writes need occur.
1702 //
1703 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1704 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1705
1706 std::vector<spv::Id> paramTypes;
1707 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1708
1709 for (int p = 0; p < (int)parameters.size(); ++p) {
1710 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1711 spv::Id typeId = convertGlslangToSpvType(paramType);
1712 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1713 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1714 else
1715 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1716 paramTypes.push_back(typeId);
1717 }
1718
1719 spv::Block* functionBlock;
1720 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1721 paramTypes, &functionBlock);
1722
1723 // Track function to emit/call later
1724 functionMap[glslFunction->getName().c_str()] = function;
1725
1726 // Set the parameter id's
1727 for (int p = 0; p < (int)parameters.size(); ++p) {
1728 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1729 // give a name too
1730 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1731 }
1732 }
1733}
1734
1735// Process all the initializers, while skipping the functions and link objects
1736void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1737{
1738 builder.setBuildPoint(shaderEntry->getLastBlock());
1739 for (int i = 0; i < (int)initializers.size(); ++i) {
1740 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1741 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1742
1743 // We're on a top-level node that's not a function. Treat as an initializer, whose
1744 // code goes into the beginning of main.
1745 initializer->traverse(this);
1746 }
1747 }
1748}
1749
1750// Process all the functions, while skipping initializers.
1751void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1752{
1753 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1754 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1755 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1756 node->traverse(this);
1757 }
1758}
1759
1760void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1761{
1762 // SPIR-V functions should already be in the functionMap from the prepass
1763 // that called makeFunctions().
1764 spv::Function* function = functionMap[node->getName().c_str()];
1765 spv::Block* functionBlock = function->getEntryBlock();
1766 builder.setBuildPoint(functionBlock);
1767}
1768
Rex Xu04db3f52015-09-16 11:44:02 +08001769void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001770{
Rex Xufc618912015-09-09 16:42:49 +08001771 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001772 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1773 builder.clearAccessChain();
1774 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001775
1776 // Special case l-value operands
1777 bool lvalue = false;
1778 switch (node.getOp()) {
1779 case glslang::EOpImageAtomicAdd:
1780 case glslang::EOpImageAtomicMin:
1781 case glslang::EOpImageAtomicMax:
1782 case glslang::EOpImageAtomicAnd:
1783 case glslang::EOpImageAtomicOr:
1784 case glslang::EOpImageAtomicXor:
1785 case glslang::EOpImageAtomicExchange:
1786 case glslang::EOpImageAtomicCompSwap:
1787 if (i == 0)
1788 lvalue = true;
1789 break;
1790 default:
1791 break;
1792 }
1793
Rex Xu6b86d492015-09-16 17:48:22 +08001794 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001795 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001796 else
Rex Xu30f92582015-09-14 10:38:56 +08001797 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001798 }
1799}
1800
John Kessenichfc51d282015-08-19 13:34:18 -06001801void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001802{
John Kessenichfc51d282015-08-19 13:34:18 -06001803 builder.clearAccessChain();
1804 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001805 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001806}
John Kessenich140f3df2015-06-26 16:58:36 -06001807
John Kessenichfc51d282015-08-19 13:34:18 -06001808spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1809{
Rex Xufc618912015-09-09 16:42:49 +08001810 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001811 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001812 }
1813
John Kessenichfc51d282015-08-19 13:34:18 -06001814 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001815 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1816 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1817 std::vector<spv::Id> arguments;
1818 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001819 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001820 else
1821 translateArguments(*node->getAsUnaryNode(), arguments);
1822 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1823
1824 spv::Builder::TextureParameters params = { };
1825 params.sampler = arguments[0];
1826
Rex Xu04db3f52015-09-16 11:44:02 +08001827 glslang::TCrackedTextureOp cracked;
1828 node->crackTexture(sampler, cracked);
1829
John Kessenichfc51d282015-08-19 13:34:18 -06001830 // Check for queries
1831 if (cracked.query) {
1832 switch (node->getOp()) {
1833 case glslang::EOpImageQuerySize:
1834 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001835 if (arguments.size() > 1) {
1836 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001837 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001838 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001839 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001840 case glslang::EOpImageQuerySamples:
1841 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001842 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001843 case glslang::EOpTextureQueryLod:
1844 params.coords = arguments[1];
1845 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1846 case glslang::EOpTextureQueryLevels:
1847 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1848 default:
1849 assert(0);
1850 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001851 }
John Kessenich140f3df2015-06-26 16:58:36 -06001852 }
1853
Rex Xufc618912015-09-09 16:42:49 +08001854 // Check for image functions other than queries
1855 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001856 std::vector<spv::Id> operands;
1857 auto opIt = arguments.begin();
1858 operands.push_back(*(opIt++));
1859 operands.push_back(*(opIt++));
1860 if (node->getOp() == glslang::EOpImageStore)
Rex Xu6b86d492015-09-16 17:48:22 +08001861 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001862 // TODO: add 'sample' operand
1863 if (node->getOp() == glslang::EOpImageLoad) {
1864 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1865 } else if (node->getOp() == glslang::EOpImageStore) {
1866 builder.createNoResultOp(spv::OpImageWrite, operands);
1867 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001868 } else {
1869 // Process image atomic operations
1870
1871 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1872 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001873 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001874
Rex Xufc618912015-09-09 16:42:49 +08001875 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001876 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001877
1878 std::vector<spv::Id> operands;
1879 operands.push_back(pointer);
1880 for (; opIt != arguments.end(); ++opIt)
1881 operands.push_back(*opIt);
1882
Rex Xu04db3f52015-09-16 11:44:02 +08001883 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001884 }
1885 }
1886
1887 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001888 if (cracked.gather)
1889 spv::MissingFunctionality("texture gather");
1890
1891 // check for bias argument
1892 bool bias = false;
1893 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1894 int nonBiasArgCount = 2;
1895 if (cracked.offset)
1896 ++nonBiasArgCount;
1897 if (cracked.grad)
1898 nonBiasArgCount += 2;
1899
1900 if ((int)arguments.size() > nonBiasArgCount)
1901 bias = true;
1902 }
1903
1904 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1905
1906 // set the rest of the arguments
1907 params.coords = arguments[1];
1908 int extraArgs = 0;
1909 if (cubeCompare)
1910 params.Dref = arguments[2];
1911 else if (sampler.shadow) {
1912 std::vector<spv::Id> indexes;
1913 int comp;
1914 if (cracked.proj)
1915 comp = 3;
1916 else
1917 comp = builder.getNumComponents(params.coords) - 1;
1918 indexes.push_back(comp);
1919 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1920 }
1921 if (cracked.lod) {
1922 params.lod = arguments[2];
1923 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08001924 } else if (sampler.ms) {
1925 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08001926 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001927 }
1928 if (cracked.grad) {
1929 params.gradX = arguments[2 + extraArgs];
1930 params.gradY = arguments[3 + extraArgs];
1931 extraArgs += 2;
1932 }
1933 //if (gather && compare) {
1934 // params.compare = arguments[2 + extraArgs];
1935 // ++extraArgs;
1936 //}
1937 if (cracked.offset || cracked.offsets) {
1938 params.offset = arguments[2 + extraArgs];
1939 ++extraArgs;
1940 }
1941 if (bias) {
1942 params.bias = arguments[2 + extraArgs];
1943 ++extraArgs;
1944 }
1945
Jason Ekstrand18b9fbd2015-09-05 14:14:48 -07001946 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001947}
1948
1949spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1950{
1951 // Grab the function's pointer from the previously created function
1952 spv::Function* function = functionMap[node->getName().c_str()];
1953 if (! function)
1954 return 0;
1955
1956 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1957 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1958
1959 // See comments in makeFunctions() for details about the semantics for parameter passing.
1960 //
1961 // These imply we need a four step process:
1962 // 1. Evaluate the arguments
1963 // 2. Allocate and make copies of in, out, and inout arguments
1964 // 3. Make the call
1965 // 4. Copy back the results
1966
1967 // 1. Evaluate the arguments
1968 std::vector<spv::Builder::AccessChain> lValues;
1969 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06001970 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06001971 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1972 // build l-value
1973 builder.clearAccessChain();
1974 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001975 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001976 // keep outputs as l-values, evaluate input-only as r-values
1977 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1978 // save l-value
1979 lValues.push_back(builder.getAccessChain());
1980 } else {
1981 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06001982 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06001983 }
1984 }
1985
1986 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1987 // copy the original into that space.
1988 //
1989 // Also, build up the list of actual arguments to pass in for the call
1990 int lValueCount = 0;
1991 int rValueCount = 0;
1992 std::vector<spv::Id> spvArgs;
1993 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1994 spv::Id arg;
1995 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1996 // need space to hold the copy
1997 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1998 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1999 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2000 // need to copy the input into output space
2001 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002002 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002003 builder.createStore(copy, arg);
2004 }
2005 ++lValueCount;
2006 } else {
2007 arg = rValues[rValueCount];
2008 ++rValueCount;
2009 }
2010 spvArgs.push_back(arg);
2011 }
2012
2013 // 3. Make the call.
2014 spv::Id result = builder.createFunctionCall(function, spvArgs);
2015
2016 // 4. Copy back out an "out" arguments.
2017 lValueCount = 0;
2018 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2019 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2020 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2021 spv::Id copy = builder.createLoad(spvArgs[a]);
2022 builder.setAccessChain(lValues[lValueCount]);
2023 builder.accessChainStore(copy);
2024 }
2025 ++lValueCount;
2026 }
2027 }
2028
2029 return result;
2030}
2031
2032// Translate AST operation to SPV operation, already having SPV-based operands/types.
2033spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2034 spv::Id typeId, spv::Id left, spv::Id right,
2035 glslang::TBasicType typeProxy, bool reduceComparison)
2036{
2037 bool isUnsigned = typeProxy == glslang::EbtUint;
2038 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2039
2040 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002041 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002042 bool comparison = false;
2043
2044 switch (op) {
2045 case glslang::EOpAdd:
2046 case glslang::EOpAddAssign:
2047 if (isFloat)
2048 binOp = spv::OpFAdd;
2049 else
2050 binOp = spv::OpIAdd;
2051 break;
2052 case glslang::EOpSub:
2053 case glslang::EOpSubAssign:
2054 if (isFloat)
2055 binOp = spv::OpFSub;
2056 else
2057 binOp = spv::OpISub;
2058 break;
2059 case glslang::EOpMul:
2060 case glslang::EOpMulAssign:
2061 if (isFloat)
2062 binOp = spv::OpFMul;
2063 else
2064 binOp = spv::OpIMul;
2065 break;
2066 case glslang::EOpVectorTimesScalar:
2067 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002068 if (isFloat) {
2069 if (builder.isVector(right))
2070 std::swap(left, right);
2071 assert(builder.isScalar(right));
2072 needMatchingVectors = false;
2073 binOp = spv::OpVectorTimesScalar;
2074 } else
2075 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002076 break;
2077 case glslang::EOpVectorTimesMatrix:
2078 case glslang::EOpVectorTimesMatrixAssign:
2079 assert(builder.isVector(left));
2080 assert(builder.isMatrix(right));
2081 binOp = spv::OpVectorTimesMatrix;
2082 break;
2083 case glslang::EOpMatrixTimesVector:
2084 assert(builder.isMatrix(left));
2085 assert(builder.isVector(right));
2086 binOp = spv::OpMatrixTimesVector;
2087 break;
2088 case glslang::EOpMatrixTimesScalar:
2089 case glslang::EOpMatrixTimesScalarAssign:
2090 if (builder.isMatrix(right))
2091 std::swap(left, right);
2092 assert(builder.isScalar(right));
2093 binOp = spv::OpMatrixTimesScalar;
2094 break;
2095 case glslang::EOpMatrixTimesMatrix:
2096 case glslang::EOpMatrixTimesMatrixAssign:
2097 assert(builder.isMatrix(left));
2098 assert(builder.isMatrix(right));
2099 binOp = spv::OpMatrixTimesMatrix;
2100 break;
2101 case glslang::EOpOuterProduct:
2102 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002103 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002104 break;
2105
2106 case glslang::EOpDiv:
2107 case glslang::EOpDivAssign:
2108 if (isFloat)
2109 binOp = spv::OpFDiv;
2110 else if (isUnsigned)
2111 binOp = spv::OpUDiv;
2112 else
2113 binOp = spv::OpSDiv;
2114 break;
2115 case glslang::EOpMod:
2116 case glslang::EOpModAssign:
2117 if (isFloat)
2118 binOp = spv::OpFMod;
2119 else if (isUnsigned)
2120 binOp = spv::OpUMod;
2121 else
2122 binOp = spv::OpSMod;
2123 break;
2124 case glslang::EOpRightShift:
2125 case glslang::EOpRightShiftAssign:
2126 if (isUnsigned)
2127 binOp = spv::OpShiftRightLogical;
2128 else
2129 binOp = spv::OpShiftRightArithmetic;
2130 break;
2131 case glslang::EOpLeftShift:
2132 case glslang::EOpLeftShiftAssign:
2133 binOp = spv::OpShiftLeftLogical;
2134 break;
2135 case glslang::EOpAnd:
2136 case glslang::EOpAndAssign:
2137 binOp = spv::OpBitwiseAnd;
2138 break;
2139 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002140 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002141 binOp = spv::OpLogicalAnd;
2142 break;
2143 case glslang::EOpInclusiveOr:
2144 case glslang::EOpInclusiveOrAssign:
2145 binOp = spv::OpBitwiseOr;
2146 break;
2147 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002148 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002149 binOp = spv::OpLogicalOr;
2150 break;
2151 case glslang::EOpExclusiveOr:
2152 case glslang::EOpExclusiveOrAssign:
2153 binOp = spv::OpBitwiseXor;
2154 break;
2155 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002156 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002157 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002158 break;
2159
2160 case glslang::EOpLessThan:
2161 case glslang::EOpGreaterThan:
2162 case glslang::EOpLessThanEqual:
2163 case glslang::EOpGreaterThanEqual:
2164 case glslang::EOpEqual:
2165 case glslang::EOpNotEqual:
2166 case glslang::EOpVectorEqual:
2167 case glslang::EOpVectorNotEqual:
2168 comparison = true;
2169 break;
2170 default:
2171 break;
2172 }
2173
2174 if (binOp != spv::OpNop) {
2175 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2176 switch (binOp) {
2177 case spv::OpMatrixTimesScalar:
2178 case spv::OpVectorTimesMatrix:
2179 case spv::OpMatrixTimesVector:
2180 case spv::OpMatrixTimesMatrix:
2181 break;
2182 case spv::OpFDiv:
2183 // turn it into a multiply...
2184 assert(builder.isMatrix(left) && builder.isScalar(right));
2185 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2186 binOp = spv::OpFMul;
2187 break;
2188 default:
2189 spv::MissingFunctionality("binary operation on matrix");
2190 break;
2191 }
2192
2193 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2194 builder.setPrecision(id, precision);
2195
2196 return id;
2197 }
2198
2199 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002200 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002201 builder.promoteScalar(precision, left, right);
2202
2203 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2204 builder.setPrecision(id, precision);
2205
2206 return id;
2207 }
2208
2209 if (! comparison)
2210 return 0;
2211
2212 // Comparison instructions
2213
2214 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2215 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2216
2217 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2218 }
2219
2220 switch (op) {
2221 case glslang::EOpLessThan:
2222 if (isFloat)
2223 binOp = spv::OpFOrdLessThan;
2224 else if (isUnsigned)
2225 binOp = spv::OpULessThan;
2226 else
2227 binOp = spv::OpSLessThan;
2228 break;
2229 case glslang::EOpGreaterThan:
2230 if (isFloat)
2231 binOp = spv::OpFOrdGreaterThan;
2232 else if (isUnsigned)
2233 binOp = spv::OpUGreaterThan;
2234 else
2235 binOp = spv::OpSGreaterThan;
2236 break;
2237 case glslang::EOpLessThanEqual:
2238 if (isFloat)
2239 binOp = spv::OpFOrdLessThanEqual;
2240 else if (isUnsigned)
2241 binOp = spv::OpULessThanEqual;
2242 else
2243 binOp = spv::OpSLessThanEqual;
2244 break;
2245 case glslang::EOpGreaterThanEqual:
2246 if (isFloat)
2247 binOp = spv::OpFOrdGreaterThanEqual;
2248 else if (isUnsigned)
2249 binOp = spv::OpUGreaterThanEqual;
2250 else
2251 binOp = spv::OpSGreaterThanEqual;
2252 break;
2253 case glslang::EOpEqual:
2254 case glslang::EOpVectorEqual:
2255 if (isFloat)
2256 binOp = spv::OpFOrdEqual;
2257 else
2258 binOp = spv::OpIEqual;
2259 break;
2260 case glslang::EOpNotEqual:
2261 case glslang::EOpVectorNotEqual:
2262 if (isFloat)
2263 binOp = spv::OpFOrdNotEqual;
2264 else
2265 binOp = spv::OpINotEqual;
2266 break;
2267 default:
2268 break;
2269 }
2270
2271 if (binOp != spv::OpNop) {
2272 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2273 builder.setPrecision(id, precision);
2274
2275 return id;
2276 }
2277
2278 return 0;
2279}
2280
Rex Xu04db3f52015-09-16 11:44:02 +08002281spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06002282{
2283 spv::Op unaryOp = spv::OpNop;
2284 int libCall = -1;
Rex Xu04db3f52015-09-16 11:44:02 +08002285 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002286
2287 switch (op) {
2288 case glslang::EOpNegative:
2289 if (isFloat)
2290 unaryOp = spv::OpFNegate;
2291 else
2292 unaryOp = spv::OpSNegate;
2293 break;
2294
2295 case glslang::EOpLogicalNot:
2296 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002297 unaryOp = spv::OpLogicalNot;
2298 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002299 case glslang::EOpBitwiseNot:
2300 unaryOp = spv::OpNot;
2301 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002302
John Kessenich140f3df2015-06-26 16:58:36 -06002303 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002304 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002305 break;
2306 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002307 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002308 break;
2309 case glslang::EOpTranspose:
2310 unaryOp = spv::OpTranspose;
2311 break;
2312
2313 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002314 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002315 break;
2316 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002317 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002318 break;
2319 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002320 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002321 break;
2322 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002323 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002324 break;
2325 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002326 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002327 break;
2328 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002329 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002330 break;
2331 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002332 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002333 break;
2334 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002335 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002336 break;
2337
2338 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002339 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002340 break;
2341 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002342 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002343 break;
2344 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002345 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002346 break;
2347 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002348 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002349 break;
2350 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002351 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002352 break;
2353 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002354 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002355 break;
2356
2357 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002358 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002359 break;
2360 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002361 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002362 break;
2363
2364 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002365 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002366 break;
2367 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002368 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002369 break;
2370 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002371 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002372 break;
2373 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002374 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002375 break;
2376 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002377 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002378 break;
2379 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002380 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002381 break;
2382
2383 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002384 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002385 break;
2386 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002387 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002388 break;
2389 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002390 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002391 break;
2392 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002393 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002394 break;
2395 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002396 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002397 break;
2398 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002399 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002400 break;
2401
2402 case glslang::EOpIsNan:
2403 unaryOp = spv::OpIsNan;
2404 break;
2405 case glslang::EOpIsInf:
2406 unaryOp = spv::OpIsInf;
2407 break;
2408
John Kessenich140f3df2015-06-26 16:58:36 -06002409 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002410 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002411 break;
2412 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002413 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002414 break;
2415 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002416 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002417 break;
2418 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002419 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002420 break;
2421 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002422 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002423 break;
2424 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002425 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002426 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002427 case glslang::EOpPackSnorm4x8:
2428 libCall = spv::GLSLstd450PackSnorm4x8;
2429 break;
2430 case glslang::EOpUnpackSnorm4x8:
2431 libCall = spv::GLSLstd450UnpackSnorm4x8;
2432 break;
2433 case glslang::EOpPackUnorm4x8:
2434 libCall = spv::GLSLstd450PackUnorm4x8;
2435 break;
2436 case glslang::EOpUnpackUnorm4x8:
2437 libCall = spv::GLSLstd450UnpackUnorm4x8;
2438 break;
2439 case glslang::EOpPackDouble2x32:
2440 libCall = spv::GLSLstd450PackDouble2x32;
2441 break;
2442 case glslang::EOpUnpackDouble2x32:
2443 libCall = spv::GLSLstd450UnpackDouble2x32;
2444 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002445
2446 case glslang::EOpDPdx:
2447 unaryOp = spv::OpDPdx;
2448 break;
2449 case glslang::EOpDPdy:
2450 unaryOp = spv::OpDPdy;
2451 break;
2452 case glslang::EOpFwidth:
2453 unaryOp = spv::OpFwidth;
2454 break;
2455 case glslang::EOpDPdxFine:
2456 unaryOp = spv::OpDPdxFine;
2457 break;
2458 case glslang::EOpDPdyFine:
2459 unaryOp = spv::OpDPdyFine;
2460 break;
2461 case glslang::EOpFwidthFine:
2462 unaryOp = spv::OpFwidthFine;
2463 break;
2464 case glslang::EOpDPdxCoarse:
2465 unaryOp = spv::OpDPdxCoarse;
2466 break;
2467 case glslang::EOpDPdyCoarse:
2468 unaryOp = spv::OpDPdyCoarse;
2469 break;
2470 case glslang::EOpFwidthCoarse:
2471 unaryOp = spv::OpFwidthCoarse;
2472 break;
2473
2474 case glslang::EOpAny:
2475 unaryOp = spv::OpAny;
2476 break;
2477 case glslang::EOpAll:
2478 unaryOp = spv::OpAll;
2479 break;
2480
2481 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002482 if (isFloat)
2483 libCall = spv::GLSLstd450FAbs;
2484 else
2485 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002486 break;
2487 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002488 if (isFloat)
2489 libCall = spv::GLSLstd450FSign;
2490 else
2491 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002492 break;
2493
John Kessenichfc51d282015-08-19 13:34:18 -06002494 case glslang::EOpAtomicCounterIncrement:
2495 case glslang::EOpAtomicCounterDecrement:
2496 case glslang::EOpAtomicCounter:
2497 {
2498 // Handle all of the atomics in one place, in createAtomicOperation()
2499 std::vector<spv::Id> operands;
2500 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002501 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002502 }
2503
2504 case glslang::EOpImageLoad:
2505 unaryOp = spv::OpImageRead;
2506 break;
2507
2508 case glslang::EOpBitFieldReverse:
2509 unaryOp = spv::OpBitReverse;
2510 break;
2511 case glslang::EOpBitCount:
2512 unaryOp = spv::OpBitCount;
2513 break;
2514 case glslang::EOpFindLSB:
2515 libCall = spv::GLSLstd450FindILSB;
2516 break;
2517 case glslang::EOpFindMSB:
2518 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2519 libCall = spv::GLSLstd450FindSMSB;
2520 break;
2521
John Kessenich140f3df2015-06-26 16:58:36 -06002522 default:
2523 return 0;
2524 }
2525
2526 spv::Id id;
2527 if (libCall >= 0) {
2528 std::vector<spv::Id> args;
2529 args.push_back(operand);
2530 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2531 } else
2532 id = builder.createUnaryOp(unaryOp, typeId, operand);
2533
2534 builder.setPrecision(id, precision);
2535
2536 return id;
2537}
2538
2539spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2540{
2541 spv::Op convOp = spv::OpNop;
2542 spv::Id zero = 0;
2543 spv::Id one = 0;
2544
2545 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2546
2547 switch (op) {
2548 case glslang::EOpConvIntToBool:
2549 case glslang::EOpConvUintToBool:
2550 zero = builder.makeUintConstant(0);
2551 zero = makeSmearedConstant(zero, vectorSize);
2552 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2553
2554 case glslang::EOpConvFloatToBool:
2555 zero = builder.makeFloatConstant(0.0F);
2556 zero = makeSmearedConstant(zero, vectorSize);
2557 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2558
2559 case glslang::EOpConvDoubleToBool:
2560 zero = builder.makeDoubleConstant(0.0);
2561 zero = makeSmearedConstant(zero, vectorSize);
2562 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2563
2564 case glslang::EOpConvBoolToFloat:
2565 convOp = spv::OpSelect;
2566 zero = builder.makeFloatConstant(0.0);
2567 one = builder.makeFloatConstant(1.0);
2568 break;
2569 case glslang::EOpConvBoolToDouble:
2570 convOp = spv::OpSelect;
2571 zero = builder.makeDoubleConstant(0.0);
2572 one = builder.makeDoubleConstant(1.0);
2573 break;
2574 case glslang::EOpConvBoolToInt:
2575 zero = builder.makeIntConstant(0);
2576 one = builder.makeIntConstant(1);
2577 convOp = spv::OpSelect;
2578 break;
2579 case glslang::EOpConvBoolToUint:
2580 zero = builder.makeUintConstant(0);
2581 one = builder.makeUintConstant(1);
2582 convOp = spv::OpSelect;
2583 break;
2584
2585 case glslang::EOpConvIntToFloat:
2586 case glslang::EOpConvIntToDouble:
2587 convOp = spv::OpConvertSToF;
2588 break;
2589
2590 case glslang::EOpConvUintToFloat:
2591 case glslang::EOpConvUintToDouble:
2592 convOp = spv::OpConvertUToF;
2593 break;
2594
2595 case glslang::EOpConvDoubleToFloat:
2596 case glslang::EOpConvFloatToDouble:
2597 convOp = spv::OpFConvert;
2598 break;
2599
2600 case glslang::EOpConvFloatToInt:
2601 case glslang::EOpConvDoubleToInt:
2602 convOp = spv::OpConvertFToS;
2603 break;
2604
2605 case glslang::EOpConvUintToInt:
2606 case glslang::EOpConvIntToUint:
2607 convOp = spv::OpBitcast;
2608 break;
2609
2610 case glslang::EOpConvFloatToUint:
2611 case glslang::EOpConvDoubleToUint:
2612 convOp = spv::OpConvertFToU;
2613 break;
2614 default:
2615 break;
2616 }
2617
2618 spv::Id result = 0;
2619 if (convOp == spv::OpNop)
2620 return result;
2621
2622 if (convOp == spv::OpSelect) {
2623 zero = makeSmearedConstant(zero, vectorSize);
2624 one = makeSmearedConstant(one, vectorSize);
2625 result = builder.createTriOp(convOp, destType, operand, one, zero);
2626 } else
2627 result = builder.createUnaryOp(convOp, destType, operand);
2628
2629 builder.setPrecision(result, precision);
2630
2631 return result;
2632}
2633
2634spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2635{
2636 if (vectorSize == 0)
2637 return constant;
2638
2639 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2640 std::vector<spv::Id> components;
2641 for (int c = 0; c < vectorSize; ++c)
2642 components.push_back(constant);
2643 return builder.makeCompositeConstant(vectorTypeId, components);
2644}
2645
John Kessenich426394d2015-07-23 10:22:48 -06002646// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002647spv::Id TGlslangToSpvTraverser::createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich426394d2015-07-23 10:22:48 -06002648{
2649 spv::Op opCode = spv::OpNop;
2650
2651 switch (op) {
2652 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002653 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002654 opCode = spv::OpAtomicIAdd;
2655 break;
2656 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002657 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002658 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002659 break;
2660 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002661 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002662 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002663 break;
2664 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002665 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002666 opCode = spv::OpAtomicAnd;
2667 break;
2668 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002669 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002670 opCode = spv::OpAtomicOr;
2671 break;
2672 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002673 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002674 opCode = spv::OpAtomicXor;
2675 break;
2676 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002677 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002678 opCode = spv::OpAtomicExchange;
2679 break;
2680 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002681 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002682 opCode = spv::OpAtomicCompareExchange;
2683 break;
2684 case glslang::EOpAtomicCounterIncrement:
2685 opCode = spv::OpAtomicIIncrement;
2686 break;
2687 case glslang::EOpAtomicCounterDecrement:
2688 opCode = spv::OpAtomicIDecrement;
2689 break;
2690 case glslang::EOpAtomicCounter:
2691 opCode = spv::OpAtomicLoad;
2692 break;
2693 default:
2694 spv::MissingFunctionality("missing nested atomic");
2695 break;
2696 }
2697
2698 // Sort out the operands
2699 // - mapping from glslang -> SPV
2700 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002701 // - compare-exchange swaps the value and comparator
2702 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002703 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2704 auto opIt = operands.begin(); // walk the glslang operands
2705 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002706 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2707 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2708 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002709 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2710 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002711 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002712 spvAtomicOperands.push_back(*(opIt + 1));
2713 spvAtomicOperands.push_back(*opIt);
2714 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002715 }
John Kessenich426394d2015-07-23 10:22:48 -06002716
John Kessenich3e60a6f2015-09-14 22:45:16 -06002717 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002718 for (; opIt != operands.end(); ++opIt)
2719 spvAtomicOperands.push_back(*opIt);
2720
2721 return builder.createOp(opCode, typeId, spvAtomicOperands);
2722}
2723
John Kessenich5e4b1242015-08-06 22:53:06 -06002724spv::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 -06002725{
John Kessenich5e4b1242015-08-06 22:53:06 -06002726 bool isUnsigned = typeProxy == glslang::EbtUint;
2727 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2728
John Kessenich140f3df2015-06-26 16:58:36 -06002729 spv::Op opCode = spv::OpNop;
2730 int libCall = -1;
2731
2732 switch (op) {
2733 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002734 if (isFloat)
2735 libCall = spv::GLSLstd450FMin;
2736 else if (isUnsigned)
2737 libCall = spv::GLSLstd450UMin;
2738 else
2739 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002740 break;
2741 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002742 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002743 break;
2744 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002745 if (isFloat)
2746 libCall = spv::GLSLstd450FMax;
2747 else if (isUnsigned)
2748 libCall = spv::GLSLstd450UMax;
2749 else
2750 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002751 break;
2752 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002753 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002754 break;
2755 case glslang::EOpDot:
2756 opCode = spv::OpDot;
2757 break;
2758 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002759 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002760 break;
2761
2762 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002763 if (isFloat)
2764 libCall = spv::GLSLstd450FClamp;
2765 else if (isUnsigned)
2766 libCall = spv::GLSLstd450UClamp;
2767 else
2768 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002769 break;
2770 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002771 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002772 break;
2773 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002774 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002775 break;
2776 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002777 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002778 break;
2779
2780 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002781 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002782 break;
2783 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002784 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002785 break;
2786 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002787 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002788 break;
2789 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002790 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002791 break;
2792 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002793 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002794 break;
John Kessenich426394d2015-07-23 10:22:48 -06002795
John Kessenich140f3df2015-06-26 16:58:36 -06002796 default:
2797 return 0;
2798 }
2799
2800 spv::Id id = 0;
2801 if (libCall >= 0)
2802 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2803 else {
2804 switch (operands.size()) {
2805 case 0:
2806 // should all be handled by visitAggregate and createNoArgOperation
2807 assert(0);
2808 return 0;
2809 case 1:
2810 // should all be handled by createUnaryOperation
2811 assert(0);
2812 return 0;
2813 case 2:
2814 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2815 break;
2816 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002817 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002818 break;
2819 default:
2820 // These do not exist yet
2821 assert(0 && "operation with more than 3 operands");
2822 break;
2823 }
2824 }
2825
2826 builder.setPrecision(id, precision);
2827
2828 return id;
2829}
2830
2831// Intrinsics with no arguments, no return value, and no precision.
2832spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2833{
2834 // TODO: get the barrier operands correct
2835
2836 switch (op) {
2837 case glslang::EOpEmitVertex:
2838 builder.createNoResultOp(spv::OpEmitVertex);
2839 return 0;
2840 case glslang::EOpEndPrimitive:
2841 builder.createNoResultOp(spv::OpEndPrimitive);
2842 return 0;
2843 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002844 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2845 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002846 return 0;
2847 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002848 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002849 return 0;
2850 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002851 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002852 return 0;
2853 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002854 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002855 return 0;
2856 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002857 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002858 return 0;
2859 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002860 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002861 return 0;
2862 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002863 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002864 return 0;
2865 default:
2866 spv::MissingFunctionality("operation with no arguments");
2867 return 0;
2868 }
2869}
2870
2871spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2872{
John Kessenich2f273362015-07-18 22:34:27 -06002873 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002874 spv::Id id;
2875 if (symbolValues.end() != iter) {
2876 id = iter->second;
2877 return id;
2878 }
2879
2880 // it was not found, create it
2881 id = createSpvVariable(symbol);
2882 symbolValues[symbol->getId()] = id;
2883
2884 if (! symbol->getType().isStruct()) {
2885 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2886 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2887 if (symbol->getQualifier().hasLocation())
2888 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2889 if (symbol->getQualifier().hasIndex())
2890 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2891 if (symbol->getQualifier().hasComponent())
2892 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2893 if (glslangIntermediate->getXfbMode()) {
2894 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002895 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002896 if (symbol->getQualifier().hasXfbBuffer())
2897 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2898 if (symbol->getQualifier().hasXfbOffset())
2899 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2900 }
2901 }
2902
2903 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2904 if (symbol->getQualifier().hasStream())
2905 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2906 if (symbol->getQualifier().hasSet())
2907 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2908 if (symbol->getQualifier().hasBinding())
2909 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2910 if (glslangIntermediate->getXfbMode()) {
2911 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002912 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002913 if (symbol->getQualifier().hasXfbBuffer())
2914 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2915 }
2916
2917 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002918 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002919 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002920 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002921
2922 if (linkageOnly)
2923 builder.addDecoration(id, spv::DecorationNoStaticUse);
2924
2925 return id;
2926}
2927
2928void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2929{
2930 if (dec != spv::BadValue)
2931 builder.addDecoration(id, dec);
2932}
2933
2934void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2935{
2936 if (dec != spv::BadValue)
2937 builder.addMemberDecoration(id, (unsigned)member, dec);
2938}
2939
2940// Use 'consts' as the flattened glslang source of scalar constants to recursively
2941// build the aggregate SPIR-V constant.
2942//
2943// If there are not enough elements present in 'consts', 0 will be substituted;
2944// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2945//
2946spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2947{
2948 // vector of constants for SPIR-V
2949 std::vector<spv::Id> spvConsts;
2950
2951 // Type is used for struct and array constants
2952 spv::Id typeId = convertGlslangToSpvType(glslangType);
2953
2954 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002955 glslang::TType elementType(glslangType, 0);
2956 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002957 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2958 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002959 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002960 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2961 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2962 } else if (glslangType.getStruct()) {
2963 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2964 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2965 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2966 } else if (glslangType.isVector()) {
2967 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2968 bool zero = nextConst >= consts.size();
2969 switch (glslangType.getBasicType()) {
2970 case glslang::EbtInt:
2971 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2972 break;
2973 case glslang::EbtUint:
2974 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2975 break;
2976 case glslang::EbtFloat:
2977 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2978 break;
2979 case glslang::EbtDouble:
2980 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2981 break;
2982 case glslang::EbtBool:
2983 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2984 break;
2985 default:
2986 spv::MissingFunctionality("constant vector type");
2987 break;
2988 }
2989 ++nextConst;
2990 }
2991 } else {
2992 // we have a non-aggregate (scalar) constant
2993 bool zero = nextConst >= consts.size();
2994 spv::Id scalar = 0;
2995 switch (glslangType.getBasicType()) {
2996 case glslang::EbtInt:
2997 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2998 break;
2999 case glslang::EbtUint:
3000 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
3001 break;
3002 case glslang::EbtFloat:
3003 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
3004 break;
3005 case glslang::EbtDouble:
3006 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
3007 break;
3008 case glslang::EbtBool:
3009 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
3010 break;
3011 default:
3012 spv::MissingFunctionality("constant scalar type");
3013 break;
3014 }
3015 ++nextConst;
3016 return scalar;
3017 }
3018
3019 return builder.makeCompositeConstant(typeId, spvConsts);
3020}
3021
3022}; // end anonymous namespace
3023
3024namespace glslang {
3025
John Kessenich68d78fd2015-07-12 19:28:10 -06003026void GetSpirvVersion(std::string& version)
3027{
John Kessenich9e55f632015-07-15 10:03:39 -06003028 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003029 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06003030 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003031 version = buf;
3032}
3033
John Kessenich140f3df2015-06-26 16:58:36 -06003034// Write SPIR-V out to a binary file
3035void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3036{
3037 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003038 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003039 for (int i = 0; i < (int)spirv.size(); ++i) {
3040 unsigned int word = spirv[i];
3041 out.write((const char*)&word, 4);
3042 }
3043 out.close();
3044}
3045
3046//
3047// Set up the glslang traversal
3048//
3049void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3050{
3051 TIntermNode* root = intermediate.getTreeRoot();
3052
3053 if (root == 0)
3054 return;
3055
3056 glslang::GetThreadPoolAllocator().push();
3057
3058 TGlslangToSpvTraverser it(&intermediate);
3059
3060 root->traverse(&it);
3061
3062 it.dumpSpv(spirv);
3063
3064 glslang::GetThreadPoolAllocator().pop();
3065}
3066
3067}; // end namespace glslang