blob: 1a7c69c73690e4cb6411e19c74957c6d1452509d [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;
448 default: mode = spv::BadValue; break;
449 }
450 if (mode != spv::BadValue)
451 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
452
453 // TODO
454 //builder.addExecutionMode(spv::VertexSpacingMdName, glslangIntermediate->getVertexSpacing());
455 //builder.addExecutionMode(spv::VertexOrderMdName, glslangIntermediate->getVertexOrder());
456 //builder.addExecutionMode(spv::PointModeMdName, glslangIntermediate->getPointMode());
457 break;
458
459 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600460 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600461 switch (glslangIntermediate->getInputPrimitive()) {
462 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
463 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
464 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
465 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
466 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
467 default: mode = spv::BadValue; break;
468 }
469 if (mode != spv::BadValue)
470 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
471 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
472
473 switch (glslangIntermediate->getOutputPrimitive()) {
474 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
475 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
476 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
477 default: mode = spv::BadValue; break;
478 }
479 if (mode != spv::BadValue)
480 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
481 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
482 break;
483
484 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600485 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600486 if (glslangIntermediate->getPixelCenterInteger())
487 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
488 if (glslangIntermediate->getOriginUpperLeft())
489 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600490 else
491 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kessenich140f3df2015-06-26 16:58:36 -0600492 break;
493
494 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600495 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600496 break;
497
498 default:
499 break;
500 }
501
502}
503
504TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
505{
506 if (! mainTerminated) {
507 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
508 builder.setBuildPoint(lastMainBlock);
509 builder.leaveFunction(true);
510 }
511}
512
513//
514// Implement the traversal functions.
515//
516// Return true from interior nodes to have the external traversal
517// continue on to children. Return false if children were
518// already processed.
519//
520
521//
522// Symbols can turn into
523// - uniform/input reads
524// - output writes
525// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
526// - something simple that degenerates into the last bullet
527//
528void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
529{
530 // getSymbolId() will set up all the IO decorations on the first call.
531 // Formal function parameters were mapped during makeFunctions().
532 spv::Id id = getSymbolId(symbol);
533
534 if (! linkageOnly) {
535 // Prepare to generate code for the access
536
537 // L-value chains will be computed left to right. We're on the symbol now,
538 // which is the left-most part of the access chain, so now is "clear" time,
539 // followed by setting the base.
540 builder.clearAccessChain();
541
542 // For now, we consider all user variables as being in memory, so they are pointers,
543 // except for "const in" arguments to a function, which are an intermediate object.
544 // See comments in handleUserFunctionCall().
545 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
546 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
547 builder.setAccessChainRValue(id);
548 else
549 builder.setAccessChainLValue(id);
550 }
551}
552
553bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
554{
555 // First, handle special cases
556 switch (node->getOp()) {
557 case glslang::EOpAssign:
558 case glslang::EOpAddAssign:
559 case glslang::EOpSubAssign:
560 case glslang::EOpMulAssign:
561 case glslang::EOpVectorTimesMatrixAssign:
562 case glslang::EOpVectorTimesScalarAssign:
563 case glslang::EOpMatrixTimesScalarAssign:
564 case glslang::EOpMatrixTimesMatrixAssign:
565 case glslang::EOpDivAssign:
566 case glslang::EOpModAssign:
567 case glslang::EOpAndAssign:
568 case glslang::EOpInclusiveOrAssign:
569 case glslang::EOpExclusiveOrAssign:
570 case glslang::EOpLeftShiftAssign:
571 case glslang::EOpRightShiftAssign:
572 // A bin-op assign "a += b" means the same thing as "a = a + b"
573 // where a is evaluated before b. For a simple assignment, GLSL
574 // says to evaluate the left before the right. So, always, left
575 // node then right node.
576 {
577 // get the left l-value, save it away
578 builder.clearAccessChain();
579 node->getLeft()->traverse(this);
580 spv::Builder::AccessChain lValue = builder.getAccessChain();
581
582 // evaluate the right
583 builder.clearAccessChain();
584 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600585 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600586
587 if (node->getOp() != glslang::EOpAssign) {
588 // the left is also an r-value
589 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600590 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600591
592 // do the operation
593 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
594 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
595 node->getType().getBasicType());
596
597 // these all need their counterparts in createBinaryOperation()
598 if (rValue == 0)
599 spv::MissingFunctionality("createBinaryOperation");
600 }
601
602 // store the result
603 builder.setAccessChain(lValue);
604 builder.accessChainStore(rValue);
605
606 // assignments are expressions having an rValue after they are evaluated...
607 builder.clearAccessChain();
608 builder.setAccessChainRValue(rValue);
609 }
610 return false;
611 case glslang::EOpIndexDirect:
612 case glslang::EOpIndexDirectStruct:
613 {
614 // Get the left part of the access chain.
615 node->getLeft()->traverse(this);
616
617 // Add the next element in the chain
618
619 int index = 0;
620 if (node->getRight()->getAsConstantUnion() == 0)
621 spv::MissingFunctionality("direct index without a constant node");
622 else
623 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
624
625 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
626 // This may be, e.g., an anonymous block-member selection, which generally need
627 // index remapping due to hidden members in anonymous blocks.
628 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
629 if (remapper.size() == 0)
630 spv::MissingFunctionality("block without member remapping");
631 else
632 index = remapper[index];
633 }
634
635 if (! node->getLeft()->getType().isArray() &&
636 node->getLeft()->getType().isVector() &&
637 node->getOp() == glslang::EOpIndexDirect) {
638 // This is essentially a hard-coded vector swizzle of size 1,
639 // so short circuit the access-chain stuff with a swizzle.
640 std::vector<unsigned> swizzle;
641 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600642 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600643 } else {
644 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600645 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600646 }
647 }
648 return false;
649 case glslang::EOpIndexIndirect:
650 {
651 // Structure or array or vector indirection.
652 // Will use native SPIR-V access-chain for struct and array indirection;
653 // matrices are arrays of vectors, so will also work for a matrix.
654 // Will use the access chain's 'component' for variable index into a vector.
655
656 // This adapter is building access chains left to right.
657 // Set up the access chain to the left.
658 node->getLeft()->traverse(this);
659
660 // save it so that computing the right side doesn't trash it
661 spv::Builder::AccessChain partial = builder.getAccessChain();
662
663 // compute the next index in the chain
664 builder.clearAccessChain();
665 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600666 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600667
668 // restore the saved access chain
669 builder.setAccessChain(partial);
670
671 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600672 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600673 else
John Kessenichfa668da2015-09-13 14:46:30 -0600674 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600675 }
676 return false;
677 case glslang::EOpVectorSwizzle:
678 {
679 node->getLeft()->traverse(this);
680 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
681 std::vector<unsigned> swizzle;
682 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
683 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600684 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600685 }
686 return false;
687 default:
688 break;
689 }
690
691 // Assume generic binary op...
692
693 // Get the operands
694 builder.clearAccessChain();
695 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600696 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600697
698 builder.clearAccessChain();
699 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600700 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600701
702 spv::Id result;
703 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
704
705 result = createBinaryOperation(node->getOp(), precision,
706 convertGlslangToSpvType(node->getType()), left, right,
707 node->getLeft()->getType().getBasicType());
708
709 if (! result) {
710 spv::MissingFunctionality("glslang binary operation");
711 } else {
712 builder.clearAccessChain();
713 builder.setAccessChainRValue(result);
714
715 return false;
716 }
717
718 return true;
719}
720
721bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
722{
John Kessenichfc51d282015-08-19 13:34:18 -0600723 spv::Id result = spv::NoResult;
724
725 // try texturing first
726 result = createImageTextureFunctionCall(node);
727 if (result != spv::NoResult) {
728 builder.clearAccessChain();
729 builder.setAccessChainRValue(result);
730
731 return false; // done with this node
732 }
733
734 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600735
736 if (node->getOp() == glslang::EOpArrayLength) {
737 // Quite special; won't want to evaluate the operand.
738
739 // Normal .length() would have been constant folded by the front-end.
740 // So, this has to be block.lastMember.length().
741 // SPV wants "block" as the operand, go get it.
742 assert(node->getOperand()->getType().isRuntimeSizedArray());
743 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
744 block->traverse(this);
745 spv::Id length = builder.createUnaryOp(spv::OpArrayLength, builder.makeIntType(32), builder.accessChainGetLValue());
746
747 builder.clearAccessChain();
748 builder.setAccessChainRValue(length);
749
750 return false;
751 }
752
John Kessenichfc51d282015-08-19 13:34:18 -0600753 // Start by evaluating the operand
754
John Kessenich140f3df2015-06-26 16:58:36 -0600755 builder.clearAccessChain();
756 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800757
Rex Xufc618912015-09-09 16:42:49 +0800758 spv::Id operand = spv::NoResult;
759
760 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
761 node->getOp() == glslang::EOpAtomicCounterDecrement ||
762 node->getOp() == glslang::EOpAtomicCounter)
763 operand = builder.accessChainGetLValue(); // Special case l-value operands
764 else
Rex Xu30f92582015-09-14 10:38:56 +0800765 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600766
767 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
768
769 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600770 if (! result)
771 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600772
773 // if not, then possibly an operation
774 if (! result)
Rex Xu04db3f52015-09-16 11:44:02 +0800775 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600776
777 if (result) {
778 builder.clearAccessChain();
779 builder.setAccessChainRValue(result);
780
781 return false; // done with this node
782 }
783
784 // it must be a special case, check...
785 switch (node->getOp()) {
786 case glslang::EOpPostIncrement:
787 case glslang::EOpPostDecrement:
788 case glslang::EOpPreIncrement:
789 case glslang::EOpPreDecrement:
790 {
791 // we need the integer value "1" or the floating point "1.0" to add/subtract
792 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
793 builder.makeFloatConstant(1.0F) :
794 builder.makeIntConstant(1);
795 glslang::TOperator op;
796 if (node->getOp() == glslang::EOpPreIncrement ||
797 node->getOp() == glslang::EOpPostIncrement)
798 op = glslang::EOpAdd;
799 else
800 op = glslang::EOpSub;
801
802 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
803 convertGlslangToSpvType(node->getType()), operand, one,
804 node->getType().getBasicType());
805 if (result == 0)
806 spv::MissingFunctionality("createBinaryOperation for unary");
807
808 // The result of operation is always stored, but conditionally the
809 // consumed result. The consumed result is always an r-value.
810 builder.accessChainStore(result);
811 builder.clearAccessChain();
812 if (node->getOp() == glslang::EOpPreIncrement ||
813 node->getOp() == glslang::EOpPreDecrement)
814 builder.setAccessChainRValue(result);
815 else
816 builder.setAccessChainRValue(operand);
817 }
818
819 return false;
820
821 case glslang::EOpEmitStreamVertex:
822 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
823 return false;
824 case glslang::EOpEndStreamPrimitive:
825 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
826 return false;
827
828 default:
829 spv::MissingFunctionality("glslang unary");
830 break;
831 }
832
833 return true;
834}
835
836bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
837{
John Kessenichfc51d282015-08-19 13:34:18 -0600838 spv::Id result = spv::NoResult;
839
840 // try texturing
841 result = createImageTextureFunctionCall(node);
842 if (result != spv::NoResult) {
843 builder.clearAccessChain();
844 builder.setAccessChainRValue(result);
845
846 return false;
847 }
Rex Xufc618912015-09-09 16:42:49 +0800848 else if (node->getOp() == glslang::EOpImageStore)
849 {
850 // "imageStore" is a special case, which has no result
851 return false;
852 }
John Kessenichfc51d282015-08-19 13:34:18 -0600853
John Kessenich140f3df2015-06-26 16:58:36 -0600854 glslang::TOperator binOp = glslang::EOpNull;
855 bool reduceComparison = true;
856 bool isMatrix = false;
857 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600858 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600859
860 assert(node->getOp());
861
862 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
863
864 switch (node->getOp()) {
865 case glslang::EOpSequence:
866 {
867 if (preVisit)
868 ++sequenceDepth;
869 else
870 --sequenceDepth;
871
872 if (sequenceDepth == 1) {
873 // If this is the parent node of all the functions, we want to see them
874 // early, so all call points have actual SPIR-V functions to reference.
875 // In all cases, still let the traverser visit the children for us.
876 makeFunctions(node->getAsAggregate()->getSequence());
877
878 // Also, we want all globals initializers to go into the entry of main(), before
879 // anything else gets there, so visit out of order, doing them all now.
880 makeGlobalInitializers(node->getAsAggregate()->getSequence());
881
882 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
883 // so do them manually.
884 visitFunctions(node->getAsAggregate()->getSequence());
885
886 return false;
887 }
888
889 return true;
890 }
891 case glslang::EOpLinkerObjects:
892 {
893 if (visit == glslang::EvPreVisit)
894 linkageOnly = true;
895 else
896 linkageOnly = false;
897
898 return true;
899 }
900 case glslang::EOpComma:
901 {
902 // processing from left to right naturally leaves the right-most
903 // lying around in the access chain
904 glslang::TIntermSequence& glslangOperands = node->getSequence();
905 for (int i = 0; i < (int)glslangOperands.size(); ++i)
906 glslangOperands[i]->traverse(this);
907
908 return false;
909 }
910 case glslang::EOpFunction:
911 if (visit == glslang::EvPreVisit) {
912 if (isShaderEntrypoint(node)) {
913 inMain = true;
914 builder.setBuildPoint(shaderEntry->getLastBlock());
915 } else {
916 handleFunctionEntry(node);
917 }
918 } else {
919 if (inMain)
920 mainTerminated = true;
921 builder.leaveFunction(inMain);
922 inMain = false;
923 }
924
925 return true;
926 case glslang::EOpParameters:
927 // Parameters will have been consumed by EOpFunction processing, but not
928 // the body, so we still visited the function node's children, making this
929 // child redundant.
930 return false;
931 case glslang::EOpFunctionCall:
932 {
933 if (node->isUserDefined())
934 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600935
936 if (! result) {
937 spv::MissingFunctionality("glslang function call");
938 glslang::TConstUnionArray emptyConsts;
939 int nextConst = 0;
940 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
941 }
942 builder.clearAccessChain();
943 builder.setAccessChainRValue(result);
944
945 return false;
946 }
947 case glslang::EOpConstructMat2x2:
948 case glslang::EOpConstructMat2x3:
949 case glslang::EOpConstructMat2x4:
950 case glslang::EOpConstructMat3x2:
951 case glslang::EOpConstructMat3x3:
952 case glslang::EOpConstructMat3x4:
953 case glslang::EOpConstructMat4x2:
954 case glslang::EOpConstructMat4x3:
955 case glslang::EOpConstructMat4x4:
956 case glslang::EOpConstructDMat2x2:
957 case glslang::EOpConstructDMat2x3:
958 case glslang::EOpConstructDMat2x4:
959 case glslang::EOpConstructDMat3x2:
960 case glslang::EOpConstructDMat3x3:
961 case glslang::EOpConstructDMat3x4:
962 case glslang::EOpConstructDMat4x2:
963 case glslang::EOpConstructDMat4x3:
964 case glslang::EOpConstructDMat4x4:
965 isMatrix = true;
966 // fall through
967 case glslang::EOpConstructFloat:
968 case glslang::EOpConstructVec2:
969 case glslang::EOpConstructVec3:
970 case glslang::EOpConstructVec4:
971 case glslang::EOpConstructDouble:
972 case glslang::EOpConstructDVec2:
973 case glslang::EOpConstructDVec3:
974 case glslang::EOpConstructDVec4:
975 case glslang::EOpConstructBool:
976 case glslang::EOpConstructBVec2:
977 case glslang::EOpConstructBVec3:
978 case glslang::EOpConstructBVec4:
979 case glslang::EOpConstructInt:
980 case glslang::EOpConstructIVec2:
981 case glslang::EOpConstructIVec3:
982 case glslang::EOpConstructIVec4:
983 case glslang::EOpConstructUint:
984 case glslang::EOpConstructUVec2:
985 case glslang::EOpConstructUVec3:
986 case glslang::EOpConstructUVec4:
987 case glslang::EOpConstructStruct:
988 {
989 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +0800990 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -0600991 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
992 spv::Id constructed;
993 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
994 std::vector<spv::Id> constituents;
995 for (int c = 0; c < (int)arguments.size(); ++c)
996 constituents.push_back(arguments[c]);
997 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
998 } else {
999 if (isMatrix)
1000 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1001 else
1002 constructed = builder.createConstructor(precision, arguments, resultTypeId);
1003 }
1004
1005 builder.clearAccessChain();
1006 builder.setAccessChainRValue(constructed);
1007
1008 return false;
1009 }
1010
1011 // These six are component-wise compares with component-wise results.
1012 // Forward on to createBinaryOperation(), requesting a vector result.
1013 case glslang::EOpLessThan:
1014 case glslang::EOpGreaterThan:
1015 case glslang::EOpLessThanEqual:
1016 case glslang::EOpGreaterThanEqual:
1017 case glslang::EOpVectorEqual:
1018 case glslang::EOpVectorNotEqual:
1019 {
1020 // Map the operation to a binary
1021 binOp = node->getOp();
1022 reduceComparison = false;
1023 switch (node->getOp()) {
1024 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1025 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1026 default: binOp = node->getOp(); break;
1027 }
1028
1029 break;
1030 }
1031 case glslang::EOpMul:
1032 // compontent-wise matrix multiply
1033 binOp = glslang::EOpMul;
1034 break;
1035 case glslang::EOpOuterProduct:
1036 // two vectors multiplied to make a matrix
1037 binOp = glslang::EOpOuterProduct;
1038 break;
1039 case glslang::EOpDot:
1040 {
1041 // for scalar dot product, use multiply
1042 glslang::TIntermSequence& glslangOperands = node->getSequence();
1043 if (! glslangOperands[0]->getAsTyped()->isVector())
1044 binOp = glslang::EOpMul;
1045 break;
1046 }
1047 case glslang::EOpMod:
1048 // when an aggregate, this is the floating-point mod built-in function,
1049 // which can be emitted by the one in createBinaryOperation()
1050 binOp = glslang::EOpMod;
1051 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001052 case glslang::EOpEmitVertex:
1053 case glslang::EOpEndPrimitive:
1054 case glslang::EOpBarrier:
1055 case glslang::EOpMemoryBarrier:
1056 case glslang::EOpMemoryBarrierAtomicCounter:
1057 case glslang::EOpMemoryBarrierBuffer:
1058 case glslang::EOpMemoryBarrierImage:
1059 case glslang::EOpMemoryBarrierShared:
1060 case glslang::EOpGroupMemoryBarrier:
1061 noReturnValue = true;
1062 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1063 break;
1064
John Kessenich426394d2015-07-23 10:22:48 -06001065 case glslang::EOpAtomicAdd:
1066 case glslang::EOpAtomicMin:
1067 case glslang::EOpAtomicMax:
1068 case glslang::EOpAtomicAnd:
1069 case glslang::EOpAtomicOr:
1070 case glslang::EOpAtomicXor:
1071 case glslang::EOpAtomicExchange:
1072 case glslang::EOpAtomicCompSwap:
1073 atomic = true;
1074 break;
1075
John Kessenichfc51d282015-08-19 13:34:18 -06001076 case glslang::EOpAddCarry:
1077 case glslang::EOpSubBorrow:
1078 case glslang::EOpUMulExtended:
1079 case glslang::EOpIMulExtended:
1080 case glslang::EOpBitfieldExtract:
1081 case glslang::EOpBitfieldInsert:
1082 spv::MissingFunctionality("integer aggregate");
1083 break;
1084
1085 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001086 case glslang::EOpFrexp:
1087 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001088 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1089 break;
1090
John Kessenich140f3df2015-06-26 16:58:36 -06001091 default:
1092 break;
1093 }
1094
1095 //
1096 // See if it maps to a regular operation.
1097 //
John Kessenich140f3df2015-06-26 16:58:36 -06001098 if (binOp != glslang::EOpNull) {
1099 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1100 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1101 assert(left && right);
1102
1103 builder.clearAccessChain();
1104 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001105 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001106
1107 builder.clearAccessChain();
1108 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001109 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001110
1111 result = createBinaryOperation(binOp, precision,
1112 convertGlslangToSpvType(node->getType()), leftId, rightId,
1113 left->getType().getBasicType(), reduceComparison);
1114
1115 // code above should only make binOp that exists in createBinaryOperation
1116 if (result == 0)
1117 spv::MissingFunctionality("createBinaryOperation for aggregate");
1118
1119 builder.clearAccessChain();
1120 builder.setAccessChainRValue(result);
1121
1122 return false;
1123 }
1124
John Kessenich426394d2015-07-23 10:22:48 -06001125 //
1126 // Create the list of operands.
1127 //
John Kessenich140f3df2015-06-26 16:58:36 -06001128 glslang::TIntermSequence& glslangOperands = node->getSequence();
1129 std::vector<spv::Id> operands;
1130 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1131 builder.clearAccessChain();
1132 glslangOperands[arg]->traverse(this);
1133
1134 // special case l-value operands; there are just a few
1135 bool lvalue = false;
1136 switch (node->getOp()) {
1137 //case glslang::EOpFrexp:
1138 case glslang::EOpModf:
1139 if (arg == 1)
1140 lvalue = true;
1141 break;
Rex Xud4782c12015-09-06 16:30:11 +08001142 case glslang::EOpAtomicAdd:
1143 case glslang::EOpAtomicMin:
1144 case glslang::EOpAtomicMax:
1145 case glslang::EOpAtomicAnd:
1146 case glslang::EOpAtomicOr:
1147 case glslang::EOpAtomicXor:
1148 case glslang::EOpAtomicExchange:
1149 case glslang::EOpAtomicCompSwap:
1150 if (arg == 0)
1151 lvalue = true;
1152 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001153 //case glslang::EOpUAddCarry:
1154 //case glslang::EOpUSubBorrow:
1155 //case glslang::EOpUMulExtended:
1156 default:
1157 break;
1158 }
1159 if (lvalue)
1160 operands.push_back(builder.accessChainGetLValue());
1161 else
John Kessenichfa668da2015-09-13 14:46:30 -06001162 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001163 }
John Kessenich426394d2015-07-23 10:22:48 -06001164
1165 if (atomic) {
1166 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001167 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001168 } else {
1169 // Pass through to generic operations.
1170 switch (glslangOperands.size()) {
1171 case 0:
1172 result = createNoArgOperation(node->getOp());
1173 break;
1174 case 1:
Rex Xu04db3f52015-09-16 11:44:02 +08001175 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001176 break;
1177 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001178 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001179 break;
1180 }
John Kessenich140f3df2015-06-26 16:58:36 -06001181 }
1182
1183 if (noReturnValue)
1184 return false;
1185
1186 if (! result) {
1187 spv::MissingFunctionality("glslang aggregate");
1188 return true;
1189 } else {
1190 builder.clearAccessChain();
1191 builder.setAccessChainRValue(result);
1192 return false;
1193 }
1194}
1195
1196bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1197{
1198 // This path handles both if-then-else and ?:
1199 // The if-then-else has a node type of void, while
1200 // ?: has a non-void node type
1201 spv::Id result = 0;
1202 if (node->getBasicType() != glslang::EbtVoid) {
1203 // don't handle this as just on-the-fly temporaries, because there will be two names
1204 // and better to leave SSA to later passes
1205 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1206 }
1207
1208 // emit the condition before doing anything with selection
1209 node->getCondition()->traverse(this);
1210
1211 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001212 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001213
1214 if (node->getTrueBlock()) {
1215 // emit the "then" statement
1216 node->getTrueBlock()->traverse(this);
1217 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001218 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001219 }
1220
1221 if (node->getFalseBlock()) {
1222 ifBuilder.makeBeginElse();
1223 // emit the "else" statement
1224 node->getFalseBlock()->traverse(this);
1225 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001226 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001227 }
1228
1229 ifBuilder.makeEndIf();
1230
1231 if (result) {
1232 // GLSL only has r-values as the result of a :?, but
1233 // if we have an l-value, that can be more efficient if it will
1234 // become the base of a complex r-value expression, because the
1235 // next layer copies r-values into memory to use the access-chain mechanism
1236 builder.clearAccessChain();
1237 builder.setAccessChainLValue(result);
1238 }
1239
1240 return false;
1241}
1242
1243bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1244{
1245 // emit and get the condition before doing anything with switch
1246 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001247 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001248
1249 // browse the children to sort out code segments
1250 int defaultSegment = -1;
1251 std::vector<TIntermNode*> codeSegments;
1252 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1253 std::vector<int> caseValues;
1254 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1255 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1256 TIntermNode* child = *c;
1257 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001258 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001259 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001260 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001261 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1262 } else
1263 codeSegments.push_back(child);
1264 }
1265
1266 // handle the case where the last code segment is missing, due to no code
1267 // statements between the last case and the end of the switch statement
1268 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1269 (int)codeSegments.size() == defaultSegment)
1270 codeSegments.push_back(nullptr);
1271
1272 // make the switch statement
1273 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001274 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001275
1276 // emit all the code in the segments
1277 breakForLoop.push(false);
1278 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1279 builder.nextSwitchSegment(segmentBlocks, s);
1280 if (codeSegments[s])
1281 codeSegments[s]->traverse(this);
1282 else
1283 builder.addSwitchBreak();
1284 }
1285 breakForLoop.pop();
1286
1287 builder.endSwitch(segmentBlocks);
1288
1289 return false;
1290}
1291
1292void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1293{
1294 int nextConst = 0;
1295 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1296
1297 builder.clearAccessChain();
1298 builder.setAccessChainRValue(constant);
1299}
1300
1301bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1302{
1303 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1304 loopTerminal.push(node->getTerminal());
1305
David Netoc22f37c2015-07-15 16:21:26 -04001306 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001307
1308 if (node->getTest()) {
1309 node->getTest()->traverse(this);
1310 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001311 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001312 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001313 } else {
1314 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001315 }
1316
David Netoc22f37c2015-07-15 16:21:26 -04001317 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001318 breakForLoop.push(true);
1319 node->getBody()->traverse(this);
1320 breakForLoop.pop();
1321 }
1322
1323 if (loopTerminal.top())
1324 loopTerminal.top()->traverse(this);
1325
1326 builder.closeLoop();
1327
1328 loopTerminal.pop();
1329
1330 return false;
1331}
1332
1333bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1334{
1335 if (node->getExpression())
1336 node->getExpression()->traverse(this);
1337
1338 switch (node->getFlowOp()) {
1339 case glslang::EOpKill:
1340 builder.makeDiscard();
1341 break;
1342 case glslang::EOpBreak:
1343 if (breakForLoop.top())
1344 builder.createLoopExit();
1345 else
1346 builder.addSwitchBreak();
1347 break;
1348 case glslang::EOpContinue:
1349 if (loopTerminal.top())
1350 loopTerminal.top()->traverse(this);
1351 builder.createLoopContinue();
1352 break;
1353 case glslang::EOpReturn:
1354 if (inMain)
1355 builder.makeMainReturn();
1356 else if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001357 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001358 else
1359 builder.makeReturn();
1360
1361 builder.clearAccessChain();
1362 break;
1363
1364 default:
1365 spv::MissingFunctionality("branch type");
1366 break;
1367 }
1368
1369 return false;
1370}
1371
1372spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1373{
1374 // First, steer off constants, which are not SPIR-V variables, but
1375 // can still have a mapping to a SPIR-V Id.
1376 if (node->getQualifier().storage == glslang::EvqConst) {
1377 int nextConst = 0;
1378 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1379 }
1380
1381 // Now, handle actual variables
1382 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1383 spv::Id spvType = convertGlslangToSpvType(node->getType());
1384
1385 const char* name = node->getName().c_str();
1386 if (glslang::IsAnonymous(name))
1387 name = "";
1388
1389 return builder.createVariable(storageClass, spvType, name);
1390}
1391
1392// Return type Id of the sampled type.
1393spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1394{
1395 switch (sampler.type) {
1396 case glslang::EbtFloat: return builder.makeFloatType(32);
1397 case glslang::EbtInt: return builder.makeIntType(32);
1398 case glslang::EbtUint: return builder.makeUintType(32);
1399 default:
1400 spv::MissingFunctionality("sampled type");
1401 return builder.makeFloatType(32);
1402 }
1403}
1404
John Kessenich31ed4832015-09-09 17:51:38 -06001405// Convert from a glslang type to an SPV type, by calling into
1406// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001407spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1408{
John Kessenich31ed4832015-09-09 17:51:38 -06001409 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1410}
1411
1412// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1413// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1414spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1415{
John Kessenich140f3df2015-06-26 16:58:36 -06001416 spv::Id spvType = 0;
1417
1418 switch (type.getBasicType()) {
1419 case glslang::EbtVoid:
1420 spvType = builder.makeVoidType();
1421 if (type.isArray())
1422 spv::MissingFunctionality("array of void");
1423 break;
1424 case glslang::EbtFloat:
1425 spvType = builder.makeFloatType(32);
1426 break;
1427 case glslang::EbtDouble:
1428 spvType = builder.makeFloatType(64);
1429 break;
1430 case glslang::EbtBool:
1431 spvType = builder.makeBoolType();
1432 break;
1433 case glslang::EbtInt:
1434 spvType = builder.makeIntType(32);
1435 break;
1436 case glslang::EbtUint:
1437 spvType = builder.makeUintType(32);
1438 break;
John Kessenich426394d2015-07-23 10:22:48 -06001439 case glslang::EbtAtomicUint:
1440 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1441 spvType = builder.makeUintType(32);
1442 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001443 case glslang::EbtSampler:
1444 {
1445 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001446 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
Rex Xufc618912015-09-09 16:42:49 +08001447 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich5e4b1242015-08-06 22:53:06 -06001448 // OpenGL "textures" need to be combined with a sampler
1449 if (! sampler.image)
1450 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001451 }
1452 break;
1453 case glslang::EbtStruct:
1454 case glslang::EbtBlock:
1455 {
1456 // If we've seen this struct type, return it
1457 const glslang::TTypeList* glslangStruct = type.getStruct();
1458 std::vector<spv::Id> structFields;
1459 spvType = structMap[glslangStruct];
1460 if (spvType)
1461 break;
1462
1463 // else, we haven't seen it...
1464
1465 // Create a vector of struct types for SPIR-V to consume
1466 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1467 if (type.getBasicType() == glslang::EbtBlock)
1468 memberRemapper[glslangStruct].resize(glslangStruct->size());
1469 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1470 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1471 if (glslangType.hiddenMember()) {
1472 ++memberDelta;
1473 if (type.getBasicType() == glslang::EbtBlock)
1474 memberRemapper[glslangStruct][i] = -1;
1475 } else {
1476 if (type.getBasicType() == glslang::EbtBlock)
1477 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001478 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001479 }
1480 }
1481
1482 // Make the SPIR-V type
1483 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1484 structMap[glslangStruct] = spvType;
1485
1486 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001487 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001488 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1489 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1490 int member = i;
1491 if (type.getBasicType() == glslang::EbtBlock)
1492 member = memberRemapper[glslangStruct][i];
1493 // using -1 above to indicate a hidden member
1494 if (member >= 0) {
1495 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1496 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1497 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1498 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1499 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1500 if (glslangType.getQualifier().hasLocation())
1501 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1502 if (glslangType.getQualifier().hasComponent())
1503 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1504 if (glslangType.getQualifier().hasXfbOffset())
1505 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001506 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001507 // figure out what to do with offset, which is accumulating
1508 int nextOffset;
1509 updateMemberOffset(type, glslangType, offset, nextOffset);
1510 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001511 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001512 offset = nextOffset;
1513 }
John Kessenich140f3df2015-06-26 16:58:36 -06001514
John Kessenich31ed4832015-09-09 17:51:38 -06001515 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001516 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1517 }
1518
John Kessenich140f3df2015-06-26 16:58:36 -06001519 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001520 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1521 if (builtIn != spv::BadValue)
1522 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001523 }
1524 }
1525
1526 // Decorate the structure
1527 addDecoration(spvType, TranslateLayoutDecoration(type));
1528 addDecoration(spvType, TranslateBlockDecoration(type));
1529 if (type.getQualifier().hasStream())
1530 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1531 if (glslangIntermediate->getXfbMode()) {
1532 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001533 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001534 if (type.getQualifier().hasXfbBuffer())
1535 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1536 }
1537 }
1538 break;
1539 default:
1540 spv::MissingFunctionality("basic type");
1541 break;
1542 }
1543
1544 if (type.isMatrix())
1545 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1546 else {
1547 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1548 if (type.getVectorSize() > 1)
1549 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1550 }
1551
1552 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001553 // Do all but the outer dimension
1554 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1555 assert(type.getArraySizes()->getDimSize(dim) > 0);
1556 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1557 }
John Kessenich31ed4832015-09-09 17:51:38 -06001558
John Kessenichc9a80832015-09-12 12:17:44 -06001559 // Do the outer dimension, which might not be known for a runtime-sized array
1560 if (type.isRuntimeSizedArray()) {
1561 spvType = builder.makeRuntimeArray(spvType);
1562 } else {
1563 assert(type.getOuterArraySize() > 0);
1564 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1565 }
1566
1567 // TODO: layout still needs to be done hierarchically for arrays of arrays, which
1568 // may still require additional "link time" support from the front-end
1569 // for arrays of arrays
John Kessenich31ed4832015-09-09 17:51:38 -06001570 if (explicitLayout)
1571 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001572 }
1573
1574 return spvType;
1575}
1576
John Kessenich31ed4832015-09-09 17:51:38 -06001577bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1578{
1579 return type.getBasicType() == glslang::EbtBlock &&
1580 type.getQualifier().layoutPacking != glslang::ElpShared &&
1581 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1582 (type.getQualifier().storage == glslang::EvqUniform ||
1583 type.getQualifier().storage == glslang::EvqBuffer);
1584}
1585
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001586// Given an array type, returns the integer stride required for that array
1587int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1588{
1589 glslang::TType derefType(arrayType, 0);
1590 int size;
1591 glslangIntermediate->getBaseAlignment(derefType, size, true);
1592 return size;
1593}
1594
1595// Given a matrix type, returns the integer stride required for that matrix
1596// when used as a member of an interface block
1597int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1598{
1599 int size;
1600 return glslangIntermediate->getBaseAlignment(matrixType, size, true);
1601}
1602
John Kessenich5e4b1242015-08-06 22:53:06 -06001603// Given a member type of a struct, realign the current offset for it, and compute
1604// the next (not yet aligned) offset for the next member, which will get aligned
1605// on the next call.
1606// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1607// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1608// -1 means a non-forced member offset (no decoration needed).
1609void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1610{
1611 // this will get a positive value when deemed necessary
1612 nextOffset = -1;
1613
1614 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1615 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1616
1617 // override anything in currentOffset with user-set offset
1618 if (memberType.getQualifier().hasOffset())
1619 currentOffset = memberType.getQualifier().layoutOffset;
1620
1621 // It could be that current linker usage in glslang updated all the layoutOffset,
1622 // in which case the following code does not matter. But, that's not quite right
1623 // once cross-compilation unit GLSL validation is done, as the original user
1624 // settings are needed in layoutOffset, and then the following will come into play.
1625
1626 if (! forceOffset) {
1627 if (! memberType.getQualifier().hasOffset())
1628 currentOffset = -1;
1629
1630 return;
1631 }
1632
1633 // Getting this far means we are forcing offsets
1634 if (currentOffset < 0)
1635 currentOffset = 0;
1636
1637 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1638 // but possibly not yet correctly aligned.
1639
1640 int memberSize;
1641 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1642 glslang::RoundToPow2(currentOffset, memberAlignment);
1643 nextOffset = currentOffset + memberSize;
1644}
1645
John Kessenich140f3df2015-06-26 16:58:36 -06001646bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1647{
1648 return node->getName() == "main(";
1649}
1650
1651// Make all the functions, skeletally, without actually visiting their bodies.
1652void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1653{
1654 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1655 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1656 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1657 continue;
1658
1659 // We're on a user function. Set up the basic interface for the function now,
1660 // so that it's available to call.
1661 // Translating the body will happen later.
1662 //
1663 // Typically (except for a "const in" parameter), an address will be passed to the
1664 // function. What it is an address of varies:
1665 //
1666 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1667 // so that write needs to be to a copy, hence the address of a copy works.
1668 //
1669 // - "const in" parameters can just be the r-value, as no writes need occur.
1670 //
1671 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1672 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1673
1674 std::vector<spv::Id> paramTypes;
1675 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1676
1677 for (int p = 0; p < (int)parameters.size(); ++p) {
1678 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1679 spv::Id typeId = convertGlslangToSpvType(paramType);
1680 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1681 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1682 else
1683 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1684 paramTypes.push_back(typeId);
1685 }
1686
1687 spv::Block* functionBlock;
1688 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1689 paramTypes, &functionBlock);
1690
1691 // Track function to emit/call later
1692 functionMap[glslFunction->getName().c_str()] = function;
1693
1694 // Set the parameter id's
1695 for (int p = 0; p < (int)parameters.size(); ++p) {
1696 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1697 // give a name too
1698 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1699 }
1700 }
1701}
1702
1703// Process all the initializers, while skipping the functions and link objects
1704void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1705{
1706 builder.setBuildPoint(shaderEntry->getLastBlock());
1707 for (int i = 0; i < (int)initializers.size(); ++i) {
1708 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1709 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1710
1711 // We're on a top-level node that's not a function. Treat as an initializer, whose
1712 // code goes into the beginning of main.
1713 initializer->traverse(this);
1714 }
1715 }
1716}
1717
1718// Process all the functions, while skipping initializers.
1719void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1720{
1721 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1722 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1723 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1724 node->traverse(this);
1725 }
1726}
1727
1728void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1729{
1730 // SPIR-V functions should already be in the functionMap from the prepass
1731 // that called makeFunctions().
1732 spv::Function* function = functionMap[node->getName().c_str()];
1733 spv::Block* functionBlock = function->getEntryBlock();
1734 builder.setBuildPoint(functionBlock);
1735}
1736
Rex Xu04db3f52015-09-16 11:44:02 +08001737void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001738{
Rex Xufc618912015-09-09 16:42:49 +08001739 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001740 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1741 builder.clearAccessChain();
1742 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001743
1744 // Special case l-value operands
1745 bool lvalue = false;
1746 switch (node.getOp()) {
1747 case glslang::EOpImageAtomicAdd:
1748 case glslang::EOpImageAtomicMin:
1749 case glslang::EOpImageAtomicMax:
1750 case glslang::EOpImageAtomicAnd:
1751 case glslang::EOpImageAtomicOr:
1752 case glslang::EOpImageAtomicXor:
1753 case glslang::EOpImageAtomicExchange:
1754 case glslang::EOpImageAtomicCompSwap:
1755 if (i == 0)
1756 lvalue = true;
1757 break;
1758 default:
1759 break;
1760 }
1761
1762 if (lvalue) {
1763 arguments.push_back(builder.accessChainGetLValue());
Rex Xu30f92582015-09-14 10:38:56 +08001764 } else {
1765 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
Rex Xufc618912015-09-09 16:42:49 +08001766 }
John Kessenich140f3df2015-06-26 16:58:36 -06001767 }
1768}
1769
John Kessenichfc51d282015-08-19 13:34:18 -06001770void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001771{
John Kessenichfc51d282015-08-19 13:34:18 -06001772 builder.clearAccessChain();
1773 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001774 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001775}
John Kessenich140f3df2015-06-26 16:58:36 -06001776
John Kessenichfc51d282015-08-19 13:34:18 -06001777spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1778{
Rex Xufc618912015-09-09 16:42:49 +08001779 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001780 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001781 }
1782
John Kessenichfc51d282015-08-19 13:34:18 -06001783 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001784 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1785 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1786 std::vector<spv::Id> arguments;
1787 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001788 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001789 else
1790 translateArguments(*node->getAsUnaryNode(), arguments);
1791 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1792
1793 spv::Builder::TextureParameters params = { };
1794 params.sampler = arguments[0];
1795
Rex Xu04db3f52015-09-16 11:44:02 +08001796 glslang::TCrackedTextureOp cracked;
1797 node->crackTexture(sampler, cracked);
1798
John Kessenichfc51d282015-08-19 13:34:18 -06001799 // Check for queries
1800 if (cracked.query) {
1801 switch (node->getOp()) {
1802 case glslang::EOpImageQuerySize:
1803 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001804 if (arguments.size() > 1) {
1805 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001806 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001807 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001808 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001809 case glslang::EOpImageQuerySamples:
1810 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001811 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001812 case glslang::EOpTextureQueryLod:
1813 params.coords = arguments[1];
1814 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1815 case glslang::EOpTextureQueryLevels:
1816 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1817 default:
1818 assert(0);
1819 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001820 }
John Kessenich140f3df2015-06-26 16:58:36 -06001821 }
1822
Rex Xufc618912015-09-09 16:42:49 +08001823 // Check for image functions other than queries
1824 if (node->isImage()) {
1825 if (node->getOp() == glslang::EOpImageLoad) {
1826 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), arguments);
1827 }
1828 else if (node->getOp() == glslang::EOpImageStore) {
1829 builder.createNoResultOp(spv::OpImageWrite, arguments);
1830 return spv::NoResult;
1831 }
1832 else {
1833 // Process image atomic operations. GLSL "IMAGE_PARAMS" will involve in constructing an image texel
1834 // pointer and this pointer, as the first source operand, is required by SPIR-V atomic operations.
1835 std::vector<spv::Id> imageParams;
1836 auto opIt = arguments.begin();
1837 imageParams.push_back(*(opIt++));
1838 imageParams.push_back(*(opIt++));
1839 imageParams.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001840
Rex Xufc618912015-09-09 16:42:49 +08001841 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
1842 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, imageParams);
1843
1844 std::vector<spv::Id> operands;
1845 operands.push_back(pointer);
1846 for (; opIt != arguments.end(); ++opIt)
1847 operands.push_back(*opIt);
1848
Rex Xu04db3f52015-09-16 11:44:02 +08001849 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001850 }
1851 }
1852
1853 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001854 if (cracked.gather)
1855 spv::MissingFunctionality("texture gather");
1856
1857 // check for bias argument
1858 bool bias = false;
1859 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1860 int nonBiasArgCount = 2;
1861 if (cracked.offset)
1862 ++nonBiasArgCount;
1863 if (cracked.grad)
1864 nonBiasArgCount += 2;
1865
1866 if ((int)arguments.size() > nonBiasArgCount)
1867 bias = true;
1868 }
1869
1870 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1871
1872 // set the rest of the arguments
1873 params.coords = arguments[1];
1874 int extraArgs = 0;
1875 if (cubeCompare)
1876 params.Dref = arguments[2];
1877 else if (sampler.shadow) {
1878 std::vector<spv::Id> indexes;
1879 int comp;
1880 if (cracked.proj)
1881 comp = 3;
1882 else
1883 comp = builder.getNumComponents(params.coords) - 1;
1884 indexes.push_back(comp);
1885 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1886 }
1887 if (cracked.lod) {
1888 params.lod = arguments[2];
1889 ++extraArgs;
Rex Xu04db3f52015-09-16 11:44:02 +08001890 } else if (cracked.sample) {
1891 params.sample = arguments[2]; // For MS, sample should be specified
1892 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001893 }
1894 if (cracked.grad) {
1895 params.gradX = arguments[2 + extraArgs];
1896 params.gradY = arguments[3 + extraArgs];
1897 extraArgs += 2;
1898 }
1899 //if (gather && compare) {
1900 // params.compare = arguments[2 + extraArgs];
1901 // ++extraArgs;
1902 //}
1903 if (cracked.offset || cracked.offsets) {
1904 params.offset = arguments[2 + extraArgs];
1905 ++extraArgs;
1906 }
1907 if (bias) {
1908 params.bias = arguments[2 + extraArgs];
1909 ++extraArgs;
1910 }
1911
Jason Ekstrand18b9fbd2015-09-05 14:14:48 -07001912 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001913}
1914
1915spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1916{
1917 // Grab the function's pointer from the previously created function
1918 spv::Function* function = functionMap[node->getName().c_str()];
1919 if (! function)
1920 return 0;
1921
1922 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1923 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1924
1925 // See comments in makeFunctions() for details about the semantics for parameter passing.
1926 //
1927 // These imply we need a four step process:
1928 // 1. Evaluate the arguments
1929 // 2. Allocate and make copies of in, out, and inout arguments
1930 // 3. Make the call
1931 // 4. Copy back the results
1932
1933 // 1. Evaluate the arguments
1934 std::vector<spv::Builder::AccessChain> lValues;
1935 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06001936 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06001937 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1938 // build l-value
1939 builder.clearAccessChain();
1940 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001941 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001942 // keep outputs as l-values, evaluate input-only as r-values
1943 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1944 // save l-value
1945 lValues.push_back(builder.getAccessChain());
1946 } else {
1947 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06001948 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06001949 }
1950 }
1951
1952 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1953 // copy the original into that space.
1954 //
1955 // Also, build up the list of actual arguments to pass in for the call
1956 int lValueCount = 0;
1957 int rValueCount = 0;
1958 std::vector<spv::Id> spvArgs;
1959 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1960 spv::Id arg;
1961 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1962 // need space to hold the copy
1963 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
1964 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
1965 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
1966 // need to copy the input into output space
1967 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06001968 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06001969 builder.createStore(copy, arg);
1970 }
1971 ++lValueCount;
1972 } else {
1973 arg = rValues[rValueCount];
1974 ++rValueCount;
1975 }
1976 spvArgs.push_back(arg);
1977 }
1978
1979 // 3. Make the call.
1980 spv::Id result = builder.createFunctionCall(function, spvArgs);
1981
1982 // 4. Copy back out an "out" arguments.
1983 lValueCount = 0;
1984 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1985 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1986 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
1987 spv::Id copy = builder.createLoad(spvArgs[a]);
1988 builder.setAccessChain(lValues[lValueCount]);
1989 builder.accessChainStore(copy);
1990 }
1991 ++lValueCount;
1992 }
1993 }
1994
1995 return result;
1996}
1997
1998// Translate AST operation to SPV operation, already having SPV-based operands/types.
1999spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2000 spv::Id typeId, spv::Id left, spv::Id right,
2001 glslang::TBasicType typeProxy, bool reduceComparison)
2002{
2003 bool isUnsigned = typeProxy == glslang::EbtUint;
2004 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2005
2006 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002007 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002008 bool comparison = false;
2009
2010 switch (op) {
2011 case glslang::EOpAdd:
2012 case glslang::EOpAddAssign:
2013 if (isFloat)
2014 binOp = spv::OpFAdd;
2015 else
2016 binOp = spv::OpIAdd;
2017 break;
2018 case glslang::EOpSub:
2019 case glslang::EOpSubAssign:
2020 if (isFloat)
2021 binOp = spv::OpFSub;
2022 else
2023 binOp = spv::OpISub;
2024 break;
2025 case glslang::EOpMul:
2026 case glslang::EOpMulAssign:
2027 if (isFloat)
2028 binOp = spv::OpFMul;
2029 else
2030 binOp = spv::OpIMul;
2031 break;
2032 case glslang::EOpVectorTimesScalar:
2033 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002034 if (isFloat) {
2035 if (builder.isVector(right))
2036 std::swap(left, right);
2037 assert(builder.isScalar(right));
2038 needMatchingVectors = false;
2039 binOp = spv::OpVectorTimesScalar;
2040 } else
2041 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002042 break;
2043 case glslang::EOpVectorTimesMatrix:
2044 case glslang::EOpVectorTimesMatrixAssign:
2045 assert(builder.isVector(left));
2046 assert(builder.isMatrix(right));
2047 binOp = spv::OpVectorTimesMatrix;
2048 break;
2049 case glslang::EOpMatrixTimesVector:
2050 assert(builder.isMatrix(left));
2051 assert(builder.isVector(right));
2052 binOp = spv::OpMatrixTimesVector;
2053 break;
2054 case glslang::EOpMatrixTimesScalar:
2055 case glslang::EOpMatrixTimesScalarAssign:
2056 if (builder.isMatrix(right))
2057 std::swap(left, right);
2058 assert(builder.isScalar(right));
2059 binOp = spv::OpMatrixTimesScalar;
2060 break;
2061 case glslang::EOpMatrixTimesMatrix:
2062 case glslang::EOpMatrixTimesMatrixAssign:
2063 assert(builder.isMatrix(left));
2064 assert(builder.isMatrix(right));
2065 binOp = spv::OpMatrixTimesMatrix;
2066 break;
2067 case glslang::EOpOuterProduct:
2068 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002069 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002070 break;
2071
2072 case glslang::EOpDiv:
2073 case glslang::EOpDivAssign:
2074 if (isFloat)
2075 binOp = spv::OpFDiv;
2076 else if (isUnsigned)
2077 binOp = spv::OpUDiv;
2078 else
2079 binOp = spv::OpSDiv;
2080 break;
2081 case glslang::EOpMod:
2082 case glslang::EOpModAssign:
2083 if (isFloat)
2084 binOp = spv::OpFMod;
2085 else if (isUnsigned)
2086 binOp = spv::OpUMod;
2087 else
2088 binOp = spv::OpSMod;
2089 break;
2090 case glslang::EOpRightShift:
2091 case glslang::EOpRightShiftAssign:
2092 if (isUnsigned)
2093 binOp = spv::OpShiftRightLogical;
2094 else
2095 binOp = spv::OpShiftRightArithmetic;
2096 break;
2097 case glslang::EOpLeftShift:
2098 case glslang::EOpLeftShiftAssign:
2099 binOp = spv::OpShiftLeftLogical;
2100 break;
2101 case glslang::EOpAnd:
2102 case glslang::EOpAndAssign:
2103 binOp = spv::OpBitwiseAnd;
2104 break;
2105 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002106 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002107 binOp = spv::OpLogicalAnd;
2108 break;
2109 case glslang::EOpInclusiveOr:
2110 case glslang::EOpInclusiveOrAssign:
2111 binOp = spv::OpBitwiseOr;
2112 break;
2113 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002114 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002115 binOp = spv::OpLogicalOr;
2116 break;
2117 case glslang::EOpExclusiveOr:
2118 case glslang::EOpExclusiveOrAssign:
2119 binOp = spv::OpBitwiseXor;
2120 break;
2121 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002122 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002123 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002124 break;
2125
2126 case glslang::EOpLessThan:
2127 case glslang::EOpGreaterThan:
2128 case glslang::EOpLessThanEqual:
2129 case glslang::EOpGreaterThanEqual:
2130 case glslang::EOpEqual:
2131 case glslang::EOpNotEqual:
2132 case glslang::EOpVectorEqual:
2133 case glslang::EOpVectorNotEqual:
2134 comparison = true;
2135 break;
2136 default:
2137 break;
2138 }
2139
2140 if (binOp != spv::OpNop) {
2141 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2142 switch (binOp) {
2143 case spv::OpMatrixTimesScalar:
2144 case spv::OpVectorTimesMatrix:
2145 case spv::OpMatrixTimesVector:
2146 case spv::OpMatrixTimesMatrix:
2147 break;
2148 case spv::OpFDiv:
2149 // turn it into a multiply...
2150 assert(builder.isMatrix(left) && builder.isScalar(right));
2151 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2152 binOp = spv::OpFMul;
2153 break;
2154 default:
2155 spv::MissingFunctionality("binary operation on matrix");
2156 break;
2157 }
2158
2159 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2160 builder.setPrecision(id, precision);
2161
2162 return id;
2163 }
2164
2165 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002166 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002167 builder.promoteScalar(precision, left, right);
2168
2169 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2170 builder.setPrecision(id, precision);
2171
2172 return id;
2173 }
2174
2175 if (! comparison)
2176 return 0;
2177
2178 // Comparison instructions
2179
2180 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2181 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2182
2183 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2184 }
2185
2186 switch (op) {
2187 case glslang::EOpLessThan:
2188 if (isFloat)
2189 binOp = spv::OpFOrdLessThan;
2190 else if (isUnsigned)
2191 binOp = spv::OpULessThan;
2192 else
2193 binOp = spv::OpSLessThan;
2194 break;
2195 case glslang::EOpGreaterThan:
2196 if (isFloat)
2197 binOp = spv::OpFOrdGreaterThan;
2198 else if (isUnsigned)
2199 binOp = spv::OpUGreaterThan;
2200 else
2201 binOp = spv::OpSGreaterThan;
2202 break;
2203 case glslang::EOpLessThanEqual:
2204 if (isFloat)
2205 binOp = spv::OpFOrdLessThanEqual;
2206 else if (isUnsigned)
2207 binOp = spv::OpULessThanEqual;
2208 else
2209 binOp = spv::OpSLessThanEqual;
2210 break;
2211 case glslang::EOpGreaterThanEqual:
2212 if (isFloat)
2213 binOp = spv::OpFOrdGreaterThanEqual;
2214 else if (isUnsigned)
2215 binOp = spv::OpUGreaterThanEqual;
2216 else
2217 binOp = spv::OpSGreaterThanEqual;
2218 break;
2219 case glslang::EOpEqual:
2220 case glslang::EOpVectorEqual:
2221 if (isFloat)
2222 binOp = spv::OpFOrdEqual;
2223 else
2224 binOp = spv::OpIEqual;
2225 break;
2226 case glslang::EOpNotEqual:
2227 case glslang::EOpVectorNotEqual:
2228 if (isFloat)
2229 binOp = spv::OpFOrdNotEqual;
2230 else
2231 binOp = spv::OpINotEqual;
2232 break;
2233 default:
2234 break;
2235 }
2236
2237 if (binOp != spv::OpNop) {
2238 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2239 builder.setPrecision(id, precision);
2240
2241 return id;
2242 }
2243
2244 return 0;
2245}
2246
Rex Xu04db3f52015-09-16 11:44:02 +08002247spv::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 -06002248{
2249 spv::Op unaryOp = spv::OpNop;
2250 int libCall = -1;
Rex Xu04db3f52015-09-16 11:44:02 +08002251 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002252
2253 switch (op) {
2254 case glslang::EOpNegative:
2255 if (isFloat)
2256 unaryOp = spv::OpFNegate;
2257 else
2258 unaryOp = spv::OpSNegate;
2259 break;
2260
2261 case glslang::EOpLogicalNot:
2262 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002263 unaryOp = spv::OpLogicalNot;
2264 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002265 case glslang::EOpBitwiseNot:
2266 unaryOp = spv::OpNot;
2267 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002268
John Kessenich140f3df2015-06-26 16:58:36 -06002269 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002270 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002271 break;
2272 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002273 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002274 break;
2275 case glslang::EOpTranspose:
2276 unaryOp = spv::OpTranspose;
2277 break;
2278
2279 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002280 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002281 break;
2282 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002283 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002284 break;
2285 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002286 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002287 break;
2288 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002289 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002290 break;
2291 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002292 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002293 break;
2294 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002295 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002296 break;
2297 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002298 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002299 break;
2300 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002301 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002302 break;
2303
2304 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002305 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002306 break;
2307 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002308 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002309 break;
2310 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002311 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002312 break;
2313 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002314 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002315 break;
2316 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002317 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002318 break;
2319 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002320 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002321 break;
2322
2323 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002324 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002325 break;
2326 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002327 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002328 break;
2329
2330 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002331 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002332 break;
2333 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002334 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002335 break;
2336 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002337 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002338 break;
2339 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002340 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002341 break;
2342 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002343 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002344 break;
2345 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002346 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002347 break;
2348
2349 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002350 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002351 break;
2352 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002353 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002354 break;
2355 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002356 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002357 break;
2358 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002359 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002360 break;
2361 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002362 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002363 break;
2364 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002365 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002366 break;
2367
2368 case glslang::EOpIsNan:
2369 unaryOp = spv::OpIsNan;
2370 break;
2371 case glslang::EOpIsInf:
2372 unaryOp = spv::OpIsInf;
2373 break;
2374
John Kessenich140f3df2015-06-26 16:58:36 -06002375 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002376 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002377 break;
2378 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002379 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002380 break;
2381 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002382 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002383 break;
2384 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002385 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002386 break;
2387 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002388 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002389 break;
2390 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002391 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002392 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002393 case glslang::EOpPackSnorm4x8:
2394 libCall = spv::GLSLstd450PackSnorm4x8;
2395 break;
2396 case glslang::EOpUnpackSnorm4x8:
2397 libCall = spv::GLSLstd450UnpackSnorm4x8;
2398 break;
2399 case glslang::EOpPackUnorm4x8:
2400 libCall = spv::GLSLstd450PackUnorm4x8;
2401 break;
2402 case glslang::EOpUnpackUnorm4x8:
2403 libCall = spv::GLSLstd450UnpackUnorm4x8;
2404 break;
2405 case glslang::EOpPackDouble2x32:
2406 libCall = spv::GLSLstd450PackDouble2x32;
2407 break;
2408 case glslang::EOpUnpackDouble2x32:
2409 libCall = spv::GLSLstd450UnpackDouble2x32;
2410 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002411
2412 case glslang::EOpDPdx:
2413 unaryOp = spv::OpDPdx;
2414 break;
2415 case glslang::EOpDPdy:
2416 unaryOp = spv::OpDPdy;
2417 break;
2418 case glslang::EOpFwidth:
2419 unaryOp = spv::OpFwidth;
2420 break;
2421 case glslang::EOpDPdxFine:
2422 unaryOp = spv::OpDPdxFine;
2423 break;
2424 case glslang::EOpDPdyFine:
2425 unaryOp = spv::OpDPdyFine;
2426 break;
2427 case glslang::EOpFwidthFine:
2428 unaryOp = spv::OpFwidthFine;
2429 break;
2430 case glslang::EOpDPdxCoarse:
2431 unaryOp = spv::OpDPdxCoarse;
2432 break;
2433 case glslang::EOpDPdyCoarse:
2434 unaryOp = spv::OpDPdyCoarse;
2435 break;
2436 case glslang::EOpFwidthCoarse:
2437 unaryOp = spv::OpFwidthCoarse;
2438 break;
2439
2440 case glslang::EOpAny:
2441 unaryOp = spv::OpAny;
2442 break;
2443 case glslang::EOpAll:
2444 unaryOp = spv::OpAll;
2445 break;
2446
2447 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002448 if (isFloat)
2449 libCall = spv::GLSLstd450FAbs;
2450 else
2451 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002452 break;
2453 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002454 if (isFloat)
2455 libCall = spv::GLSLstd450FSign;
2456 else
2457 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002458 break;
2459
John Kessenichfc51d282015-08-19 13:34:18 -06002460 case glslang::EOpAtomicCounterIncrement:
2461 case glslang::EOpAtomicCounterDecrement:
2462 case glslang::EOpAtomicCounter:
2463 {
2464 // Handle all of the atomics in one place, in createAtomicOperation()
2465 std::vector<spv::Id> operands;
2466 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002467 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002468 }
2469
2470 case glslang::EOpImageLoad:
2471 unaryOp = spv::OpImageRead;
2472 break;
2473
2474 case glslang::EOpBitFieldReverse:
2475 unaryOp = spv::OpBitReverse;
2476 break;
2477 case glslang::EOpBitCount:
2478 unaryOp = spv::OpBitCount;
2479 break;
2480 case glslang::EOpFindLSB:
2481 libCall = spv::GLSLstd450FindILSB;
2482 break;
2483 case glslang::EOpFindMSB:
2484 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2485 libCall = spv::GLSLstd450FindSMSB;
2486 break;
2487
John Kessenich140f3df2015-06-26 16:58:36 -06002488 default:
2489 return 0;
2490 }
2491
2492 spv::Id id;
2493 if (libCall >= 0) {
2494 std::vector<spv::Id> args;
2495 args.push_back(operand);
2496 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2497 } else
2498 id = builder.createUnaryOp(unaryOp, typeId, operand);
2499
2500 builder.setPrecision(id, precision);
2501
2502 return id;
2503}
2504
2505spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2506{
2507 spv::Op convOp = spv::OpNop;
2508 spv::Id zero = 0;
2509 spv::Id one = 0;
2510
2511 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2512
2513 switch (op) {
2514 case glslang::EOpConvIntToBool:
2515 case glslang::EOpConvUintToBool:
2516 zero = builder.makeUintConstant(0);
2517 zero = makeSmearedConstant(zero, vectorSize);
2518 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2519
2520 case glslang::EOpConvFloatToBool:
2521 zero = builder.makeFloatConstant(0.0F);
2522 zero = makeSmearedConstant(zero, vectorSize);
2523 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2524
2525 case glslang::EOpConvDoubleToBool:
2526 zero = builder.makeDoubleConstant(0.0);
2527 zero = makeSmearedConstant(zero, vectorSize);
2528 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2529
2530 case glslang::EOpConvBoolToFloat:
2531 convOp = spv::OpSelect;
2532 zero = builder.makeFloatConstant(0.0);
2533 one = builder.makeFloatConstant(1.0);
2534 break;
2535 case glslang::EOpConvBoolToDouble:
2536 convOp = spv::OpSelect;
2537 zero = builder.makeDoubleConstant(0.0);
2538 one = builder.makeDoubleConstant(1.0);
2539 break;
2540 case glslang::EOpConvBoolToInt:
2541 zero = builder.makeIntConstant(0);
2542 one = builder.makeIntConstant(1);
2543 convOp = spv::OpSelect;
2544 break;
2545 case glslang::EOpConvBoolToUint:
2546 zero = builder.makeUintConstant(0);
2547 one = builder.makeUintConstant(1);
2548 convOp = spv::OpSelect;
2549 break;
2550
2551 case glslang::EOpConvIntToFloat:
2552 case glslang::EOpConvIntToDouble:
2553 convOp = spv::OpConvertSToF;
2554 break;
2555
2556 case glslang::EOpConvUintToFloat:
2557 case glslang::EOpConvUintToDouble:
2558 convOp = spv::OpConvertUToF;
2559 break;
2560
2561 case glslang::EOpConvDoubleToFloat:
2562 case glslang::EOpConvFloatToDouble:
2563 convOp = spv::OpFConvert;
2564 break;
2565
2566 case glslang::EOpConvFloatToInt:
2567 case glslang::EOpConvDoubleToInt:
2568 convOp = spv::OpConvertFToS;
2569 break;
2570
2571 case glslang::EOpConvUintToInt:
2572 case glslang::EOpConvIntToUint:
2573 convOp = spv::OpBitcast;
2574 break;
2575
2576 case glslang::EOpConvFloatToUint:
2577 case glslang::EOpConvDoubleToUint:
2578 convOp = spv::OpConvertFToU;
2579 break;
2580 default:
2581 break;
2582 }
2583
2584 spv::Id result = 0;
2585 if (convOp == spv::OpNop)
2586 return result;
2587
2588 if (convOp == spv::OpSelect) {
2589 zero = makeSmearedConstant(zero, vectorSize);
2590 one = makeSmearedConstant(one, vectorSize);
2591 result = builder.createTriOp(convOp, destType, operand, one, zero);
2592 } else
2593 result = builder.createUnaryOp(convOp, destType, operand);
2594
2595 builder.setPrecision(result, precision);
2596
2597 return result;
2598}
2599
2600spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2601{
2602 if (vectorSize == 0)
2603 return constant;
2604
2605 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2606 std::vector<spv::Id> components;
2607 for (int c = 0; c < vectorSize; ++c)
2608 components.push_back(constant);
2609 return builder.makeCompositeConstant(vectorTypeId, components);
2610}
2611
John Kessenich426394d2015-07-23 10:22:48 -06002612// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002613spv::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 -06002614{
2615 spv::Op opCode = spv::OpNop;
2616
2617 switch (op) {
2618 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002619 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002620 opCode = spv::OpAtomicIAdd;
2621 break;
2622 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002623 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002624 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002625 break;
2626 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002627 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002628 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002629 break;
2630 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002631 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002632 opCode = spv::OpAtomicAnd;
2633 break;
2634 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002635 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002636 opCode = spv::OpAtomicOr;
2637 break;
2638 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002639 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002640 opCode = spv::OpAtomicXor;
2641 break;
2642 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002643 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002644 opCode = spv::OpAtomicExchange;
2645 break;
2646 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002647 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002648 opCode = spv::OpAtomicCompareExchange;
2649 break;
2650 case glslang::EOpAtomicCounterIncrement:
2651 opCode = spv::OpAtomicIIncrement;
2652 break;
2653 case glslang::EOpAtomicCounterDecrement:
2654 opCode = spv::OpAtomicIDecrement;
2655 break;
2656 case glslang::EOpAtomicCounter:
2657 opCode = spv::OpAtomicLoad;
2658 break;
2659 default:
2660 spv::MissingFunctionality("missing nested atomic");
2661 break;
2662 }
2663
2664 // Sort out the operands
2665 // - mapping from glslang -> SPV
2666 // - there are extra SPV operands with no glslang source
2667 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2668 auto opIt = operands.begin(); // walk the glslang operands
2669 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002670
2671 // Add scope and memory semantics
2672 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2673 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2674 if (opCode == spv::OpAtomicCompareExchange) {
2675 // There are 2 memory semantics for compare-exchange
2676 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
2677 }
John Kessenich426394d2015-07-23 10:22:48 -06002678
2679 // Add the rest of the operands, skipping the first one, which was dealt with above.
2680 // For some ops, there are none, for some 1, for compare-exchange, 2.
2681 for (; opIt != operands.end(); ++opIt)
2682 spvAtomicOperands.push_back(*opIt);
2683
2684 return builder.createOp(opCode, typeId, spvAtomicOperands);
2685}
2686
John Kessenich5e4b1242015-08-06 22:53:06 -06002687spv::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 -06002688{
John Kessenich5e4b1242015-08-06 22:53:06 -06002689 bool isUnsigned = typeProxy == glslang::EbtUint;
2690 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2691
John Kessenich140f3df2015-06-26 16:58:36 -06002692 spv::Op opCode = spv::OpNop;
2693 int libCall = -1;
2694
2695 switch (op) {
2696 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002697 if (isFloat)
2698 libCall = spv::GLSLstd450FMin;
2699 else if (isUnsigned)
2700 libCall = spv::GLSLstd450UMin;
2701 else
2702 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002703 break;
2704 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002705 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002706 break;
2707 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 if (isFloat)
2709 libCall = spv::GLSLstd450FMax;
2710 else if (isUnsigned)
2711 libCall = spv::GLSLstd450UMax;
2712 else
2713 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002714 break;
2715 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002716 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002717 break;
2718 case glslang::EOpDot:
2719 opCode = spv::OpDot;
2720 break;
2721 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002722 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002723 break;
2724
2725 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002726 if (isFloat)
2727 libCall = spv::GLSLstd450FClamp;
2728 else if (isUnsigned)
2729 libCall = spv::GLSLstd450UClamp;
2730 else
2731 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002732 break;
2733 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002734 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002735 break;
2736 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002737 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002738 break;
2739 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002740 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002741 break;
2742
2743 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002744 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002745 break;
2746 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002747 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002748 break;
2749 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002750 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002751 break;
2752 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002753 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002754 break;
2755 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002756 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002757 break;
John Kessenich426394d2015-07-23 10:22:48 -06002758
John Kessenich140f3df2015-06-26 16:58:36 -06002759 default:
2760 return 0;
2761 }
2762
2763 spv::Id id = 0;
2764 if (libCall >= 0)
2765 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2766 else {
2767 switch (operands.size()) {
2768 case 0:
2769 // should all be handled by visitAggregate and createNoArgOperation
2770 assert(0);
2771 return 0;
2772 case 1:
2773 // should all be handled by createUnaryOperation
2774 assert(0);
2775 return 0;
2776 case 2:
2777 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2778 break;
2779 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002780 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002781 break;
2782 default:
2783 // These do not exist yet
2784 assert(0 && "operation with more than 3 operands");
2785 break;
2786 }
2787 }
2788
2789 builder.setPrecision(id, precision);
2790
2791 return id;
2792}
2793
2794// Intrinsics with no arguments, no return value, and no precision.
2795spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2796{
2797 // TODO: get the barrier operands correct
2798
2799 switch (op) {
2800 case glslang::EOpEmitVertex:
2801 builder.createNoResultOp(spv::OpEmitVertex);
2802 return 0;
2803 case glslang::EOpEndPrimitive:
2804 builder.createNoResultOp(spv::OpEndPrimitive);
2805 return 0;
2806 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002807 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2808 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002809 return 0;
2810 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002811 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002812 return 0;
2813 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002814 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002815 return 0;
2816 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002817 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002818 return 0;
2819 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002820 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002821 return 0;
2822 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002823 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002824 return 0;
2825 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002826 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002827 return 0;
2828 default:
2829 spv::MissingFunctionality("operation with no arguments");
2830 return 0;
2831 }
2832}
2833
2834spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2835{
John Kessenich2f273362015-07-18 22:34:27 -06002836 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002837 spv::Id id;
2838 if (symbolValues.end() != iter) {
2839 id = iter->second;
2840 return id;
2841 }
2842
2843 // it was not found, create it
2844 id = createSpvVariable(symbol);
2845 symbolValues[symbol->getId()] = id;
2846
2847 if (! symbol->getType().isStruct()) {
2848 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2849 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2850 if (symbol->getQualifier().hasLocation())
2851 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2852 if (symbol->getQualifier().hasIndex())
2853 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2854 if (symbol->getQualifier().hasComponent())
2855 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2856 if (glslangIntermediate->getXfbMode()) {
2857 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002858 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002859 if (symbol->getQualifier().hasXfbBuffer())
2860 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2861 if (symbol->getQualifier().hasXfbOffset())
2862 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2863 }
2864 }
2865
2866 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2867 if (symbol->getQualifier().hasStream())
2868 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2869 if (symbol->getQualifier().hasSet())
2870 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2871 if (symbol->getQualifier().hasBinding())
2872 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2873 if (glslangIntermediate->getXfbMode()) {
2874 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002875 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002876 if (symbol->getQualifier().hasXfbBuffer())
2877 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2878 }
2879
2880 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002881 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002882 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002883 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002884
2885 if (linkageOnly)
2886 builder.addDecoration(id, spv::DecorationNoStaticUse);
2887
2888 return id;
2889}
2890
2891void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2892{
2893 if (dec != spv::BadValue)
2894 builder.addDecoration(id, dec);
2895}
2896
2897void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2898{
2899 if (dec != spv::BadValue)
2900 builder.addMemberDecoration(id, (unsigned)member, dec);
2901}
2902
2903// Use 'consts' as the flattened glslang source of scalar constants to recursively
2904// build the aggregate SPIR-V constant.
2905//
2906// If there are not enough elements present in 'consts', 0 will be substituted;
2907// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2908//
2909spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2910{
2911 // vector of constants for SPIR-V
2912 std::vector<spv::Id> spvConsts;
2913
2914 // Type is used for struct and array constants
2915 spv::Id typeId = convertGlslangToSpvType(glslangType);
2916
2917 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002918 glslang::TType elementType(glslangType, 0);
2919 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002920 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2921 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002922 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002923 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2924 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2925 } else if (glslangType.getStruct()) {
2926 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2927 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2928 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2929 } else if (glslangType.isVector()) {
2930 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2931 bool zero = nextConst >= consts.size();
2932 switch (glslangType.getBasicType()) {
2933 case glslang::EbtInt:
2934 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2935 break;
2936 case glslang::EbtUint:
2937 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2938 break;
2939 case glslang::EbtFloat:
2940 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2941 break;
2942 case glslang::EbtDouble:
2943 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2944 break;
2945 case glslang::EbtBool:
2946 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2947 break;
2948 default:
2949 spv::MissingFunctionality("constant vector type");
2950 break;
2951 }
2952 ++nextConst;
2953 }
2954 } else {
2955 // we have a non-aggregate (scalar) constant
2956 bool zero = nextConst >= consts.size();
2957 spv::Id scalar = 0;
2958 switch (glslangType.getBasicType()) {
2959 case glslang::EbtInt:
2960 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
2961 break;
2962 case glslang::EbtUint:
2963 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
2964 break;
2965 case glslang::EbtFloat:
2966 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
2967 break;
2968 case glslang::EbtDouble:
2969 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
2970 break;
2971 case glslang::EbtBool:
2972 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
2973 break;
2974 default:
2975 spv::MissingFunctionality("constant scalar type");
2976 break;
2977 }
2978 ++nextConst;
2979 return scalar;
2980 }
2981
2982 return builder.makeCompositeConstant(typeId, spvConsts);
2983}
2984
2985}; // end anonymous namespace
2986
2987namespace glslang {
2988
John Kessenich68d78fd2015-07-12 19:28:10 -06002989void GetSpirvVersion(std::string& version)
2990{
John Kessenich9e55f632015-07-15 10:03:39 -06002991 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06002992 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06002993 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06002994 version = buf;
2995}
2996
John Kessenich140f3df2015-06-26 16:58:36 -06002997// Write SPIR-V out to a binary file
2998void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
2999{
3000 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003001 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003002 for (int i = 0; i < (int)spirv.size(); ++i) {
3003 unsigned int word = spirv[i];
3004 out.write((const char*)&word, 4);
3005 }
3006 out.close();
3007}
3008
3009//
3010// Set up the glslang traversal
3011//
3012void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3013{
3014 TIntermNode* root = intermediate.getTreeRoot();
3015
3016 if (root == 0)
3017 return;
3018
3019 glslang::GetThreadPoolAllocator().push();
3020
3021 TGlslangToSpvTraverser it(&intermediate);
3022
3023 root->traverse(&it);
3024
3025 it.dumpSpv(spirv);
3026
3027 glslang::GetThreadPoolAllocator().pop();
3028}
3029
3030}; // end namespace glslang