blob: 508ebed219a9dbf6d153bc3a6b113dd46f4f987c [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;
John Kessenichda581a22015-10-14 14:10:30 -0600324 case glslang::EbvBaseVertex:
325 case glslang::EbvBaseInstance:
326 case glslang::EbvDrawId:
327 // TODO: Add SPIR-V builtin ID.
328 spv::MissingFunctionality("Draw parameters");
329 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600330 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
331 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
332 case glslang::EbvLayer: return spv::BuiltInLayer;
333 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
334 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
335 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
336 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
337 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
338 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
339 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
340 case glslang::EbvFace: return spv::BuiltInFrontFacing;
341 case glslang::EbvSampleId: return spv::BuiltInSampleId;
342 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
343 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
344 case glslang::EbvFragColor: return spv::BuiltInFragColor;
345 case glslang::EbvFragData: return spv::BuiltInFragColor;
346 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
347 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
348 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
349 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
350 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
351 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
352 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
353 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
354 default: return (spv::BuiltIn)spv::BadValue;
355 }
356}
357
Rex Xufc618912015-09-09 16:42:49 +0800358// Translate glslang image layout format to SPIR-V image format.
359spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
360{
361 assert(type.getBasicType() == glslang::EbtSampler);
362
363 switch (type.getQualifier().layoutFormat) {
364 case glslang::ElfNone: return spv::ImageFormatUnknown;
365 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
366 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
367 case glslang::ElfR32f: return spv::ImageFormatR32f;
368 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
369 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
370 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
371 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
372 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
373 case glslang::ElfR16f: return spv::ImageFormatR16f;
374 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
375 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
376 case glslang::ElfRg16: return spv::ImageFormatRg16;
377 case glslang::ElfRg8: return spv::ImageFormatRg8;
378 case glslang::ElfR16: return spv::ImageFormatR16;
379 case glslang::ElfR8: return spv::ImageFormatR8;
380 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
381 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
382 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
383 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
384 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
385 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
386 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
387 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
388 case glslang::ElfR32i: return spv::ImageFormatR32i;
389 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
390 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
391 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
392 case glslang::ElfR16i: return spv::ImageFormatR16i;
393 case glslang::ElfR8i: return spv::ImageFormatR8i;
394 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
395 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
396 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
397 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
398 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
399 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
400 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
401 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
402 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
403 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
404 default: return (spv::ImageFormat)spv::BadValue;
405 }
406}
407
John Kessenich140f3df2015-06-26 16:58:36 -0600408//
409// Implement the TGlslangToSpvTraverser class.
410//
411
412TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
413 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
414 builder(GlslangMagic),
415 inMain(false), mainTerminated(false), linkageOnly(false),
416 glslangIntermediate(glslangIntermediate)
417{
418 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
419
420 builder.clearAccessChain();
421 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
422 stdBuiltins = builder.import("GLSL.std.450");
423 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
424 shaderEntry = builder.makeMain();
John Kessenich5e4b1242015-08-06 22:53:06 -0600425 builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600426
427 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600428 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
429 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600430 builder.addSourceExtension(it->c_str());
431
432 // Add the top-level modes for this shader.
433
434 if (glslangIntermediate->getXfbMode())
435 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
436
437 unsigned int mode;
438 switch (glslangIntermediate->getStage()) {
439 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600440 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600441 break;
442
443 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600444 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600445 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
446 break;
447
448 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600449 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600450 switch (glslangIntermediate->getInputPrimitive()) {
451 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
452 case glslang::ElgQuads: mode = spv::ExecutionModeInputQuads; break;
453 case glslang::ElgIsolines: mode = spv::ExecutionModeInputIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600454 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600455 }
456 if (mode != spv::BadValue)
457 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
458
John Kesseniche6903322015-10-13 16:29:02 -0600459 switch (glslangIntermediate->getVertexSpacing()) {
460 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
461 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
462 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
463 default: mode = spv::BadValue; break;
464 }
465 if (mode != spv::BadValue)
466 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
467
468 switch (glslangIntermediate->getVertexOrder()) {
469 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
470 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
471 default: mode = spv::BadValue; break;
472 }
473 if (mode != spv::BadValue)
474 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
475
476 if (glslangIntermediate->getPointMode())
477 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600478 break;
479
480 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600481 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600482 switch (glslangIntermediate->getInputPrimitive()) {
483 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
484 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
485 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
486 case glslang::ElgTriangles: mode = spv::ExecutionModeInputTriangles; break;
487 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
488 default: mode = spv::BadValue; break;
489 }
490 if (mode != spv::BadValue)
491 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600492
John Kessenich140f3df2015-06-26 16:58:36 -0600493 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
494
495 switch (glslangIntermediate->getOutputPrimitive()) {
496 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
497 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
498 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
499 default: mode = spv::BadValue; break;
500 }
501 if (mode != spv::BadValue)
502 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
503 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
504 break;
505
506 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600507 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600508 if (glslangIntermediate->getPixelCenterInteger())
509 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600510
John Kessenich140f3df2015-06-26 16:58:36 -0600511 if (glslangIntermediate->getOriginUpperLeft())
512 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600513 else
514 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600515
516 if (glslangIntermediate->getEarlyFragmentTests())
517 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
518
519 switch(glslangIntermediate->getDepth()) {
520 case glslang::EldAny: mode = spv::ExecutionModeDepthAny; break;
521 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
522 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
523 default: mode = spv::BadValue; break;
524 }
525 if (mode != spv::BadValue)
526 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
527
528 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
529 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600530 break;
531
532 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600533 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600534 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
535 glslangIntermediate->getLocalSize(1),
536 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600537 break;
538
539 default:
540 break;
541 }
542
543}
544
545TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
546{
547 if (! mainTerminated) {
548 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
549 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600550 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600551 }
552}
553
554//
555// Implement the traversal functions.
556//
557// Return true from interior nodes to have the external traversal
558// continue on to children. Return false if children were
559// already processed.
560//
561
562//
563// Symbols can turn into
564// - uniform/input reads
565// - output writes
566// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
567// - something simple that degenerates into the last bullet
568//
569void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
570{
571 // getSymbolId() will set up all the IO decorations on the first call.
572 // Formal function parameters were mapped during makeFunctions().
573 spv::Id id = getSymbolId(symbol);
574
575 if (! linkageOnly) {
576 // Prepare to generate code for the access
577
578 // L-value chains will be computed left to right. We're on the symbol now,
579 // which is the left-most part of the access chain, so now is "clear" time,
580 // followed by setting the base.
581 builder.clearAccessChain();
582
583 // For now, we consider all user variables as being in memory, so they are pointers,
584 // except for "const in" arguments to a function, which are an intermediate object.
585 // See comments in handleUserFunctionCall().
586 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
587 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
588 builder.setAccessChainRValue(id);
589 else
590 builder.setAccessChainLValue(id);
591 }
592}
593
594bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
595{
596 // First, handle special cases
597 switch (node->getOp()) {
598 case glslang::EOpAssign:
599 case glslang::EOpAddAssign:
600 case glslang::EOpSubAssign:
601 case glslang::EOpMulAssign:
602 case glslang::EOpVectorTimesMatrixAssign:
603 case glslang::EOpVectorTimesScalarAssign:
604 case glslang::EOpMatrixTimesScalarAssign:
605 case glslang::EOpMatrixTimesMatrixAssign:
606 case glslang::EOpDivAssign:
607 case glslang::EOpModAssign:
608 case glslang::EOpAndAssign:
609 case glslang::EOpInclusiveOrAssign:
610 case glslang::EOpExclusiveOrAssign:
611 case glslang::EOpLeftShiftAssign:
612 case glslang::EOpRightShiftAssign:
613 // A bin-op assign "a += b" means the same thing as "a = a + b"
614 // where a is evaluated before b. For a simple assignment, GLSL
615 // says to evaluate the left before the right. So, always, left
616 // node then right node.
617 {
618 // get the left l-value, save it away
619 builder.clearAccessChain();
620 node->getLeft()->traverse(this);
621 spv::Builder::AccessChain lValue = builder.getAccessChain();
622
623 // evaluate the right
624 builder.clearAccessChain();
625 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600626 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600627
628 if (node->getOp() != glslang::EOpAssign) {
629 // the left is also an r-value
630 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600631 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600632
633 // do the operation
634 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
635 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
636 node->getType().getBasicType());
637
638 // these all need their counterparts in createBinaryOperation()
639 if (rValue == 0)
640 spv::MissingFunctionality("createBinaryOperation");
641 }
642
643 // store the result
644 builder.setAccessChain(lValue);
645 builder.accessChainStore(rValue);
646
647 // assignments are expressions having an rValue after they are evaluated...
648 builder.clearAccessChain();
649 builder.setAccessChainRValue(rValue);
650 }
651 return false;
652 case glslang::EOpIndexDirect:
653 case glslang::EOpIndexDirectStruct:
654 {
655 // Get the left part of the access chain.
656 node->getLeft()->traverse(this);
657
658 // Add the next element in the chain
659
660 int index = 0;
661 if (node->getRight()->getAsConstantUnion() == 0)
662 spv::MissingFunctionality("direct index without a constant node");
663 else
664 index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
665
666 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
667 // This may be, e.g., an anonymous block-member selection, which generally need
668 // index remapping due to hidden members in anonymous blocks.
669 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
670 if (remapper.size() == 0)
671 spv::MissingFunctionality("block without member remapping");
672 else
673 index = remapper[index];
674 }
675
676 if (! node->getLeft()->getType().isArray() &&
677 node->getLeft()->getType().isVector() &&
678 node->getOp() == glslang::EOpIndexDirect) {
679 // This is essentially a hard-coded vector swizzle of size 1,
680 // so short circuit the access-chain stuff with a swizzle.
681 std::vector<unsigned> swizzle;
682 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600683 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600684 } else {
685 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600686 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600687 }
688 }
689 return false;
690 case glslang::EOpIndexIndirect:
691 {
692 // Structure or array or vector indirection.
693 // Will use native SPIR-V access-chain for struct and array indirection;
694 // matrices are arrays of vectors, so will also work for a matrix.
695 // Will use the access chain's 'component' for variable index into a vector.
696
697 // This adapter is building access chains left to right.
698 // Set up the access chain to the left.
699 node->getLeft()->traverse(this);
700
701 // save it so that computing the right side doesn't trash it
702 spv::Builder::AccessChain partial = builder.getAccessChain();
703
704 // compute the next index in the chain
705 builder.clearAccessChain();
706 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600707 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600708
709 // restore the saved access chain
710 builder.setAccessChain(partial);
711
712 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600713 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600714 else
John Kessenichfa668da2015-09-13 14:46:30 -0600715 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600716 }
717 return false;
718 case glslang::EOpVectorSwizzle:
719 {
720 node->getLeft()->traverse(this);
721 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
722 std::vector<unsigned> swizzle;
723 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
724 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600725 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600726 }
727 return false;
728 default:
729 break;
730 }
731
732 // Assume generic binary op...
733
734 // Get the operands
735 builder.clearAccessChain();
736 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600737 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600738
739 builder.clearAccessChain();
740 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600741 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600742
743 spv::Id result;
744 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
745
746 result = createBinaryOperation(node->getOp(), precision,
747 convertGlslangToSpvType(node->getType()), left, right,
748 node->getLeft()->getType().getBasicType());
749
750 if (! result) {
751 spv::MissingFunctionality("glslang binary operation");
752 } else {
753 builder.clearAccessChain();
754 builder.setAccessChainRValue(result);
755
756 return false;
757 }
758
759 return true;
760}
761
762bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
763{
John Kessenichfc51d282015-08-19 13:34:18 -0600764 spv::Id result = spv::NoResult;
765
766 // try texturing first
767 result = createImageTextureFunctionCall(node);
768 if (result != spv::NoResult) {
769 builder.clearAccessChain();
770 builder.setAccessChainRValue(result);
771
772 return false; // done with this node
773 }
774
775 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600776
777 if (node->getOp() == glslang::EOpArrayLength) {
778 // Quite special; won't want to evaluate the operand.
779
780 // Normal .length() would have been constant folded by the front-end.
781 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600782 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600783 assert(node->getOperand()->getType().isRuntimeSizedArray());
784 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
785 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600786 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
787 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600788
789 builder.clearAccessChain();
790 builder.setAccessChainRValue(length);
791
792 return false;
793 }
794
John Kessenichfc51d282015-08-19 13:34:18 -0600795 // Start by evaluating the operand
796
John Kessenich140f3df2015-06-26 16:58:36 -0600797 builder.clearAccessChain();
798 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800799
Rex Xufc618912015-09-09 16:42:49 +0800800 spv::Id operand = spv::NoResult;
801
802 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
803 node->getOp() == glslang::EOpAtomicCounterDecrement ||
804 node->getOp() == glslang::EOpAtomicCounter)
805 operand = builder.accessChainGetLValue(); // Special case l-value operands
806 else
Rex Xu30f92582015-09-14 10:38:56 +0800807 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600808
809 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
810
811 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600812 if (! result)
813 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600814
815 // if not, then possibly an operation
816 if (! result)
Rex Xu04db3f52015-09-16 11:44:02 +0800817 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600818
819 if (result) {
820 builder.clearAccessChain();
821 builder.setAccessChainRValue(result);
822
823 return false; // done with this node
824 }
825
826 // it must be a special case, check...
827 switch (node->getOp()) {
828 case glslang::EOpPostIncrement:
829 case glslang::EOpPostDecrement:
830 case glslang::EOpPreIncrement:
831 case glslang::EOpPreDecrement:
832 {
833 // we need the integer value "1" or the floating point "1.0" to add/subtract
834 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
835 builder.makeFloatConstant(1.0F) :
836 builder.makeIntConstant(1);
837 glslang::TOperator op;
838 if (node->getOp() == glslang::EOpPreIncrement ||
839 node->getOp() == glslang::EOpPostIncrement)
840 op = glslang::EOpAdd;
841 else
842 op = glslang::EOpSub;
843
844 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
845 convertGlslangToSpvType(node->getType()), operand, one,
846 node->getType().getBasicType());
847 if (result == 0)
848 spv::MissingFunctionality("createBinaryOperation for unary");
849
850 // The result of operation is always stored, but conditionally the
851 // consumed result. The consumed result is always an r-value.
852 builder.accessChainStore(result);
853 builder.clearAccessChain();
854 if (node->getOp() == glslang::EOpPreIncrement ||
855 node->getOp() == glslang::EOpPreDecrement)
856 builder.setAccessChainRValue(result);
857 else
858 builder.setAccessChainRValue(operand);
859 }
860
861 return false;
862
863 case glslang::EOpEmitStreamVertex:
864 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
865 return false;
866 case glslang::EOpEndStreamPrimitive:
867 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
868 return false;
869
870 default:
871 spv::MissingFunctionality("glslang unary");
872 break;
873 }
874
875 return true;
876}
877
878bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
879{
John Kessenichfc51d282015-08-19 13:34:18 -0600880 spv::Id result = spv::NoResult;
881
882 // try texturing
883 result = createImageTextureFunctionCall(node);
884 if (result != spv::NoResult) {
885 builder.clearAccessChain();
886 builder.setAccessChainRValue(result);
887
888 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600889 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800890 // "imageStore" is a special case, which has no result
891 return false;
892 }
John Kessenichfc51d282015-08-19 13:34:18 -0600893
John Kessenich140f3df2015-06-26 16:58:36 -0600894 glslang::TOperator binOp = glslang::EOpNull;
895 bool reduceComparison = true;
896 bool isMatrix = false;
897 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600898 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600899
900 assert(node->getOp());
901
902 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
903
904 switch (node->getOp()) {
905 case glslang::EOpSequence:
906 {
907 if (preVisit)
908 ++sequenceDepth;
909 else
910 --sequenceDepth;
911
912 if (sequenceDepth == 1) {
913 // If this is the parent node of all the functions, we want to see them
914 // early, so all call points have actual SPIR-V functions to reference.
915 // In all cases, still let the traverser visit the children for us.
916 makeFunctions(node->getAsAggregate()->getSequence());
917
918 // Also, we want all globals initializers to go into the entry of main(), before
919 // anything else gets there, so visit out of order, doing them all now.
920 makeGlobalInitializers(node->getAsAggregate()->getSequence());
921
922 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
923 // so do them manually.
924 visitFunctions(node->getAsAggregate()->getSequence());
925
926 return false;
927 }
928
929 return true;
930 }
931 case glslang::EOpLinkerObjects:
932 {
933 if (visit == glslang::EvPreVisit)
934 linkageOnly = true;
935 else
936 linkageOnly = false;
937
938 return true;
939 }
940 case glslang::EOpComma:
941 {
942 // processing from left to right naturally leaves the right-most
943 // lying around in the access chain
944 glslang::TIntermSequence& glslangOperands = node->getSequence();
945 for (int i = 0; i < (int)glslangOperands.size(); ++i)
946 glslangOperands[i]->traverse(this);
947
948 return false;
949 }
950 case glslang::EOpFunction:
951 if (visit == glslang::EvPreVisit) {
952 if (isShaderEntrypoint(node)) {
953 inMain = true;
954 builder.setBuildPoint(shaderEntry->getLastBlock());
955 } else {
956 handleFunctionEntry(node);
957 }
958 } else {
959 if (inMain)
960 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600961 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600962 inMain = false;
963 }
964
965 return true;
966 case glslang::EOpParameters:
967 // Parameters will have been consumed by EOpFunction processing, but not
968 // the body, so we still visited the function node's children, making this
969 // child redundant.
970 return false;
971 case glslang::EOpFunctionCall:
972 {
973 if (node->isUserDefined())
974 result = handleUserFunctionCall(node);
John Kessenich140f3df2015-06-26 16:58:36 -0600975
976 if (! result) {
977 spv::MissingFunctionality("glslang function call");
978 glslang::TConstUnionArray emptyConsts;
979 int nextConst = 0;
980 result = createSpvConstant(node->getType(), emptyConsts, nextConst);
981 }
982 builder.clearAccessChain();
983 builder.setAccessChainRValue(result);
984
985 return false;
986 }
987 case glslang::EOpConstructMat2x2:
988 case glslang::EOpConstructMat2x3:
989 case glslang::EOpConstructMat2x4:
990 case glslang::EOpConstructMat3x2:
991 case glslang::EOpConstructMat3x3:
992 case glslang::EOpConstructMat3x4:
993 case glslang::EOpConstructMat4x2:
994 case glslang::EOpConstructMat4x3:
995 case glslang::EOpConstructMat4x4:
996 case glslang::EOpConstructDMat2x2:
997 case glslang::EOpConstructDMat2x3:
998 case glslang::EOpConstructDMat2x4:
999 case glslang::EOpConstructDMat3x2:
1000 case glslang::EOpConstructDMat3x3:
1001 case glslang::EOpConstructDMat3x4:
1002 case glslang::EOpConstructDMat4x2:
1003 case glslang::EOpConstructDMat4x3:
1004 case glslang::EOpConstructDMat4x4:
1005 isMatrix = true;
1006 // fall through
1007 case glslang::EOpConstructFloat:
1008 case glslang::EOpConstructVec2:
1009 case glslang::EOpConstructVec3:
1010 case glslang::EOpConstructVec4:
1011 case glslang::EOpConstructDouble:
1012 case glslang::EOpConstructDVec2:
1013 case glslang::EOpConstructDVec3:
1014 case glslang::EOpConstructDVec4:
1015 case glslang::EOpConstructBool:
1016 case glslang::EOpConstructBVec2:
1017 case glslang::EOpConstructBVec3:
1018 case glslang::EOpConstructBVec4:
1019 case glslang::EOpConstructInt:
1020 case glslang::EOpConstructIVec2:
1021 case glslang::EOpConstructIVec3:
1022 case glslang::EOpConstructIVec4:
1023 case glslang::EOpConstructUint:
1024 case glslang::EOpConstructUVec2:
1025 case glslang::EOpConstructUVec3:
1026 case glslang::EOpConstructUVec4:
1027 case glslang::EOpConstructStruct:
1028 {
1029 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001030 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001031 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1032 spv::Id constructed;
1033 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1034 std::vector<spv::Id> constituents;
1035 for (int c = 0; c < (int)arguments.size(); ++c)
1036 constituents.push_back(arguments[c]);
1037 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
1038 } else {
1039 if (isMatrix)
1040 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1041 else
1042 constructed = builder.createConstructor(precision, arguments, resultTypeId);
1043 }
1044
1045 builder.clearAccessChain();
1046 builder.setAccessChainRValue(constructed);
1047
1048 return false;
1049 }
1050
1051 // These six are component-wise compares with component-wise results.
1052 // Forward on to createBinaryOperation(), requesting a vector result.
1053 case glslang::EOpLessThan:
1054 case glslang::EOpGreaterThan:
1055 case glslang::EOpLessThanEqual:
1056 case glslang::EOpGreaterThanEqual:
1057 case glslang::EOpVectorEqual:
1058 case glslang::EOpVectorNotEqual:
1059 {
1060 // Map the operation to a binary
1061 binOp = node->getOp();
1062 reduceComparison = false;
1063 switch (node->getOp()) {
1064 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1065 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1066 default: binOp = node->getOp(); break;
1067 }
1068
1069 break;
1070 }
1071 case glslang::EOpMul:
1072 // compontent-wise matrix multiply
1073 binOp = glslang::EOpMul;
1074 break;
1075 case glslang::EOpOuterProduct:
1076 // two vectors multiplied to make a matrix
1077 binOp = glslang::EOpOuterProduct;
1078 break;
1079 case glslang::EOpDot:
1080 {
1081 // for scalar dot product, use multiply
1082 glslang::TIntermSequence& glslangOperands = node->getSequence();
1083 if (! glslangOperands[0]->getAsTyped()->isVector())
1084 binOp = glslang::EOpMul;
1085 break;
1086 }
1087 case glslang::EOpMod:
1088 // when an aggregate, this is the floating-point mod built-in function,
1089 // which can be emitted by the one in createBinaryOperation()
1090 binOp = glslang::EOpMod;
1091 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001092 case glslang::EOpEmitVertex:
1093 case glslang::EOpEndPrimitive:
1094 case glslang::EOpBarrier:
1095 case glslang::EOpMemoryBarrier:
1096 case glslang::EOpMemoryBarrierAtomicCounter:
1097 case glslang::EOpMemoryBarrierBuffer:
1098 case glslang::EOpMemoryBarrierImage:
1099 case glslang::EOpMemoryBarrierShared:
1100 case glslang::EOpGroupMemoryBarrier:
1101 noReturnValue = true;
1102 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1103 break;
1104
John Kessenich426394d2015-07-23 10:22:48 -06001105 case glslang::EOpAtomicAdd:
1106 case glslang::EOpAtomicMin:
1107 case glslang::EOpAtomicMax:
1108 case glslang::EOpAtomicAnd:
1109 case glslang::EOpAtomicOr:
1110 case glslang::EOpAtomicXor:
1111 case glslang::EOpAtomicExchange:
1112 case glslang::EOpAtomicCompSwap:
1113 atomic = true;
1114 break;
1115
John Kessenichfc51d282015-08-19 13:34:18 -06001116 case glslang::EOpAddCarry:
1117 case glslang::EOpSubBorrow:
1118 case glslang::EOpUMulExtended:
1119 case glslang::EOpIMulExtended:
1120 case glslang::EOpBitfieldExtract:
1121 case glslang::EOpBitfieldInsert:
1122 spv::MissingFunctionality("integer aggregate");
1123 break;
1124
1125 case glslang::EOpFma:
John Kessenich78258d32015-08-19 17:30:12 -06001126 case glslang::EOpFrexp:
1127 case glslang::EOpLdexp:
John Kessenichfc51d282015-08-19 13:34:18 -06001128 spv::MissingFunctionality("fma/frexp/ldexp aggregate");
1129 break;
1130
John Kessenich140f3df2015-06-26 16:58:36 -06001131 default:
1132 break;
1133 }
1134
1135 //
1136 // See if it maps to a regular operation.
1137 //
John Kessenich140f3df2015-06-26 16:58:36 -06001138 if (binOp != glslang::EOpNull) {
1139 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1140 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1141 assert(left && right);
1142
1143 builder.clearAccessChain();
1144 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001145 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001146
1147 builder.clearAccessChain();
1148 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001149 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001150
1151 result = createBinaryOperation(binOp, precision,
1152 convertGlslangToSpvType(node->getType()), leftId, rightId,
1153 left->getType().getBasicType(), reduceComparison);
1154
1155 // code above should only make binOp that exists in createBinaryOperation
1156 if (result == 0)
1157 spv::MissingFunctionality("createBinaryOperation for aggregate");
1158
1159 builder.clearAccessChain();
1160 builder.setAccessChainRValue(result);
1161
1162 return false;
1163 }
1164
John Kessenich426394d2015-07-23 10:22:48 -06001165 //
1166 // Create the list of operands.
1167 //
John Kessenich140f3df2015-06-26 16:58:36 -06001168 glslang::TIntermSequence& glslangOperands = node->getSequence();
1169 std::vector<spv::Id> operands;
1170 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1171 builder.clearAccessChain();
1172 glslangOperands[arg]->traverse(this);
1173
1174 // special case l-value operands; there are just a few
1175 bool lvalue = false;
1176 switch (node->getOp()) {
1177 //case glslang::EOpFrexp:
1178 case glslang::EOpModf:
1179 if (arg == 1)
1180 lvalue = true;
1181 break;
Rex Xud4782c12015-09-06 16:30:11 +08001182 case glslang::EOpAtomicAdd:
1183 case glslang::EOpAtomicMin:
1184 case glslang::EOpAtomicMax:
1185 case glslang::EOpAtomicAnd:
1186 case glslang::EOpAtomicOr:
1187 case glslang::EOpAtomicXor:
1188 case glslang::EOpAtomicExchange:
1189 case glslang::EOpAtomicCompSwap:
1190 if (arg == 0)
1191 lvalue = true;
1192 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001193 //case glslang::EOpUAddCarry:
1194 //case glslang::EOpUSubBorrow:
1195 //case glslang::EOpUMulExtended:
1196 default:
1197 break;
1198 }
1199 if (lvalue)
1200 operands.push_back(builder.accessChainGetLValue());
1201 else
John Kessenichfa668da2015-09-13 14:46:30 -06001202 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001203 }
John Kessenich426394d2015-07-23 10:22:48 -06001204
1205 if (atomic) {
1206 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001207 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001208 } else {
1209 // Pass through to generic operations.
1210 switch (glslangOperands.size()) {
1211 case 0:
1212 result = createNoArgOperation(node->getOp());
1213 break;
1214 case 1:
Rex Xu04db3f52015-09-16 11:44:02 +08001215 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), node->getType().getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001216 break;
1217 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001218 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001219 break;
1220 }
John Kessenich140f3df2015-06-26 16:58:36 -06001221 }
1222
1223 if (noReturnValue)
1224 return false;
1225
1226 if (! result) {
1227 spv::MissingFunctionality("glslang aggregate");
1228 return true;
1229 } else {
1230 builder.clearAccessChain();
1231 builder.setAccessChainRValue(result);
1232 return false;
1233 }
1234}
1235
1236bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1237{
1238 // This path handles both if-then-else and ?:
1239 // The if-then-else has a node type of void, while
1240 // ?: has a non-void node type
1241 spv::Id result = 0;
1242 if (node->getBasicType() != glslang::EbtVoid) {
1243 // don't handle this as just on-the-fly temporaries, because there will be two names
1244 // and better to leave SSA to later passes
1245 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1246 }
1247
1248 // emit the condition before doing anything with selection
1249 node->getCondition()->traverse(this);
1250
1251 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001252 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001253
1254 if (node->getTrueBlock()) {
1255 // emit the "then" statement
1256 node->getTrueBlock()->traverse(this);
1257 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001258 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001259 }
1260
1261 if (node->getFalseBlock()) {
1262 ifBuilder.makeBeginElse();
1263 // emit the "else" statement
1264 node->getFalseBlock()->traverse(this);
1265 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001266 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001267 }
1268
1269 ifBuilder.makeEndIf();
1270
1271 if (result) {
1272 // GLSL only has r-values as the result of a :?, but
1273 // if we have an l-value, that can be more efficient if it will
1274 // become the base of a complex r-value expression, because the
1275 // next layer copies r-values into memory to use the access-chain mechanism
1276 builder.clearAccessChain();
1277 builder.setAccessChainLValue(result);
1278 }
1279
1280 return false;
1281}
1282
1283bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1284{
1285 // emit and get the condition before doing anything with switch
1286 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001287 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001288
1289 // browse the children to sort out code segments
1290 int defaultSegment = -1;
1291 std::vector<TIntermNode*> codeSegments;
1292 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1293 std::vector<int> caseValues;
1294 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1295 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1296 TIntermNode* child = *c;
1297 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001298 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001299 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001300 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001301 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1302 } else
1303 codeSegments.push_back(child);
1304 }
1305
1306 // handle the case where the last code segment is missing, due to no code
1307 // statements between the last case and the end of the switch statement
1308 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1309 (int)codeSegments.size() == defaultSegment)
1310 codeSegments.push_back(nullptr);
1311
1312 // make the switch statement
1313 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001314 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001315
1316 // emit all the code in the segments
1317 breakForLoop.push(false);
1318 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1319 builder.nextSwitchSegment(segmentBlocks, s);
1320 if (codeSegments[s])
1321 codeSegments[s]->traverse(this);
1322 else
1323 builder.addSwitchBreak();
1324 }
1325 breakForLoop.pop();
1326
1327 builder.endSwitch(segmentBlocks);
1328
1329 return false;
1330}
1331
1332void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1333{
1334 int nextConst = 0;
1335 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1336
1337 builder.clearAccessChain();
1338 builder.setAccessChainRValue(constant);
1339}
1340
1341bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1342{
1343 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1344 loopTerminal.push(node->getTerminal());
1345
David Netoc22f37c2015-07-15 16:21:26 -04001346 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001347
1348 if (node->getTest()) {
1349 node->getTest()->traverse(this);
1350 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001351 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001352 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001353 } else {
1354 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001355 }
1356
David Netoc22f37c2015-07-15 16:21:26 -04001357 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001358 breakForLoop.push(true);
1359 node->getBody()->traverse(this);
1360 breakForLoop.pop();
1361 }
1362
1363 if (loopTerminal.top())
1364 loopTerminal.top()->traverse(this);
1365
1366 builder.closeLoop();
1367
1368 loopTerminal.pop();
1369
1370 return false;
1371}
1372
1373bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1374{
1375 if (node->getExpression())
1376 node->getExpression()->traverse(this);
1377
1378 switch (node->getFlowOp()) {
1379 case glslang::EOpKill:
1380 builder.makeDiscard();
1381 break;
1382 case glslang::EOpBreak:
1383 if (breakForLoop.top())
1384 builder.createLoopExit();
1385 else
1386 builder.addSwitchBreak();
1387 break;
1388 case glslang::EOpContinue:
1389 if (loopTerminal.top())
1390 loopTerminal.top()->traverse(this);
1391 builder.createLoopContinue();
1392 break;
1393 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001394 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001395 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001396 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001397 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001398
1399 builder.clearAccessChain();
1400 break;
1401
1402 default:
1403 spv::MissingFunctionality("branch type");
1404 break;
1405 }
1406
1407 return false;
1408}
1409
1410spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1411{
1412 // First, steer off constants, which are not SPIR-V variables, but
1413 // can still have a mapping to a SPIR-V Id.
1414 if (node->getQualifier().storage == glslang::EvqConst) {
1415 int nextConst = 0;
1416 return createSpvConstant(node->getType(), node->getConstArray(), nextConst);
1417 }
1418
1419 // Now, handle actual variables
1420 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1421 spv::Id spvType = convertGlslangToSpvType(node->getType());
1422
1423 const char* name = node->getName().c_str();
1424 if (glslang::IsAnonymous(name))
1425 name = "";
1426
1427 return builder.createVariable(storageClass, spvType, name);
1428}
1429
1430// Return type Id of the sampled type.
1431spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1432{
1433 switch (sampler.type) {
1434 case glslang::EbtFloat: return builder.makeFloatType(32);
1435 case glslang::EbtInt: return builder.makeIntType(32);
1436 case glslang::EbtUint: return builder.makeUintType(32);
1437 default:
1438 spv::MissingFunctionality("sampled type");
1439 return builder.makeFloatType(32);
1440 }
1441}
1442
John Kessenich31ed4832015-09-09 17:51:38 -06001443// Convert from a glslang type to an SPV type, by calling into
1444// recursive version of this function.
John Kessenich140f3df2015-06-26 16:58:36 -06001445spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1446{
John Kessenich31ed4832015-09-09 17:51:38 -06001447 return convertGlslangToSpvType(type, requiresExplicitLayout(type));
1448}
1449
1450// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1451// explicitLayout can be kept the same throughout the heirarchical recursive walk.
1452spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, bool explicitLayout)
1453{
John Kessenich140f3df2015-06-26 16:58:36 -06001454 spv::Id spvType = 0;
1455
1456 switch (type.getBasicType()) {
1457 case glslang::EbtVoid:
1458 spvType = builder.makeVoidType();
1459 if (type.isArray())
1460 spv::MissingFunctionality("array of void");
1461 break;
1462 case glslang::EbtFloat:
1463 spvType = builder.makeFloatType(32);
1464 break;
1465 case glslang::EbtDouble:
1466 spvType = builder.makeFloatType(64);
1467 break;
1468 case glslang::EbtBool:
1469 spvType = builder.makeBoolType();
1470 break;
1471 case glslang::EbtInt:
1472 spvType = builder.makeIntType(32);
1473 break;
1474 case glslang::EbtUint:
1475 spvType = builder.makeUintType(32);
1476 break;
John Kessenich426394d2015-07-23 10:22:48 -06001477 case glslang::EbtAtomicUint:
1478 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1479 spvType = builder.makeUintType(32);
1480 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001481 case glslang::EbtSampler:
1482 {
1483 const glslang::TSampler& sampler = type.getSampler();
John Kessenich5e4b1242015-08-06 22:53:06 -06001484 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
Rex Xufc618912015-09-09 16:42:49 +08001485 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich5e4b1242015-08-06 22:53:06 -06001486 // OpenGL "textures" need to be combined with a sampler
1487 if (! sampler.image)
1488 spvType = builder.makeSampledImageType(spvType);
John Kessenich140f3df2015-06-26 16:58:36 -06001489 }
1490 break;
1491 case glslang::EbtStruct:
1492 case glslang::EbtBlock:
1493 {
1494 // If we've seen this struct type, return it
1495 const glslang::TTypeList* glslangStruct = type.getStruct();
1496 std::vector<spv::Id> structFields;
1497 spvType = structMap[glslangStruct];
1498 if (spvType)
1499 break;
1500
1501 // else, we haven't seen it...
1502
1503 // Create a vector of struct types for SPIR-V to consume
1504 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1505 if (type.getBasicType() == glslang::EbtBlock)
1506 memberRemapper[glslangStruct].resize(glslangStruct->size());
1507 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1508 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1509 if (glslangType.hiddenMember()) {
1510 ++memberDelta;
1511 if (type.getBasicType() == glslang::EbtBlock)
1512 memberRemapper[glslangStruct][i] = -1;
1513 } else {
1514 if (type.getBasicType() == glslang::EbtBlock)
1515 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich31ed4832015-09-09 17:51:38 -06001516 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001517 }
1518 }
1519
1520 // Make the SPIR-V type
1521 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
1522 structMap[glslangStruct] = spvType;
1523
1524 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001525 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001526 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1527 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1528 int member = i;
1529 if (type.getBasicType() == glslang::EbtBlock)
1530 member = memberRemapper[glslangStruct][i];
1531 // using -1 above to indicate a hidden member
1532 if (member >= 0) {
1533 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
1534 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType));
1535 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1536 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1537 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1538 if (glslangType.getQualifier().hasLocation())
1539 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1540 if (glslangType.getQualifier().hasComponent())
1541 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1542 if (glslangType.getQualifier().hasXfbOffset())
1543 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenich31ed4832015-09-09 17:51:38 -06001544 else if (explicitLayout) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001545 // figure out what to do with offset, which is accumulating
1546 int nextOffset;
1547 updateMemberOffset(type, glslangType, offset, nextOffset);
1548 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001549 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001550 offset = nextOffset;
1551 }
John Kessenich140f3df2015-06-26 16:58:36 -06001552
John Kessenich31ed4832015-09-09 17:51:38 -06001553 if (glslangType.isMatrix() && explicitLayout) {
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001554 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType));
1555 }
1556
John Kessenich140f3df2015-06-26 16:58:36 -06001557 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001558 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1559 if (builtIn != spv::BadValue)
1560 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001561 }
1562 }
1563
1564 // Decorate the structure
1565 addDecoration(spvType, TranslateLayoutDecoration(type));
1566 addDecoration(spvType, TranslateBlockDecoration(type));
1567 if (type.getQualifier().hasStream())
1568 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1569 if (glslangIntermediate->getXfbMode()) {
1570 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001571 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001572 if (type.getQualifier().hasXfbBuffer())
1573 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1574 }
1575 }
1576 break;
1577 default:
1578 spv::MissingFunctionality("basic type");
1579 break;
1580 }
1581
1582 if (type.isMatrix())
1583 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1584 else {
1585 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1586 if (type.getVectorSize() > 1)
1587 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1588 }
1589
1590 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001591 // Do all but the outer dimension
1592 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1593 assert(type.getArraySizes()->getDimSize(dim) > 0);
1594 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1595 }
John Kessenich31ed4832015-09-09 17:51:38 -06001596
John Kessenichc9a80832015-09-12 12:17:44 -06001597 // Do the outer dimension, which might not be known for a runtime-sized array
1598 if (type.isRuntimeSizedArray()) {
1599 spvType = builder.makeRuntimeArray(spvType);
1600 } else {
1601 assert(type.getOuterArraySize() > 0);
1602 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1603 }
1604
1605 // TODO: layout still needs to be done hierarchically for arrays of arrays, which
1606 // may still require additional "link time" support from the front-end
1607 // for arrays of arrays
John Kessenich31ed4832015-09-09 17:51:38 -06001608 if (explicitLayout)
1609 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type));
John Kessenich140f3df2015-06-26 16:58:36 -06001610 }
1611
1612 return spvType;
1613}
1614
John Kessenich31ed4832015-09-09 17:51:38 -06001615bool TGlslangToSpvTraverser::requiresExplicitLayout(const glslang::TType& type) const
1616{
1617 return type.getBasicType() == glslang::EbtBlock &&
1618 type.getQualifier().layoutPacking != glslang::ElpShared &&
1619 type.getQualifier().layoutPacking != glslang::ElpPacked &&
1620 (type.getQualifier().storage == glslang::EvqUniform ||
1621 type.getQualifier().storage == glslang::EvqBuffer);
1622}
1623
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001624// Given an array type, returns the integer stride required for that array
1625int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType)
1626{
1627 glslang::TType derefType(arrayType, 0);
1628 int size;
1629 glslangIntermediate->getBaseAlignment(derefType, size, true);
1630 return size;
1631}
1632
1633// Given a matrix type, returns the integer stride required for that matrix
1634// when used as a member of an interface block
1635int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType)
1636{
1637 int size;
1638 return glslangIntermediate->getBaseAlignment(matrixType, size, true);
1639}
1640
John Kessenich5e4b1242015-08-06 22:53:06 -06001641// Given a member type of a struct, realign the current offset for it, and compute
1642// the next (not yet aligned) offset for the next member, which will get aligned
1643// on the next call.
1644// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1645// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1646// -1 means a non-forced member offset (no decoration needed).
1647void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset)
1648{
1649 // this will get a positive value when deemed necessary
1650 nextOffset = -1;
1651
1652 bool forceOffset = structType.getQualifier().layoutPacking == glslang::ElpStd140 ||
1653 structType.getQualifier().layoutPacking == glslang::ElpStd430;
1654
1655 // override anything in currentOffset with user-set offset
1656 if (memberType.getQualifier().hasOffset())
1657 currentOffset = memberType.getQualifier().layoutOffset;
1658
1659 // It could be that current linker usage in glslang updated all the layoutOffset,
1660 // in which case the following code does not matter. But, that's not quite right
1661 // once cross-compilation unit GLSL validation is done, as the original user
1662 // settings are needed in layoutOffset, and then the following will come into play.
1663
1664 if (! forceOffset) {
1665 if (! memberType.getQualifier().hasOffset())
1666 currentOffset = -1;
1667
1668 return;
1669 }
1670
1671 // Getting this far means we are forcing offsets
1672 if (currentOffset < 0)
1673 currentOffset = 0;
1674
1675 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1676 // but possibly not yet correctly aligned.
1677
1678 int memberSize;
1679 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, memberType.getQualifier().layoutPacking == glslang::ElpStd140);
1680 glslang::RoundToPow2(currentOffset, memberAlignment);
1681 nextOffset = currentOffset + memberSize;
1682}
1683
John Kessenich140f3df2015-06-26 16:58:36 -06001684bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1685{
1686 return node->getName() == "main(";
1687}
1688
1689// Make all the functions, skeletally, without actually visiting their bodies.
1690void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1691{
1692 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1693 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1694 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1695 continue;
1696
1697 // We're on a user function. Set up the basic interface for the function now,
1698 // so that it's available to call.
1699 // Translating the body will happen later.
1700 //
1701 // Typically (except for a "const in" parameter), an address will be passed to the
1702 // function. What it is an address of varies:
1703 //
1704 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1705 // so that write needs to be to a copy, hence the address of a copy works.
1706 //
1707 // - "const in" parameters can just be the r-value, as no writes need occur.
1708 //
1709 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1710 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1711
1712 std::vector<spv::Id> paramTypes;
1713 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1714
1715 for (int p = 0; p < (int)parameters.size(); ++p) {
1716 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1717 spv::Id typeId = convertGlslangToSpvType(paramType);
1718 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1719 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1720 else
1721 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1722 paramTypes.push_back(typeId);
1723 }
1724
1725 spv::Block* functionBlock;
1726 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1727 paramTypes, &functionBlock);
1728
1729 // Track function to emit/call later
1730 functionMap[glslFunction->getName().c_str()] = function;
1731
1732 // Set the parameter id's
1733 for (int p = 0; p < (int)parameters.size(); ++p) {
1734 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1735 // give a name too
1736 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1737 }
1738 }
1739}
1740
1741// Process all the initializers, while skipping the functions and link objects
1742void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1743{
1744 builder.setBuildPoint(shaderEntry->getLastBlock());
1745 for (int i = 0; i < (int)initializers.size(); ++i) {
1746 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1747 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1748
1749 // We're on a top-level node that's not a function. Treat as an initializer, whose
1750 // code goes into the beginning of main.
1751 initializer->traverse(this);
1752 }
1753 }
1754}
1755
1756// Process all the functions, while skipping initializers.
1757void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1758{
1759 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1760 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1761 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1762 node->traverse(this);
1763 }
1764}
1765
1766void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1767{
1768 // SPIR-V functions should already be in the functionMap from the prepass
1769 // that called makeFunctions().
1770 spv::Function* function = functionMap[node->getName().c_str()];
1771 spv::Block* functionBlock = function->getEntryBlock();
1772 builder.setBuildPoint(functionBlock);
1773}
1774
Rex Xu04db3f52015-09-16 11:44:02 +08001775void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001776{
Rex Xufc618912015-09-09 16:42:49 +08001777 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001778 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1779 builder.clearAccessChain();
1780 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001781
1782 // Special case l-value operands
1783 bool lvalue = false;
1784 switch (node.getOp()) {
1785 case glslang::EOpImageAtomicAdd:
1786 case glslang::EOpImageAtomicMin:
1787 case glslang::EOpImageAtomicMax:
1788 case glslang::EOpImageAtomicAnd:
1789 case glslang::EOpImageAtomicOr:
1790 case glslang::EOpImageAtomicXor:
1791 case glslang::EOpImageAtomicExchange:
1792 case glslang::EOpImageAtomicCompSwap:
1793 if (i == 0)
1794 lvalue = true;
1795 break;
1796 default:
1797 break;
1798 }
1799
Rex Xu6b86d492015-09-16 17:48:22 +08001800 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001801 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001802 else
Rex Xu30f92582015-09-14 10:38:56 +08001803 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001804 }
1805}
1806
John Kessenichfc51d282015-08-19 13:34:18 -06001807void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001808{
John Kessenichfc51d282015-08-19 13:34:18 -06001809 builder.clearAccessChain();
1810 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001811 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001812}
John Kessenich140f3df2015-06-26 16:58:36 -06001813
John Kessenichfc51d282015-08-19 13:34:18 -06001814spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1815{
Rex Xufc618912015-09-09 16:42:49 +08001816 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001817 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001818 }
1819
John Kessenichfc51d282015-08-19 13:34:18 -06001820 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001821 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1822 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1823 std::vector<spv::Id> arguments;
1824 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001825 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001826 else
1827 translateArguments(*node->getAsUnaryNode(), arguments);
1828 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1829
1830 spv::Builder::TextureParameters params = { };
1831 params.sampler = arguments[0];
1832
Rex Xu04db3f52015-09-16 11:44:02 +08001833 glslang::TCrackedTextureOp cracked;
1834 node->crackTexture(sampler, cracked);
1835
John Kessenichfc51d282015-08-19 13:34:18 -06001836 // Check for queries
1837 if (cracked.query) {
1838 switch (node->getOp()) {
1839 case glslang::EOpImageQuerySize:
1840 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001841 if (arguments.size() > 1) {
1842 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001843 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001844 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001845 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001846 case glslang::EOpImageQuerySamples:
1847 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001848 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001849 case glslang::EOpTextureQueryLod:
1850 params.coords = arguments[1];
1851 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1852 case glslang::EOpTextureQueryLevels:
1853 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1854 default:
1855 assert(0);
1856 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001857 }
John Kessenich140f3df2015-06-26 16:58:36 -06001858 }
1859
Rex Xufc618912015-09-09 16:42:49 +08001860 // Check for image functions other than queries
1861 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001862 std::vector<spv::Id> operands;
1863 auto opIt = arguments.begin();
1864 operands.push_back(*(opIt++));
1865 operands.push_back(*(opIt++));
1866 if (node->getOp() == glslang::EOpImageStore)
Rex Xu6b86d492015-09-16 17:48:22 +08001867 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001868 // TODO: add 'sample' operand
1869 if (node->getOp() == glslang::EOpImageLoad) {
1870 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1871 } else if (node->getOp() == glslang::EOpImageStore) {
1872 builder.createNoResultOp(spv::OpImageWrite, operands);
1873 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001874 } else {
1875 // Process image atomic operations
1876
1877 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1878 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001879 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001880
Rex Xufc618912015-09-09 16:42:49 +08001881 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001882 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001883
1884 std::vector<spv::Id> operands;
1885 operands.push_back(pointer);
1886 for (; opIt != arguments.end(); ++opIt)
1887 operands.push_back(*opIt);
1888
Rex Xu04db3f52015-09-16 11:44:02 +08001889 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001890 }
1891 }
1892
1893 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001894 if (cracked.gather)
1895 spv::MissingFunctionality("texture gather");
1896
1897 // check for bias argument
1898 bool bias = false;
1899 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch) {
1900 int nonBiasArgCount = 2;
1901 if (cracked.offset)
1902 ++nonBiasArgCount;
1903 if (cracked.grad)
1904 nonBiasArgCount += 2;
1905
1906 if ((int)arguments.size() > nonBiasArgCount)
1907 bias = true;
1908 }
1909
1910 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1911
1912 // set the rest of the arguments
1913 params.coords = arguments[1];
1914 int extraArgs = 0;
1915 if (cubeCompare)
1916 params.Dref = arguments[2];
1917 else if (sampler.shadow) {
1918 std::vector<spv::Id> indexes;
1919 int comp;
1920 if (cracked.proj)
1921 comp = 3;
1922 else
1923 comp = builder.getNumComponents(params.coords) - 1;
1924 indexes.push_back(comp);
1925 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1926 }
1927 if (cracked.lod) {
1928 params.lod = arguments[2];
1929 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08001930 } else if (sampler.ms) {
1931 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08001932 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06001933 }
1934 if (cracked.grad) {
1935 params.gradX = arguments[2 + extraArgs];
1936 params.gradY = arguments[3 + extraArgs];
1937 extraArgs += 2;
1938 }
1939 //if (gather && compare) {
1940 // params.compare = arguments[2 + extraArgs];
1941 // ++extraArgs;
1942 //}
1943 if (cracked.offset || cracked.offsets) {
1944 params.offset = arguments[2 + extraArgs];
1945 ++extraArgs;
1946 }
1947 if (bias) {
1948 params.bias = arguments[2 + extraArgs];
1949 ++extraArgs;
1950 }
1951
Jason Ekstrand18b9fbd2015-09-05 14:14:48 -07001952 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001953}
1954
1955spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
1956{
1957 // Grab the function's pointer from the previously created function
1958 spv::Function* function = functionMap[node->getName().c_str()];
1959 if (! function)
1960 return 0;
1961
1962 const glslang::TIntermSequence& glslangArgs = node->getSequence();
1963 const glslang::TQualifierList& qualifiers = node->getQualifierList();
1964
1965 // See comments in makeFunctions() for details about the semantics for parameter passing.
1966 //
1967 // These imply we need a four step process:
1968 // 1. Evaluate the arguments
1969 // 2. Allocate and make copies of in, out, and inout arguments
1970 // 3. Make the call
1971 // 4. Copy back the results
1972
1973 // 1. Evaluate the arguments
1974 std::vector<spv::Builder::AccessChain> lValues;
1975 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06001976 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06001977 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
1978 // build l-value
1979 builder.clearAccessChain();
1980 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001981 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001982 // keep outputs as l-values, evaluate input-only as r-values
1983 if (qualifiers[a] != glslang::EvqConstReadOnly) {
1984 // save l-value
1985 lValues.push_back(builder.getAccessChain());
1986 } else {
1987 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06001988 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06001989 }
1990 }
1991
1992 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
1993 // copy the original into that space.
1994 //
1995 // Also, build up the list of actual arguments to pass in for the call
1996 int lValueCount = 0;
1997 int rValueCount = 0;
1998 std::vector<spv::Id> spvArgs;
1999 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2000 spv::Id arg;
2001 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2002 // need space to hold the copy
2003 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2004 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2005 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2006 // need to copy the input into output space
2007 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002008 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002009 builder.createStore(copy, arg);
2010 }
2011 ++lValueCount;
2012 } else {
2013 arg = rValues[rValueCount];
2014 ++rValueCount;
2015 }
2016 spvArgs.push_back(arg);
2017 }
2018
2019 // 3. Make the call.
2020 spv::Id result = builder.createFunctionCall(function, spvArgs);
2021
2022 // 4. Copy back out an "out" arguments.
2023 lValueCount = 0;
2024 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2025 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2026 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2027 spv::Id copy = builder.createLoad(spvArgs[a]);
2028 builder.setAccessChain(lValues[lValueCount]);
2029 builder.accessChainStore(copy);
2030 }
2031 ++lValueCount;
2032 }
2033 }
2034
2035 return result;
2036}
2037
2038// Translate AST operation to SPV operation, already having SPV-based operands/types.
2039spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2040 spv::Id typeId, spv::Id left, spv::Id right,
2041 glslang::TBasicType typeProxy, bool reduceComparison)
2042{
2043 bool isUnsigned = typeProxy == glslang::EbtUint;
2044 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2045
2046 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002047 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002048 bool comparison = false;
2049
2050 switch (op) {
2051 case glslang::EOpAdd:
2052 case glslang::EOpAddAssign:
2053 if (isFloat)
2054 binOp = spv::OpFAdd;
2055 else
2056 binOp = spv::OpIAdd;
2057 break;
2058 case glslang::EOpSub:
2059 case glslang::EOpSubAssign:
2060 if (isFloat)
2061 binOp = spv::OpFSub;
2062 else
2063 binOp = spv::OpISub;
2064 break;
2065 case glslang::EOpMul:
2066 case glslang::EOpMulAssign:
2067 if (isFloat)
2068 binOp = spv::OpFMul;
2069 else
2070 binOp = spv::OpIMul;
2071 break;
2072 case glslang::EOpVectorTimesScalar:
2073 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002074 if (isFloat) {
2075 if (builder.isVector(right))
2076 std::swap(left, right);
2077 assert(builder.isScalar(right));
2078 needMatchingVectors = false;
2079 binOp = spv::OpVectorTimesScalar;
2080 } else
2081 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002082 break;
2083 case glslang::EOpVectorTimesMatrix:
2084 case glslang::EOpVectorTimesMatrixAssign:
2085 assert(builder.isVector(left));
2086 assert(builder.isMatrix(right));
2087 binOp = spv::OpVectorTimesMatrix;
2088 break;
2089 case glslang::EOpMatrixTimesVector:
2090 assert(builder.isMatrix(left));
2091 assert(builder.isVector(right));
2092 binOp = spv::OpMatrixTimesVector;
2093 break;
2094 case glslang::EOpMatrixTimesScalar:
2095 case glslang::EOpMatrixTimesScalarAssign:
2096 if (builder.isMatrix(right))
2097 std::swap(left, right);
2098 assert(builder.isScalar(right));
2099 binOp = spv::OpMatrixTimesScalar;
2100 break;
2101 case glslang::EOpMatrixTimesMatrix:
2102 case glslang::EOpMatrixTimesMatrixAssign:
2103 assert(builder.isMatrix(left));
2104 assert(builder.isMatrix(right));
2105 binOp = spv::OpMatrixTimesMatrix;
2106 break;
2107 case glslang::EOpOuterProduct:
2108 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002109 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002110 break;
2111
2112 case glslang::EOpDiv:
2113 case glslang::EOpDivAssign:
2114 if (isFloat)
2115 binOp = spv::OpFDiv;
2116 else if (isUnsigned)
2117 binOp = spv::OpUDiv;
2118 else
2119 binOp = spv::OpSDiv;
2120 break;
2121 case glslang::EOpMod:
2122 case glslang::EOpModAssign:
2123 if (isFloat)
2124 binOp = spv::OpFMod;
2125 else if (isUnsigned)
2126 binOp = spv::OpUMod;
2127 else
2128 binOp = spv::OpSMod;
2129 break;
2130 case glslang::EOpRightShift:
2131 case glslang::EOpRightShiftAssign:
2132 if (isUnsigned)
2133 binOp = spv::OpShiftRightLogical;
2134 else
2135 binOp = spv::OpShiftRightArithmetic;
2136 break;
2137 case glslang::EOpLeftShift:
2138 case glslang::EOpLeftShiftAssign:
2139 binOp = spv::OpShiftLeftLogical;
2140 break;
2141 case glslang::EOpAnd:
2142 case glslang::EOpAndAssign:
2143 binOp = spv::OpBitwiseAnd;
2144 break;
2145 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002146 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002147 binOp = spv::OpLogicalAnd;
2148 break;
2149 case glslang::EOpInclusiveOr:
2150 case glslang::EOpInclusiveOrAssign:
2151 binOp = spv::OpBitwiseOr;
2152 break;
2153 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002154 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002155 binOp = spv::OpLogicalOr;
2156 break;
2157 case glslang::EOpExclusiveOr:
2158 case glslang::EOpExclusiveOrAssign:
2159 binOp = spv::OpBitwiseXor;
2160 break;
2161 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002162 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002163 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002164 break;
2165
2166 case glslang::EOpLessThan:
2167 case glslang::EOpGreaterThan:
2168 case glslang::EOpLessThanEqual:
2169 case glslang::EOpGreaterThanEqual:
2170 case glslang::EOpEqual:
2171 case glslang::EOpNotEqual:
2172 case glslang::EOpVectorEqual:
2173 case glslang::EOpVectorNotEqual:
2174 comparison = true;
2175 break;
2176 default:
2177 break;
2178 }
2179
2180 if (binOp != spv::OpNop) {
2181 if (builder.isMatrix(left) || builder.isMatrix(right)) {
2182 switch (binOp) {
2183 case spv::OpMatrixTimesScalar:
2184 case spv::OpVectorTimesMatrix:
2185 case spv::OpMatrixTimesVector:
2186 case spv::OpMatrixTimesMatrix:
2187 break;
2188 case spv::OpFDiv:
2189 // turn it into a multiply...
2190 assert(builder.isMatrix(left) && builder.isScalar(right));
2191 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2192 binOp = spv::OpFMul;
2193 break;
2194 default:
2195 spv::MissingFunctionality("binary operation on matrix");
2196 break;
2197 }
2198
2199 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2200 builder.setPrecision(id, precision);
2201
2202 return id;
2203 }
2204
2205 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002206 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002207 builder.promoteScalar(precision, left, right);
2208
2209 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2210 builder.setPrecision(id, precision);
2211
2212 return id;
2213 }
2214
2215 if (! comparison)
2216 return 0;
2217
2218 // Comparison instructions
2219
2220 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2221 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2222
2223 return builder.createCompare(precision, left, right, op == glslang::EOpEqual);
2224 }
2225
2226 switch (op) {
2227 case glslang::EOpLessThan:
2228 if (isFloat)
2229 binOp = spv::OpFOrdLessThan;
2230 else if (isUnsigned)
2231 binOp = spv::OpULessThan;
2232 else
2233 binOp = spv::OpSLessThan;
2234 break;
2235 case glslang::EOpGreaterThan:
2236 if (isFloat)
2237 binOp = spv::OpFOrdGreaterThan;
2238 else if (isUnsigned)
2239 binOp = spv::OpUGreaterThan;
2240 else
2241 binOp = spv::OpSGreaterThan;
2242 break;
2243 case glslang::EOpLessThanEqual:
2244 if (isFloat)
2245 binOp = spv::OpFOrdLessThanEqual;
2246 else if (isUnsigned)
2247 binOp = spv::OpULessThanEqual;
2248 else
2249 binOp = spv::OpSLessThanEqual;
2250 break;
2251 case glslang::EOpGreaterThanEqual:
2252 if (isFloat)
2253 binOp = spv::OpFOrdGreaterThanEqual;
2254 else if (isUnsigned)
2255 binOp = spv::OpUGreaterThanEqual;
2256 else
2257 binOp = spv::OpSGreaterThanEqual;
2258 break;
2259 case glslang::EOpEqual:
2260 case glslang::EOpVectorEqual:
2261 if (isFloat)
2262 binOp = spv::OpFOrdEqual;
2263 else
2264 binOp = spv::OpIEqual;
2265 break;
2266 case glslang::EOpNotEqual:
2267 case glslang::EOpVectorNotEqual:
2268 if (isFloat)
2269 binOp = spv::OpFOrdNotEqual;
2270 else
2271 binOp = spv::OpINotEqual;
2272 break;
2273 default:
2274 break;
2275 }
2276
2277 if (binOp != spv::OpNop) {
2278 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2279 builder.setPrecision(id, precision);
2280
2281 return id;
2282 }
2283
2284 return 0;
2285}
2286
Rex Xu04db3f52015-09-16 11:44:02 +08002287spv::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 -06002288{
2289 spv::Op unaryOp = spv::OpNop;
2290 int libCall = -1;
Rex Xu04db3f52015-09-16 11:44:02 +08002291 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002292
2293 switch (op) {
2294 case glslang::EOpNegative:
2295 if (isFloat)
2296 unaryOp = spv::OpFNegate;
2297 else
2298 unaryOp = spv::OpSNegate;
2299 break;
2300
2301 case glslang::EOpLogicalNot:
2302 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002303 unaryOp = spv::OpLogicalNot;
2304 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002305 case glslang::EOpBitwiseNot:
2306 unaryOp = spv::OpNot;
2307 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002308
John Kessenich140f3df2015-06-26 16:58:36 -06002309 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002310 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002311 break;
2312 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002313 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002314 break;
2315 case glslang::EOpTranspose:
2316 unaryOp = spv::OpTranspose;
2317 break;
2318
2319 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002320 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002321 break;
2322 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002323 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002324 break;
2325 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002326 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002327 break;
2328 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002329 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002330 break;
2331 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002332 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002333 break;
2334 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002335 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002336 break;
2337 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002338 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002339 break;
2340 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002341 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002342 break;
2343
2344 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002345 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002346 break;
2347 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002348 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002349 break;
2350 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002351 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002352 break;
2353 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002354 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002355 break;
2356 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002357 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002358 break;
2359 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002360 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002361 break;
2362
2363 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002364 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002365 break;
2366 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002367 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002368 break;
2369
2370 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002371 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002372 break;
2373 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002374 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002375 break;
2376 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002377 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002378 break;
2379 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002380 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002381 break;
2382 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002383 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002384 break;
2385 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002386 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002387 break;
2388
2389 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002390 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002391 break;
2392 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002393 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002394 break;
2395 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002396 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002397 break;
2398 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002399 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002400 break;
2401 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002402 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002403 break;
2404 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002405 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002406 break;
2407
2408 case glslang::EOpIsNan:
2409 unaryOp = spv::OpIsNan;
2410 break;
2411 case glslang::EOpIsInf:
2412 unaryOp = spv::OpIsInf;
2413 break;
2414
John Kessenich140f3df2015-06-26 16:58:36 -06002415 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002416 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002417 break;
2418 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002419 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002420 break;
2421 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002422 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002423 break;
2424 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002425 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002426 break;
2427 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002428 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002429 break;
2430 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002431 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002432 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002433 case glslang::EOpPackSnorm4x8:
2434 libCall = spv::GLSLstd450PackSnorm4x8;
2435 break;
2436 case glslang::EOpUnpackSnorm4x8:
2437 libCall = spv::GLSLstd450UnpackSnorm4x8;
2438 break;
2439 case glslang::EOpPackUnorm4x8:
2440 libCall = spv::GLSLstd450PackUnorm4x8;
2441 break;
2442 case glslang::EOpUnpackUnorm4x8:
2443 libCall = spv::GLSLstd450UnpackUnorm4x8;
2444 break;
2445 case glslang::EOpPackDouble2x32:
2446 libCall = spv::GLSLstd450PackDouble2x32;
2447 break;
2448 case glslang::EOpUnpackDouble2x32:
2449 libCall = spv::GLSLstd450UnpackDouble2x32;
2450 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002451
2452 case glslang::EOpDPdx:
2453 unaryOp = spv::OpDPdx;
2454 break;
2455 case glslang::EOpDPdy:
2456 unaryOp = spv::OpDPdy;
2457 break;
2458 case glslang::EOpFwidth:
2459 unaryOp = spv::OpFwidth;
2460 break;
2461 case glslang::EOpDPdxFine:
2462 unaryOp = spv::OpDPdxFine;
2463 break;
2464 case glslang::EOpDPdyFine:
2465 unaryOp = spv::OpDPdyFine;
2466 break;
2467 case glslang::EOpFwidthFine:
2468 unaryOp = spv::OpFwidthFine;
2469 break;
2470 case glslang::EOpDPdxCoarse:
2471 unaryOp = spv::OpDPdxCoarse;
2472 break;
2473 case glslang::EOpDPdyCoarse:
2474 unaryOp = spv::OpDPdyCoarse;
2475 break;
2476 case glslang::EOpFwidthCoarse:
2477 unaryOp = spv::OpFwidthCoarse;
2478 break;
2479
2480 case glslang::EOpAny:
2481 unaryOp = spv::OpAny;
2482 break;
2483 case glslang::EOpAll:
2484 unaryOp = spv::OpAll;
2485 break;
2486
2487 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002488 if (isFloat)
2489 libCall = spv::GLSLstd450FAbs;
2490 else
2491 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002492 break;
2493 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002494 if (isFloat)
2495 libCall = spv::GLSLstd450FSign;
2496 else
2497 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002498 break;
2499
John Kessenichfc51d282015-08-19 13:34:18 -06002500 case glslang::EOpAtomicCounterIncrement:
2501 case glslang::EOpAtomicCounterDecrement:
2502 case glslang::EOpAtomicCounter:
2503 {
2504 // Handle all of the atomics in one place, in createAtomicOperation()
2505 std::vector<spv::Id> operands;
2506 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002507 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002508 }
2509
2510 case glslang::EOpImageLoad:
2511 unaryOp = spv::OpImageRead;
2512 break;
2513
2514 case glslang::EOpBitFieldReverse:
2515 unaryOp = spv::OpBitReverse;
2516 break;
2517 case glslang::EOpBitCount:
2518 unaryOp = spv::OpBitCount;
2519 break;
2520 case glslang::EOpFindLSB:
2521 libCall = spv::GLSLstd450FindILSB;
2522 break;
2523 case glslang::EOpFindMSB:
2524 spv::MissingFunctionality("signed vs. unsigned FindMSB");
2525 libCall = spv::GLSLstd450FindSMSB;
2526 break;
2527
John Kessenich140f3df2015-06-26 16:58:36 -06002528 default:
2529 return 0;
2530 }
2531
2532 spv::Id id;
2533 if (libCall >= 0) {
2534 std::vector<spv::Id> args;
2535 args.push_back(operand);
2536 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2537 } else
2538 id = builder.createUnaryOp(unaryOp, typeId, operand);
2539
2540 builder.setPrecision(id, precision);
2541
2542 return id;
2543}
2544
2545spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2546{
2547 spv::Op convOp = spv::OpNop;
2548 spv::Id zero = 0;
2549 spv::Id one = 0;
2550
2551 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2552
2553 switch (op) {
2554 case glslang::EOpConvIntToBool:
2555 case glslang::EOpConvUintToBool:
2556 zero = builder.makeUintConstant(0);
2557 zero = makeSmearedConstant(zero, vectorSize);
2558 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2559
2560 case glslang::EOpConvFloatToBool:
2561 zero = builder.makeFloatConstant(0.0F);
2562 zero = makeSmearedConstant(zero, vectorSize);
2563 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2564
2565 case glslang::EOpConvDoubleToBool:
2566 zero = builder.makeDoubleConstant(0.0);
2567 zero = makeSmearedConstant(zero, vectorSize);
2568 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2569
2570 case glslang::EOpConvBoolToFloat:
2571 convOp = spv::OpSelect;
2572 zero = builder.makeFloatConstant(0.0);
2573 one = builder.makeFloatConstant(1.0);
2574 break;
2575 case glslang::EOpConvBoolToDouble:
2576 convOp = spv::OpSelect;
2577 zero = builder.makeDoubleConstant(0.0);
2578 one = builder.makeDoubleConstant(1.0);
2579 break;
2580 case glslang::EOpConvBoolToInt:
2581 zero = builder.makeIntConstant(0);
2582 one = builder.makeIntConstant(1);
2583 convOp = spv::OpSelect;
2584 break;
2585 case glslang::EOpConvBoolToUint:
2586 zero = builder.makeUintConstant(0);
2587 one = builder.makeUintConstant(1);
2588 convOp = spv::OpSelect;
2589 break;
2590
2591 case glslang::EOpConvIntToFloat:
2592 case glslang::EOpConvIntToDouble:
2593 convOp = spv::OpConvertSToF;
2594 break;
2595
2596 case glslang::EOpConvUintToFloat:
2597 case glslang::EOpConvUintToDouble:
2598 convOp = spv::OpConvertUToF;
2599 break;
2600
2601 case glslang::EOpConvDoubleToFloat:
2602 case glslang::EOpConvFloatToDouble:
2603 convOp = spv::OpFConvert;
2604 break;
2605
2606 case glslang::EOpConvFloatToInt:
2607 case glslang::EOpConvDoubleToInt:
2608 convOp = spv::OpConvertFToS;
2609 break;
2610
2611 case glslang::EOpConvUintToInt:
2612 case glslang::EOpConvIntToUint:
2613 convOp = spv::OpBitcast;
2614 break;
2615
2616 case glslang::EOpConvFloatToUint:
2617 case glslang::EOpConvDoubleToUint:
2618 convOp = spv::OpConvertFToU;
2619 break;
2620 default:
2621 break;
2622 }
2623
2624 spv::Id result = 0;
2625 if (convOp == spv::OpNop)
2626 return result;
2627
2628 if (convOp == spv::OpSelect) {
2629 zero = makeSmearedConstant(zero, vectorSize);
2630 one = makeSmearedConstant(one, vectorSize);
2631 result = builder.createTriOp(convOp, destType, operand, one, zero);
2632 } else
2633 result = builder.createUnaryOp(convOp, destType, operand);
2634
2635 builder.setPrecision(result, precision);
2636
2637 return result;
2638}
2639
2640spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2641{
2642 if (vectorSize == 0)
2643 return constant;
2644
2645 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2646 std::vector<spv::Id> components;
2647 for (int c = 0; c < vectorSize; ++c)
2648 components.push_back(constant);
2649 return builder.makeCompositeConstant(vectorTypeId, components);
2650}
2651
John Kessenich426394d2015-07-23 10:22:48 -06002652// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002653spv::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 -06002654{
2655 spv::Op opCode = spv::OpNop;
2656
2657 switch (op) {
2658 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002659 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002660 opCode = spv::OpAtomicIAdd;
2661 break;
2662 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002663 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002664 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002665 break;
2666 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002667 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002668 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002669 break;
2670 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002671 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002672 opCode = spv::OpAtomicAnd;
2673 break;
2674 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002675 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002676 opCode = spv::OpAtomicOr;
2677 break;
2678 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002679 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002680 opCode = spv::OpAtomicXor;
2681 break;
2682 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002683 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002684 opCode = spv::OpAtomicExchange;
2685 break;
2686 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002687 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002688 opCode = spv::OpAtomicCompareExchange;
2689 break;
2690 case glslang::EOpAtomicCounterIncrement:
2691 opCode = spv::OpAtomicIIncrement;
2692 break;
2693 case glslang::EOpAtomicCounterDecrement:
2694 opCode = spv::OpAtomicIDecrement;
2695 break;
2696 case glslang::EOpAtomicCounter:
2697 opCode = spv::OpAtomicLoad;
2698 break;
2699 default:
2700 spv::MissingFunctionality("missing nested atomic");
2701 break;
2702 }
2703
2704 // Sort out the operands
2705 // - mapping from glslang -> SPV
2706 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002707 // - compare-exchange swaps the value and comparator
2708 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002709 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2710 auto opIt = operands.begin(); // walk the glslang operands
2711 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002712 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2713 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2714 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002715 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2716 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002717 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002718 spvAtomicOperands.push_back(*(opIt + 1));
2719 spvAtomicOperands.push_back(*opIt);
2720 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002721 }
John Kessenich426394d2015-07-23 10:22:48 -06002722
John Kessenich3e60a6f2015-09-14 22:45:16 -06002723 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002724 for (; opIt != operands.end(); ++opIt)
2725 spvAtomicOperands.push_back(*opIt);
2726
2727 return builder.createOp(opCode, typeId, spvAtomicOperands);
2728}
2729
John Kessenich5e4b1242015-08-06 22:53:06 -06002730spv::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 -06002731{
John Kessenich5e4b1242015-08-06 22:53:06 -06002732 bool isUnsigned = typeProxy == glslang::EbtUint;
2733 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2734
John Kessenich140f3df2015-06-26 16:58:36 -06002735 spv::Op opCode = spv::OpNop;
2736 int libCall = -1;
2737
2738 switch (op) {
2739 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002740 if (isFloat)
2741 libCall = spv::GLSLstd450FMin;
2742 else if (isUnsigned)
2743 libCall = spv::GLSLstd450UMin;
2744 else
2745 libCall = spv::GLSLstd450SMin;
John Kessenich140f3df2015-06-26 16:58:36 -06002746 break;
2747 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002748 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002749 break;
2750 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002751 if (isFloat)
2752 libCall = spv::GLSLstd450FMax;
2753 else if (isUnsigned)
2754 libCall = spv::GLSLstd450UMax;
2755 else
2756 libCall = spv::GLSLstd450SMax;
John Kessenich140f3df2015-06-26 16:58:36 -06002757 break;
2758 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002759 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002760 break;
2761 case glslang::EOpDot:
2762 opCode = spv::OpDot;
2763 break;
2764 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002765 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002766 break;
2767
2768 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002769 if (isFloat)
2770 libCall = spv::GLSLstd450FClamp;
2771 else if (isUnsigned)
2772 libCall = spv::GLSLstd450UClamp;
2773 else
2774 libCall = spv::GLSLstd450SClamp;
John Kessenich140f3df2015-06-26 16:58:36 -06002775 break;
2776 case glslang::EOpMix:
John Kessenich5e4b1242015-08-06 22:53:06 -06002777 libCall = spv::GLSLstd450Mix;
John Kessenich140f3df2015-06-26 16:58:36 -06002778 break;
2779 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002780 libCall = spv::GLSLstd450Step;
John Kessenich140f3df2015-06-26 16:58:36 -06002781 break;
2782 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002783 libCall = spv::GLSLstd450SmoothStep;
John Kessenich140f3df2015-06-26 16:58:36 -06002784 break;
2785
2786 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002787 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002788 break;
2789 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002790 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002791 break;
2792 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002793 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002794 break;
2795 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002796 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002797 break;
2798 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002799 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002800 break;
John Kessenich426394d2015-07-23 10:22:48 -06002801
John Kessenich140f3df2015-06-26 16:58:36 -06002802 default:
2803 return 0;
2804 }
2805
2806 spv::Id id = 0;
2807 if (libCall >= 0)
2808 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, operands);
2809 else {
2810 switch (operands.size()) {
2811 case 0:
2812 // should all be handled by visitAggregate and createNoArgOperation
2813 assert(0);
2814 return 0;
2815 case 1:
2816 // should all be handled by createUnaryOperation
2817 assert(0);
2818 return 0;
2819 case 2:
2820 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
2821 break;
2822 case 3:
John Kessenich426394d2015-07-23 10:22:48 -06002823 id = builder.createTriOp(opCode, typeId, operands[0], operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002824 break;
2825 default:
2826 // These do not exist yet
2827 assert(0 && "operation with more than 3 operands");
2828 break;
2829 }
2830 }
2831
2832 builder.setPrecision(id, precision);
2833
2834 return id;
2835}
2836
2837// Intrinsics with no arguments, no return value, and no precision.
2838spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
2839{
2840 // TODO: get the barrier operands correct
2841
2842 switch (op) {
2843 case glslang::EOpEmitVertex:
2844 builder.createNoResultOp(spv::OpEmitVertex);
2845 return 0;
2846 case glslang::EOpEndPrimitive:
2847 builder.createNoResultOp(spv::OpEndPrimitive);
2848 return 0;
2849 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002850 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
2851 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06002852 return 0;
2853 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002854 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06002855 return 0;
2856 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06002857 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002858 return 0;
2859 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06002860 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002861 return 0;
2862 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06002863 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002864 return 0;
2865 case glslang::EOpMemoryBarrierShared:
John Kessenich5e4b1242015-08-06 22:53:06 -06002866 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupLocalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002867 return 0;
2868 case glslang::EOpGroupMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06002869 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupGlobalMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06002870 return 0;
2871 default:
2872 spv::MissingFunctionality("operation with no arguments");
2873 return 0;
2874 }
2875}
2876
2877spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
2878{
John Kessenich2f273362015-07-18 22:34:27 -06002879 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06002880 spv::Id id;
2881 if (symbolValues.end() != iter) {
2882 id = iter->second;
2883 return id;
2884 }
2885
2886 // it was not found, create it
2887 id = createSpvVariable(symbol);
2888 symbolValues[symbol->getId()] = id;
2889
2890 if (! symbol->getType().isStruct()) {
2891 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
2892 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
2893 if (symbol->getQualifier().hasLocation())
2894 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
2895 if (symbol->getQualifier().hasIndex())
2896 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
2897 if (symbol->getQualifier().hasComponent())
2898 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
2899 if (glslangIntermediate->getXfbMode()) {
2900 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002901 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002902 if (symbol->getQualifier().hasXfbBuffer())
2903 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2904 if (symbol->getQualifier().hasXfbOffset())
2905 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
2906 }
2907 }
2908
2909 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
2910 if (symbol->getQualifier().hasStream())
2911 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
2912 if (symbol->getQualifier().hasSet())
2913 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
2914 if (symbol->getQualifier().hasBinding())
2915 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
2916 if (glslangIntermediate->getXfbMode()) {
2917 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06002918 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06002919 if (symbol->getQualifier().hasXfbBuffer())
2920 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
2921 }
2922
2923 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06002924 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06002925 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06002926 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06002927
2928 if (linkageOnly)
2929 builder.addDecoration(id, spv::DecorationNoStaticUse);
2930
2931 return id;
2932}
2933
2934void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
2935{
2936 if (dec != spv::BadValue)
2937 builder.addDecoration(id, dec);
2938}
2939
2940void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
2941{
2942 if (dec != spv::BadValue)
2943 builder.addMemberDecoration(id, (unsigned)member, dec);
2944}
2945
2946// Use 'consts' as the flattened glslang source of scalar constants to recursively
2947// build the aggregate SPIR-V constant.
2948//
2949// If there are not enough elements present in 'consts', 0 will be substituted;
2950// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
2951//
2952spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst)
2953{
2954 // vector of constants for SPIR-V
2955 std::vector<spv::Id> spvConsts;
2956
2957 // Type is used for struct and array constants
2958 spv::Id typeId = convertGlslangToSpvType(glslangType);
2959
2960 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002961 glslang::TType elementType(glslangType, 0);
2962 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich140f3df2015-06-26 16:58:36 -06002963 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst));
2964 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06002965 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06002966 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
2967 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst));
2968 } else if (glslangType.getStruct()) {
2969 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
2970 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
2971 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst));
2972 } else if (glslangType.isVector()) {
2973 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
2974 bool zero = nextConst >= consts.size();
2975 switch (glslangType.getBasicType()) {
2976 case glslang::EbtInt:
2977 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
2978 break;
2979 case glslang::EbtUint:
2980 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
2981 break;
2982 case glslang::EbtFloat:
2983 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
2984 break;
2985 case glslang::EbtDouble:
2986 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
2987 break;
2988 case glslang::EbtBool:
2989 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
2990 break;
2991 default:
2992 spv::MissingFunctionality("constant vector type");
2993 break;
2994 }
2995 ++nextConst;
2996 }
2997 } else {
2998 // we have a non-aggregate (scalar) constant
2999 bool zero = nextConst >= consts.size();
3000 spv::Id scalar = 0;
3001 switch (glslangType.getBasicType()) {
3002 case glslang::EbtInt:
3003 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst());
3004 break;
3005 case glslang::EbtUint:
3006 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst());
3007 break;
3008 case glslang::EbtFloat:
3009 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst());
3010 break;
3011 case glslang::EbtDouble:
3012 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst());
3013 break;
3014 case glslang::EbtBool:
3015 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst());
3016 break;
3017 default:
3018 spv::MissingFunctionality("constant scalar type");
3019 break;
3020 }
3021 ++nextConst;
3022 return scalar;
3023 }
3024
3025 return builder.makeCompositeConstant(typeId, spvConsts);
3026}
3027
3028}; // end anonymous namespace
3029
3030namespace glslang {
3031
John Kessenich68d78fd2015-07-12 19:28:10 -06003032void GetSpirvVersion(std::string& version)
3033{
John Kessenich9e55f632015-07-15 10:03:39 -06003034 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003035 char buf[bufSize];
John Kessenich9e55f632015-07-15 10:03:39 -06003036 snprintf(buf, bufSize, "%d, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003037 version = buf;
3038}
3039
John Kessenich140f3df2015-06-26 16:58:36 -06003040// Write SPIR-V out to a binary file
3041void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3042{
3043 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003044 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003045 for (int i = 0; i < (int)spirv.size(); ++i) {
3046 unsigned int word = spirv[i];
3047 out.write((const char*)&word, 4);
3048 }
3049 out.close();
3050}
3051
3052//
3053// Set up the glslang traversal
3054//
3055void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3056{
3057 TIntermNode* root = intermediate.getTreeRoot();
3058
3059 if (root == 0)
3060 return;
3061
3062 glslang::GetThreadPoolAllocator().push();
3063
3064 TGlslangToSpvTraverser it(&intermediate);
3065
3066 root->traverse(&it);
3067
3068 it.dumpSpv(spirv);
3069
3070 glslang::GetThreadPoolAllocator().pop();
3071}
3072
3073}; // end namespace glslang