blob: afea3bcc2417cccf159ef48eb26e2d8be27f5671 [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
John Kessenich55e7d112015-11-15 21:33:39 -070063// For low-order part of the generator's magic number. Bump up
64// when there is a change in the style (e.g., if SSA form changes,
65// or a different instruction sequence to do something gets used).
66const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060067
68//
69// The main holder of information for translating glslang to SPIR-V.
70//
71// Derives from the AST walking base class.
72//
73class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
74public:
75 TGlslangToSpvTraverser(const glslang::TIntermediate*);
76 virtual ~TGlslangToSpvTraverser();
77
78 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
79 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
80 void visitConstantUnion(glslang::TIntermConstantUnion*);
81 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
82 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
83 void visitSymbol(glslang::TIntermSymbol* symbol);
84 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
85 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
86 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
87
John Kessenich7ba63412015-12-20 17:37:07 -070088 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060089
90protected:
91 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
92 spv::Id getSampledType(const glslang::TSampler&);
93 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kessenich3ac051e2015-12-20 11:29:16 -070094 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenichf85e8062015-12-19 13:57:10 -070095 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -070096 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
97 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
98 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -060099
100 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
101 void makeFunctions(const glslang::TIntermSequence&);
102 void makeGlobalInitializers(const glslang::TIntermSequence&);
103 void visitFunctions(const glslang::TIntermSequence&);
104 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800105 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600106 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
107 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600108 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
109
110 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700111 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800112 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 -0600113 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
114 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800115 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 -0600116 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 -0600117 spv::Id createNoArgOperation(glslang::TOperator op);
118 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
119 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700120 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600121 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700122 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
123 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600124 bool isTrivialLeaf(const glslang::TIntermTyped* node);
125 bool isTrivial(const glslang::TIntermTyped* node);
126 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600127
128 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700129 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600130 int sequenceDepth;
131
132 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
133 spv::Builder builder;
134 bool inMain;
135 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700136 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700137 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600138 const glslang::TIntermediate* glslangIntermediate;
139 spv::Id stdBuiltins;
140
John Kessenich2f273362015-07-18 22:34:27 -0600141 std::unordered_map<int, spv::Id> symbolValues;
142 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
143 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700144 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600145 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 -0600146 std::stack<bool> breakForLoop; // false means break for switch
147 std::stack<glslang::TIntermTyped*> loopTerminal; // code from the last part of a for loop: for(...; ...; terminal), needed for e.g., continue };
148};
149
150//
151// Helper functions for translating glslang representations to SPIR-V enumerants.
152//
153
154// Translate glslang profile to SPIR-V source language.
155spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
156{
157 switch (profile) {
158 case ENoProfile:
159 case ECoreProfile:
160 case ECompatibilityProfile:
161 return spv::SourceLanguageGLSL;
162 case EEsProfile:
163 return spv::SourceLanguageESSL;
164 default:
165 return spv::SourceLanguageUnknown;
166 }
167}
168
169// Translate glslang language (stage) to SPIR-V execution model.
170spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
171{
172 switch (stage) {
173 case EShLangVertex: return spv::ExecutionModelVertex;
174 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
175 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
176 case EShLangGeometry: return spv::ExecutionModelGeometry;
177 case EShLangFragment: return spv::ExecutionModelFragment;
178 case EShLangCompute: return spv::ExecutionModelGLCompute;
179 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700180 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600181 return spv::ExecutionModelFragment;
182 }
183}
184
185// Translate glslang type to SPIR-V storage class.
186spv::StorageClass TranslateStorageClass(const glslang::TType& type)
187{
188 if (type.getQualifier().isPipeInput())
189 return spv::StorageClassInput;
190 else if (type.getQualifier().isPipeOutput())
191 return spv::StorageClassOutput;
192 else if (type.getQualifier().isUniformOrBuffer()) {
193 if (type.getBasicType() == glslang::EbtBlock)
194 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800195 else if (type.getBasicType() == glslang::EbtAtomicUint)
196 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600197 else
198 return spv::StorageClassUniformConstant;
199 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
200 } else {
201 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700202 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
203 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600204 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
205 case glslang::EvqTemporary: return spv::StorageClassFunction;
206 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700207 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600208 return spv::StorageClassFunction;
209 }
210 }
211}
212
213// Translate glslang sampler type to SPIR-V dimensionality.
214spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
215{
216 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700217 case glslang::Esd1D: return spv::Dim1D;
218 case glslang::Esd2D: return spv::Dim2D;
219 case glslang::Esd3D: return spv::Dim3D;
220 case glslang::EsdCube: return spv::DimCube;
221 case glslang::EsdRect: return spv::DimRect;
222 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600223 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700224 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600225 return spv::Dim2D;
226 }
227}
228
229// Translate glslang type to SPIR-V precision decorations.
230spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
231{
232 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700233 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600234 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
235 case glslang::EpqHigh: return spv::NoPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600236 default:
237 return spv::NoPrecision;
238 }
239}
240
241// Translate glslang type to SPIR-V block decorations.
242spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
243{
244 if (type.getBasicType() == glslang::EbtBlock) {
245 switch (type.getQualifier().storage) {
246 case glslang::EvqUniform: return spv::DecorationBlock;
247 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
248 case glslang::EvqVaryingIn: return spv::DecorationBlock;
249 case glslang::EvqVaryingOut: return spv::DecorationBlock;
250 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700251 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600252 break;
253 }
254 }
255
256 return (spv::Decoration)spv::BadValue;
257}
258
259// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700260spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600261{
262 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700263 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600264 case glslang::ElmRowMajor:
265 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700266 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600267 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700268 default:
269 // opaque layouts don't need a majorness
270 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600271 }
272 } else {
273 switch (type.getBasicType()) {
274 default:
275 return (spv::Decoration)spv::BadValue;
276 break;
277 case glslang::EbtBlock:
278 switch (type.getQualifier().storage) {
279 case glslang::EvqUniform:
280 case glslang::EvqBuffer:
281 switch (type.getQualifier().layoutPacking) {
282 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600283 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
284 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600285 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 }
287 case glslang::EvqVaryingIn:
288 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700289 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600290 return (spv::Decoration)spv::BadValue;
291 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700292 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600293 return (spv::Decoration)spv::BadValue;
294 }
295 }
296 }
297}
298
299// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700300// Returns spv::Decoration(spv::BadValue) when no decoration
301// should be applied.
John Kessenich140f3df2015-06-26 16:58:36 -0600302spv::Decoration TranslateInterpolationDecoration(const glslang::TType& type)
303{
John Kessenich55e7d112015-11-15 21:33:39 -0700304 if (type.getQualifier().smooth) {
305 // Smooth decoration doesn't exist in SPIR-V 1.0
306 return (spv::Decoration)spv::BadValue;
307 }
John Kessenich140f3df2015-06-26 16:58:36 -0600308 if (type.getQualifier().nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700309 return spv::DecorationNoPerspective;
John Kessenich140f3df2015-06-26 16:58:36 -0600310 else if (type.getQualifier().patch)
311 return spv::DecorationPatch;
312 else if (type.getQualifier().flat)
313 return spv::DecorationFlat;
314 else if (type.getQualifier().centroid)
315 return spv::DecorationCentroid;
316 else if (type.getQualifier().sample)
317 return spv::DecorationSample;
318 else
319 return (spv::Decoration)spv::BadValue;
320}
321
322// If glslang type is invaraiant, return SPIR-V invariant decoration.
323spv::Decoration TranslateInvariantDecoration(const glslang::TType& type)
324{
325 if (type.getQualifier().invariant)
326 return spv::DecorationInvariant;
327 else
328 return (spv::Decoration)spv::BadValue;
329}
330
331// Translate glslang built-in variable to SPIR-V built in decoration.
332spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
333{
334 switch (builtIn) {
335 case glslang::EbvPosition: return spv::BuiltInPosition;
336 case glslang::EbvPointSize: return spv::BuiltInPointSize;
John Kessenich140f3df2015-06-26 16:58:36 -0600337 case glslang::EbvClipDistance: return spv::BuiltInClipDistance;
338 case glslang::EbvCullDistance: return spv::BuiltInCullDistance;
339 case glslang::EbvVertexId: return spv::BuiltInVertexId;
340 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600341 case glslang::EbvBaseVertex:
342 case glslang::EbvBaseInstance:
343 case glslang::EbvDrawId:
344 // TODO: Add SPIR-V builtin ID.
345 spv::MissingFunctionality("Draw parameters");
346 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600347 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
348 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
349 case glslang::EbvLayer: return spv::BuiltInLayer;
350 case glslang::EbvViewportIndex: return spv::BuiltInViewportIndex;
351 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
352 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
353 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
354 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
355 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
356 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
357 case glslang::EbvFace: return spv::BuiltInFrontFacing;
358 case glslang::EbvSampleId: return spv::BuiltInSampleId;
359 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
360 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600361 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
362 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
363 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
364 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
365 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
366 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
367 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
368 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
369 default: return (spv::BuiltIn)spv::BadValue;
370 }
371}
372
Rex Xufc618912015-09-09 16:42:49 +0800373// Translate glslang image layout format to SPIR-V image format.
374spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
375{
376 assert(type.getBasicType() == glslang::EbtSampler);
377
378 switch (type.getQualifier().layoutFormat) {
379 case glslang::ElfNone: return spv::ImageFormatUnknown;
380 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
381 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
382 case glslang::ElfR32f: return spv::ImageFormatR32f;
383 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
384 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
385 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
386 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
387 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
388 case glslang::ElfR16f: return spv::ImageFormatR16f;
389 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
390 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
391 case glslang::ElfRg16: return spv::ImageFormatRg16;
392 case glslang::ElfRg8: return spv::ImageFormatRg8;
393 case glslang::ElfR16: return spv::ImageFormatR16;
394 case glslang::ElfR8: return spv::ImageFormatR8;
395 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
396 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
397 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
398 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
399 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
400 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
401 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
402 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
403 case glslang::ElfR32i: return spv::ImageFormatR32i;
404 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
405 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
406 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
407 case glslang::ElfR16i: return spv::ImageFormatR16i;
408 case glslang::ElfR8i: return spv::ImageFormatR8i;
409 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
410 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
411 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
412 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
413 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
414 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
415 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
416 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
417 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
418 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
419 default: return (spv::ImageFormat)spv::BadValue;
420 }
421}
422
John Kessenich140f3df2015-06-26 16:58:36 -0600423//
424// Implement the TGlslangToSpvTraverser class.
425//
426
427TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
428 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700429 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600430 inMain(false), mainTerminated(false), linkageOnly(false),
431 glslangIntermediate(glslangIntermediate)
432{
433 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
434
435 builder.clearAccessChain();
436 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
437 stdBuiltins = builder.import("GLSL.std.450");
438 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
439 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700440 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600441
442 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600443 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
444 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600445 builder.addSourceExtension(it->c_str());
446
447 // Add the top-level modes for this shader.
448
449 if (glslangIntermediate->getXfbMode())
450 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
451
452 unsigned int mode;
453 switch (glslangIntermediate->getStage()) {
454 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600455 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600456 break;
457
458 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600459 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600460 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
461 break;
462
463 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600464 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600465 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700466 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
467 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
468 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600469 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600470 }
471 if (mode != spv::BadValue)
472 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
473
John Kesseniche6903322015-10-13 16:29:02 -0600474 switch (glslangIntermediate->getVertexSpacing()) {
475 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
476 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
477 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
478 default: mode = spv::BadValue; break;
479 }
480 if (mode != spv::BadValue)
481 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
482
483 switch (glslangIntermediate->getVertexOrder()) {
484 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
485 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
486 default: mode = spv::BadValue; break;
487 }
488 if (mode != spv::BadValue)
489 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
490
491 if (glslangIntermediate->getPointMode())
492 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600493 break;
494
495 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600496 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600497 switch (glslangIntermediate->getInputPrimitive()) {
498 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
499 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
500 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700501 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600502 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
503 default: mode = spv::BadValue; break;
504 }
505 if (mode != spv::BadValue)
506 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600507
John Kessenich140f3df2015-06-26 16:58:36 -0600508 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
509
510 switch (glslangIntermediate->getOutputPrimitive()) {
511 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
512 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
513 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
514 default: mode = spv::BadValue; break;
515 }
516 if (mode != spv::BadValue)
517 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
518 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
519 break;
520
521 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600522 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600523 if (glslangIntermediate->getPixelCenterInteger())
524 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600525
John Kessenich140f3df2015-06-26 16:58:36 -0600526 if (glslangIntermediate->getOriginUpperLeft())
527 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600528 else
529 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600530
531 if (glslangIntermediate->getEarlyFragmentTests())
532 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
533
534 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600535 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
536 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
537 default: mode = spv::BadValue; break;
538 }
539 if (mode != spv::BadValue)
540 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
541
542 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
543 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600544 break;
545
546 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600547 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600548 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
549 glslangIntermediate->getLocalSize(1),
550 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600551 break;
552
553 default:
554 break;
555 }
556
557}
558
John Kessenich7ba63412015-12-20 17:37:07 -0700559// Finish everything and dump
560void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
561{
562 // finish off the entry-point SPV instruction by adding the Input/Output <id>
563 for (auto it : iOSet)
564 entryPoint->addIdOperand(it);
565
566 builder.dump(out);
567}
568
John Kessenich140f3df2015-06-26 16:58:36 -0600569TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
570{
571 if (! mainTerminated) {
572 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
573 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600574 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600575 }
576}
577
578//
579// Implement the traversal functions.
580//
581// Return true from interior nodes to have the external traversal
582// continue on to children. Return false if children were
583// already processed.
584//
585
586//
587// Symbols can turn into
588// - uniform/input reads
589// - output writes
590// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
591// - something simple that degenerates into the last bullet
592//
593void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
594{
595 // getSymbolId() will set up all the IO decorations on the first call.
596 // Formal function parameters were mapped during makeFunctions().
597 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700598
599 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
600 if (builder.isPointer(id)) {
601 spv::StorageClass sc = builder.getStorageClass(id);
602 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
603 iOSet.insert(id);
604 }
605
606 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600607 if (! linkageOnly) {
608 // Prepare to generate code for the access
609
610 // L-value chains will be computed left to right. We're on the symbol now,
611 // which is the left-most part of the access chain, so now is "clear" time,
612 // followed by setting the base.
613 builder.clearAccessChain();
614
615 // For now, we consider all user variables as being in memory, so they are pointers,
616 // except for "const in" arguments to a function, which are an intermediate object.
617 // See comments in handleUserFunctionCall().
618 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
619 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
620 builder.setAccessChainRValue(id);
621 else
622 builder.setAccessChainLValue(id);
623 }
624}
625
626bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
627{
628 // First, handle special cases
629 switch (node->getOp()) {
630 case glslang::EOpAssign:
631 case glslang::EOpAddAssign:
632 case glslang::EOpSubAssign:
633 case glslang::EOpMulAssign:
634 case glslang::EOpVectorTimesMatrixAssign:
635 case glslang::EOpVectorTimesScalarAssign:
636 case glslang::EOpMatrixTimesScalarAssign:
637 case glslang::EOpMatrixTimesMatrixAssign:
638 case glslang::EOpDivAssign:
639 case glslang::EOpModAssign:
640 case glslang::EOpAndAssign:
641 case glslang::EOpInclusiveOrAssign:
642 case glslang::EOpExclusiveOrAssign:
643 case glslang::EOpLeftShiftAssign:
644 case glslang::EOpRightShiftAssign:
645 // A bin-op assign "a += b" means the same thing as "a = a + b"
646 // where a is evaluated before b. For a simple assignment, GLSL
647 // says to evaluate the left before the right. So, always, left
648 // node then right node.
649 {
650 // get the left l-value, save it away
651 builder.clearAccessChain();
652 node->getLeft()->traverse(this);
653 spv::Builder::AccessChain lValue = builder.getAccessChain();
654
655 // evaluate the right
656 builder.clearAccessChain();
657 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600658 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600659
660 if (node->getOp() != glslang::EOpAssign) {
661 // the left is also an r-value
662 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600663 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600664
665 // do the operation
666 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
667 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
668 node->getType().getBasicType());
669
670 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700671 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600672 }
673
674 // store the result
675 builder.setAccessChain(lValue);
676 builder.accessChainStore(rValue);
677
678 // assignments are expressions having an rValue after they are evaluated...
679 builder.clearAccessChain();
680 builder.setAccessChainRValue(rValue);
681 }
682 return false;
683 case glslang::EOpIndexDirect:
684 case glslang::EOpIndexDirectStruct:
685 {
686 // Get the left part of the access chain.
687 node->getLeft()->traverse(this);
688
689 // Add the next element in the chain
690
John Kessenich55e7d112015-11-15 21:33:39 -0700691 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600692 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
693 // This may be, e.g., an anonymous block-member selection, which generally need
694 // index remapping due to hidden members in anonymous blocks.
695 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700696 assert(remapper.size() > 0);
697 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600698 }
699
700 if (! node->getLeft()->getType().isArray() &&
701 node->getLeft()->getType().isVector() &&
702 node->getOp() == glslang::EOpIndexDirect) {
703 // This is essentially a hard-coded vector swizzle of size 1,
704 // so short circuit the access-chain stuff with a swizzle.
705 std::vector<unsigned> swizzle;
706 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600707 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600708 } else {
709 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600710 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600711 }
712 }
713 return false;
714 case glslang::EOpIndexIndirect:
715 {
716 // Structure or array or vector indirection.
717 // Will use native SPIR-V access-chain for struct and array indirection;
718 // matrices are arrays of vectors, so will also work for a matrix.
719 // Will use the access chain's 'component' for variable index into a vector.
720
721 // This adapter is building access chains left to right.
722 // Set up the access chain to the left.
723 node->getLeft()->traverse(this);
724
725 // save it so that computing the right side doesn't trash it
726 spv::Builder::AccessChain partial = builder.getAccessChain();
727
728 // compute the next index in the chain
729 builder.clearAccessChain();
730 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600731 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600732
733 // restore the saved access chain
734 builder.setAccessChain(partial);
735
736 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600737 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600738 else
John Kessenichfa668da2015-09-13 14:46:30 -0600739 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600740 }
741 return false;
742 case glslang::EOpVectorSwizzle:
743 {
744 node->getLeft()->traverse(this);
745 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
746 std::vector<unsigned> swizzle;
747 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
748 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600749 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600750 }
751 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600752 case glslang::EOpLogicalOr:
753 case glslang::EOpLogicalAnd:
754 {
755
756 // These may require short circuiting, but can sometimes be done as straight
757 // binary operations. The right operand must be short circuited if it has
758 // side effects, and should probably be if it is complex.
759 if (isTrivial(node->getRight()->getAsTyped()))
760 break; // handle below as a normal binary operation
761 // otherwise, we need to do dynamic short circuiting on the right operand
762 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
763 builder.clearAccessChain();
764 builder.setAccessChainRValue(result);
765 }
766 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600767 default:
768 break;
769 }
770
771 // Assume generic binary op...
772
773 // Get the operands
774 builder.clearAccessChain();
775 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600776 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600777
778 builder.clearAccessChain();
779 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600780 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600781
782 spv::Id result;
783 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
784
785 result = createBinaryOperation(node->getOp(), precision,
786 convertGlslangToSpvType(node->getType()), left, right,
787 node->getLeft()->getType().getBasicType());
788
John Kessenich50e57562015-12-21 21:21:11 -0700789 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600790 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700791 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700792 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600793 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600794 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600795 return false;
796 }
John Kessenich140f3df2015-06-26 16:58:36 -0600797}
798
799bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
800{
John Kessenichfc51d282015-08-19 13:34:18 -0600801 spv::Id result = spv::NoResult;
802
803 // try texturing first
804 result = createImageTextureFunctionCall(node);
805 if (result != spv::NoResult) {
806 builder.clearAccessChain();
807 builder.setAccessChainRValue(result);
808
809 return false; // done with this node
810 }
811
812 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600813
814 if (node->getOp() == glslang::EOpArrayLength) {
815 // Quite special; won't want to evaluate the operand.
816
817 // Normal .length() would have been constant folded by the front-end.
818 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600819 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600820 assert(node->getOperand()->getType().isRuntimeSizedArray());
821 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
822 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600823 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
824 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600825
826 builder.clearAccessChain();
827 builder.setAccessChainRValue(length);
828
829 return false;
830 }
831
John Kessenichfc51d282015-08-19 13:34:18 -0600832 // Start by evaluating the operand
833
John Kessenich140f3df2015-06-26 16:58:36 -0600834 builder.clearAccessChain();
835 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800836
Rex Xufc618912015-09-09 16:42:49 +0800837 spv::Id operand = spv::NoResult;
838
839 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
840 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800841 node->getOp() == glslang::EOpAtomicCounter ||
842 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800843 operand = builder.accessChainGetLValue(); // Special case l-value operands
844 else
Rex Xu30f92582015-09-14 10:38:56 +0800845 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600846
847 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
848
849 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600850 if (! result)
851 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600852
853 // if not, then possibly an operation
854 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700855 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600856
857 if (result) {
858 builder.clearAccessChain();
859 builder.setAccessChainRValue(result);
860
861 return false; // done with this node
862 }
863
864 // it must be a special case, check...
865 switch (node->getOp()) {
866 case glslang::EOpPostIncrement:
867 case glslang::EOpPostDecrement:
868 case glslang::EOpPreIncrement:
869 case glslang::EOpPreDecrement:
870 {
871 // we need the integer value "1" or the floating point "1.0" to add/subtract
872 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
873 builder.makeFloatConstant(1.0F) :
874 builder.makeIntConstant(1);
875 glslang::TOperator op;
876 if (node->getOp() == glslang::EOpPreIncrement ||
877 node->getOp() == glslang::EOpPostIncrement)
878 op = glslang::EOpAdd;
879 else
880 op = glslang::EOpSub;
881
882 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
883 convertGlslangToSpvType(node->getType()), operand, one,
884 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700885 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600886
887 // The result of operation is always stored, but conditionally the
888 // consumed result. The consumed result is always an r-value.
889 builder.accessChainStore(result);
890 builder.clearAccessChain();
891 if (node->getOp() == glslang::EOpPreIncrement ||
892 node->getOp() == glslang::EOpPreDecrement)
893 builder.setAccessChainRValue(result);
894 else
895 builder.setAccessChainRValue(operand);
896 }
897
898 return false;
899
900 case glslang::EOpEmitStreamVertex:
901 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
902 return false;
903 case glslang::EOpEndStreamPrimitive:
904 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
905 return false;
906
907 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700908 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -0700909 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -0600910 }
John Kessenich140f3df2015-06-26 16:58:36 -0600911}
912
913bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
914{
John Kessenichfc51d282015-08-19 13:34:18 -0600915 spv::Id result = spv::NoResult;
916
917 // try texturing
918 result = createImageTextureFunctionCall(node);
919 if (result != spv::NoResult) {
920 builder.clearAccessChain();
921 builder.setAccessChainRValue(result);
922
923 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600924 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800925 // "imageStore" is a special case, which has no result
926 return false;
927 }
John Kessenichfc51d282015-08-19 13:34:18 -0600928
John Kessenich140f3df2015-06-26 16:58:36 -0600929 glslang::TOperator binOp = glslang::EOpNull;
930 bool reduceComparison = true;
931 bool isMatrix = false;
932 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600933 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600934
935 assert(node->getOp());
936
937 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
938
939 switch (node->getOp()) {
940 case glslang::EOpSequence:
941 {
942 if (preVisit)
943 ++sequenceDepth;
944 else
945 --sequenceDepth;
946
947 if (sequenceDepth == 1) {
948 // If this is the parent node of all the functions, we want to see them
949 // early, so all call points have actual SPIR-V functions to reference.
950 // In all cases, still let the traverser visit the children for us.
951 makeFunctions(node->getAsAggregate()->getSequence());
952
953 // Also, we want all globals initializers to go into the entry of main(), before
954 // anything else gets there, so visit out of order, doing them all now.
955 makeGlobalInitializers(node->getAsAggregate()->getSequence());
956
957 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
958 // so do them manually.
959 visitFunctions(node->getAsAggregate()->getSequence());
960
961 return false;
962 }
963
964 return true;
965 }
966 case glslang::EOpLinkerObjects:
967 {
968 if (visit == glslang::EvPreVisit)
969 linkageOnly = true;
970 else
971 linkageOnly = false;
972
973 return true;
974 }
975 case glslang::EOpComma:
976 {
977 // processing from left to right naturally leaves the right-most
978 // lying around in the access chain
979 glslang::TIntermSequence& glslangOperands = node->getSequence();
980 for (int i = 0; i < (int)glslangOperands.size(); ++i)
981 glslangOperands[i]->traverse(this);
982
983 return false;
984 }
985 case glslang::EOpFunction:
986 if (visit == glslang::EvPreVisit) {
987 if (isShaderEntrypoint(node)) {
988 inMain = true;
989 builder.setBuildPoint(shaderEntry->getLastBlock());
990 } else {
991 handleFunctionEntry(node);
992 }
993 } else {
994 if (inMain)
995 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -0600996 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600997 inMain = false;
998 }
999
1000 return true;
1001 case glslang::EOpParameters:
1002 // Parameters will have been consumed by EOpFunction processing, but not
1003 // the body, so we still visited the function node's children, making this
1004 // child redundant.
1005 return false;
1006 case glslang::EOpFunctionCall:
1007 {
1008 if (node->isUserDefined())
1009 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001010 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001011 builder.clearAccessChain();
1012 builder.setAccessChainRValue(result);
1013
1014 return false;
1015 }
1016 case glslang::EOpConstructMat2x2:
1017 case glslang::EOpConstructMat2x3:
1018 case glslang::EOpConstructMat2x4:
1019 case glslang::EOpConstructMat3x2:
1020 case glslang::EOpConstructMat3x3:
1021 case glslang::EOpConstructMat3x4:
1022 case glslang::EOpConstructMat4x2:
1023 case glslang::EOpConstructMat4x3:
1024 case glslang::EOpConstructMat4x4:
1025 case glslang::EOpConstructDMat2x2:
1026 case glslang::EOpConstructDMat2x3:
1027 case glslang::EOpConstructDMat2x4:
1028 case glslang::EOpConstructDMat3x2:
1029 case glslang::EOpConstructDMat3x3:
1030 case glslang::EOpConstructDMat3x4:
1031 case glslang::EOpConstructDMat4x2:
1032 case glslang::EOpConstructDMat4x3:
1033 case glslang::EOpConstructDMat4x4:
1034 isMatrix = true;
1035 // fall through
1036 case glslang::EOpConstructFloat:
1037 case glslang::EOpConstructVec2:
1038 case glslang::EOpConstructVec3:
1039 case glslang::EOpConstructVec4:
1040 case glslang::EOpConstructDouble:
1041 case glslang::EOpConstructDVec2:
1042 case glslang::EOpConstructDVec3:
1043 case glslang::EOpConstructDVec4:
1044 case glslang::EOpConstructBool:
1045 case glslang::EOpConstructBVec2:
1046 case glslang::EOpConstructBVec3:
1047 case glslang::EOpConstructBVec4:
1048 case glslang::EOpConstructInt:
1049 case glslang::EOpConstructIVec2:
1050 case glslang::EOpConstructIVec3:
1051 case glslang::EOpConstructIVec4:
1052 case glslang::EOpConstructUint:
1053 case glslang::EOpConstructUVec2:
1054 case glslang::EOpConstructUVec3:
1055 case glslang::EOpConstructUVec4:
1056 case glslang::EOpConstructStruct:
1057 {
1058 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001059 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001060 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1061 spv::Id constructed;
1062 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1063 std::vector<spv::Id> constituents;
1064 for (int c = 0; c < (int)arguments.size(); ++c)
1065 constituents.push_back(arguments[c]);
1066 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001067 } else if (isMatrix)
1068 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1069 else
1070 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001071
1072 builder.clearAccessChain();
1073 builder.setAccessChainRValue(constructed);
1074
1075 return false;
1076 }
1077
1078 // These six are component-wise compares with component-wise results.
1079 // Forward on to createBinaryOperation(), requesting a vector result.
1080 case glslang::EOpLessThan:
1081 case glslang::EOpGreaterThan:
1082 case glslang::EOpLessThanEqual:
1083 case glslang::EOpGreaterThanEqual:
1084 case glslang::EOpVectorEqual:
1085 case glslang::EOpVectorNotEqual:
1086 {
1087 // Map the operation to a binary
1088 binOp = node->getOp();
1089 reduceComparison = false;
1090 switch (node->getOp()) {
1091 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1092 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1093 default: binOp = node->getOp(); break;
1094 }
1095
1096 break;
1097 }
1098 case glslang::EOpMul:
1099 // compontent-wise matrix multiply
1100 binOp = glslang::EOpMul;
1101 break;
1102 case glslang::EOpOuterProduct:
1103 // two vectors multiplied to make a matrix
1104 binOp = glslang::EOpOuterProduct;
1105 break;
1106 case glslang::EOpDot:
1107 {
1108 // for scalar dot product, use multiply
1109 glslang::TIntermSequence& glslangOperands = node->getSequence();
1110 if (! glslangOperands[0]->getAsTyped()->isVector())
1111 binOp = glslang::EOpMul;
1112 break;
1113 }
1114 case glslang::EOpMod:
1115 // when an aggregate, this is the floating-point mod built-in function,
1116 // which can be emitted by the one in createBinaryOperation()
1117 binOp = glslang::EOpMod;
1118 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001119 case glslang::EOpEmitVertex:
1120 case glslang::EOpEndPrimitive:
1121 case glslang::EOpBarrier:
1122 case glslang::EOpMemoryBarrier:
1123 case glslang::EOpMemoryBarrierAtomicCounter:
1124 case glslang::EOpMemoryBarrierBuffer:
1125 case glslang::EOpMemoryBarrierImage:
1126 case glslang::EOpMemoryBarrierShared:
1127 case glslang::EOpGroupMemoryBarrier:
1128 noReturnValue = true;
1129 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1130 break;
1131
John Kessenich426394d2015-07-23 10:22:48 -06001132 case glslang::EOpAtomicAdd:
1133 case glslang::EOpAtomicMin:
1134 case glslang::EOpAtomicMax:
1135 case glslang::EOpAtomicAnd:
1136 case glslang::EOpAtomicOr:
1137 case glslang::EOpAtomicXor:
1138 case glslang::EOpAtomicExchange:
1139 case glslang::EOpAtomicCompSwap:
1140 atomic = true;
1141 break;
1142
John Kessenich140f3df2015-06-26 16:58:36 -06001143 default:
1144 break;
1145 }
1146
1147 //
1148 // See if it maps to a regular operation.
1149 //
John Kessenich140f3df2015-06-26 16:58:36 -06001150 if (binOp != glslang::EOpNull) {
1151 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1152 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1153 assert(left && right);
1154
1155 builder.clearAccessChain();
1156 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001157 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001158
1159 builder.clearAccessChain();
1160 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001161 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001162
1163 result = createBinaryOperation(binOp, precision,
1164 convertGlslangToSpvType(node->getType()), leftId, rightId,
1165 left->getType().getBasicType(), reduceComparison);
1166
1167 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001168 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001169 builder.clearAccessChain();
1170 builder.setAccessChainRValue(result);
1171
1172 return false;
1173 }
1174
John Kessenich426394d2015-07-23 10:22:48 -06001175 //
1176 // Create the list of operands.
1177 //
John Kessenich140f3df2015-06-26 16:58:36 -06001178 glslang::TIntermSequence& glslangOperands = node->getSequence();
1179 std::vector<spv::Id> operands;
1180 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1181 builder.clearAccessChain();
1182 glslangOperands[arg]->traverse(this);
1183
1184 // special case l-value operands; there are just a few
1185 bool lvalue = false;
1186 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001187 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001188 case glslang::EOpModf:
1189 if (arg == 1)
1190 lvalue = true;
1191 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001192 case glslang::EOpInterpolateAtSample:
1193 case glslang::EOpInterpolateAtOffset:
1194 if (arg == 0)
1195 lvalue = true;
1196 break;
Rex Xud4782c12015-09-06 16:30:11 +08001197 case glslang::EOpAtomicAdd:
1198 case glslang::EOpAtomicMin:
1199 case glslang::EOpAtomicMax:
1200 case glslang::EOpAtomicAnd:
1201 case glslang::EOpAtomicOr:
1202 case glslang::EOpAtomicXor:
1203 case glslang::EOpAtomicExchange:
1204 case glslang::EOpAtomicCompSwap:
1205 if (arg == 0)
1206 lvalue = true;
1207 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001208 case glslang::EOpAddCarry:
1209 case glslang::EOpSubBorrow:
1210 if (arg == 2)
1211 lvalue = true;
1212 break;
1213 case glslang::EOpUMulExtended:
1214 case glslang::EOpIMulExtended:
1215 if (arg >= 2)
1216 lvalue = true;
1217 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001218 default:
1219 break;
1220 }
1221 if (lvalue)
1222 operands.push_back(builder.accessChainGetLValue());
1223 else
John Kessenichfa668da2015-09-13 14:46:30 -06001224 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001225 }
John Kessenich426394d2015-07-23 10:22:48 -06001226
1227 if (atomic) {
1228 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001229 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001230 } else {
1231 // Pass through to generic operations.
1232 switch (glslangOperands.size()) {
1233 case 0:
1234 result = createNoArgOperation(node->getOp());
1235 break;
1236 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001237 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001238 break;
1239 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001240 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001241 break;
1242 }
John Kessenich140f3df2015-06-26 16:58:36 -06001243 }
1244
1245 if (noReturnValue)
1246 return false;
1247
1248 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001249 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001250 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001251 } else {
1252 builder.clearAccessChain();
1253 builder.setAccessChainRValue(result);
1254 return false;
1255 }
1256}
1257
1258bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1259{
1260 // This path handles both if-then-else and ?:
1261 // The if-then-else has a node type of void, while
1262 // ?: has a non-void node type
1263 spv::Id result = 0;
1264 if (node->getBasicType() != glslang::EbtVoid) {
1265 // don't handle this as just on-the-fly temporaries, because there will be two names
1266 // and better to leave SSA to later passes
1267 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1268 }
1269
1270 // emit the condition before doing anything with selection
1271 node->getCondition()->traverse(this);
1272
1273 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001274 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001275
1276 if (node->getTrueBlock()) {
1277 // emit the "then" statement
1278 node->getTrueBlock()->traverse(this);
1279 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001280 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001281 }
1282
1283 if (node->getFalseBlock()) {
1284 ifBuilder.makeBeginElse();
1285 // emit the "else" statement
1286 node->getFalseBlock()->traverse(this);
1287 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001288 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001289 }
1290
1291 ifBuilder.makeEndIf();
1292
1293 if (result) {
1294 // GLSL only has r-values as the result of a :?, but
1295 // if we have an l-value, that can be more efficient if it will
1296 // become the base of a complex r-value expression, because the
1297 // next layer copies r-values into memory to use the access-chain mechanism
1298 builder.clearAccessChain();
1299 builder.setAccessChainLValue(result);
1300 }
1301
1302 return false;
1303}
1304
1305bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1306{
1307 // emit and get the condition before doing anything with switch
1308 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001309 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001310
1311 // browse the children to sort out code segments
1312 int defaultSegment = -1;
1313 std::vector<TIntermNode*> codeSegments;
1314 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1315 std::vector<int> caseValues;
1316 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1317 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1318 TIntermNode* child = *c;
1319 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001320 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001321 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001322 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001323 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1324 } else
1325 codeSegments.push_back(child);
1326 }
1327
1328 // handle the case where the last code segment is missing, due to no code
1329 // statements between the last case and the end of the switch statement
1330 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1331 (int)codeSegments.size() == defaultSegment)
1332 codeSegments.push_back(nullptr);
1333
1334 // make the switch statement
1335 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001336 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001337
1338 // emit all the code in the segments
1339 breakForLoop.push(false);
1340 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1341 builder.nextSwitchSegment(segmentBlocks, s);
1342 if (codeSegments[s])
1343 codeSegments[s]->traverse(this);
1344 else
1345 builder.addSwitchBreak();
1346 }
1347 breakForLoop.pop();
1348
1349 builder.endSwitch(segmentBlocks);
1350
1351 return false;
1352}
1353
1354void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1355{
1356 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001357 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001358
1359 builder.clearAccessChain();
1360 builder.setAccessChainRValue(constant);
1361}
1362
1363bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1364{
1365 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1366 loopTerminal.push(node->getTerminal());
1367
David Netoc22f37c2015-07-15 16:21:26 -04001368 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001369
1370 if (node->getTest()) {
1371 node->getTest()->traverse(this);
1372 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001373 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001374 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001375 } else {
1376 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001377 }
1378
David Netoc22f37c2015-07-15 16:21:26 -04001379 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001380 breakForLoop.push(true);
1381 node->getBody()->traverse(this);
1382 breakForLoop.pop();
1383 }
1384
1385 if (loopTerminal.top())
1386 loopTerminal.top()->traverse(this);
1387
1388 builder.closeLoop();
1389
1390 loopTerminal.pop();
1391
1392 return false;
1393}
1394
1395bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1396{
1397 if (node->getExpression())
1398 node->getExpression()->traverse(this);
1399
1400 switch (node->getFlowOp()) {
1401 case glslang::EOpKill:
1402 builder.makeDiscard();
1403 break;
1404 case glslang::EOpBreak:
1405 if (breakForLoop.top())
1406 builder.createLoopExit();
1407 else
1408 builder.addSwitchBreak();
1409 break;
1410 case glslang::EOpContinue:
1411 if (loopTerminal.top())
1412 loopTerminal.top()->traverse(this);
1413 builder.createLoopContinue();
1414 break;
1415 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001416 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001417 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001418 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001419 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001420
1421 builder.clearAccessChain();
1422 break;
1423
1424 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001425 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001426 break;
1427 }
1428
1429 return false;
1430}
1431
1432spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1433{
1434 // First, steer off constants, which are not SPIR-V variables, but
1435 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001436 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001437 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001438 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001439 }
1440
1441 // Now, handle actual variables
1442 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1443 spv::Id spvType = convertGlslangToSpvType(node->getType());
1444
1445 const char* name = node->getName().c_str();
1446 if (glslang::IsAnonymous(name))
1447 name = "";
1448
1449 return builder.createVariable(storageClass, spvType, name);
1450}
1451
1452// Return type Id of the sampled type.
1453spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1454{
1455 switch (sampler.type) {
1456 case glslang::EbtFloat: return builder.makeFloatType(32);
1457 case glslang::EbtInt: return builder.makeIntType(32);
1458 case glslang::EbtUint: return builder.makeUintType(32);
1459 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001460 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001461 return builder.makeFloatType(32);
1462 }
1463}
1464
John Kessenich3ac051e2015-12-20 11:29:16 -07001465// Convert from a glslang type to an SPV type, by calling into a
1466// recursive version of this function. This establishes the inherited
1467// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001468spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1469{
John Kessenich3ac051e2015-12-20 11:29:16 -07001470 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier().layoutMatrix);
John Kessenich31ed4832015-09-09 17:51:38 -06001471}
1472
1473// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1474// explicitLayout can be kept the same throughout the heirarchical recursive walk.
John Kessenich3ac051e2015-12-20 11:29:16 -07001475spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich31ed4832015-09-09 17:51:38 -06001476{
John Kessenich140f3df2015-06-26 16:58:36 -06001477 spv::Id spvType = 0;
1478
1479 switch (type.getBasicType()) {
1480 case glslang::EbtVoid:
1481 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001482 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001483 break;
1484 case glslang::EbtFloat:
1485 spvType = builder.makeFloatType(32);
1486 break;
1487 case glslang::EbtDouble:
1488 spvType = builder.makeFloatType(64);
1489 break;
1490 case glslang::EbtBool:
1491 spvType = builder.makeBoolType();
1492 break;
1493 case glslang::EbtInt:
1494 spvType = builder.makeIntType(32);
1495 break;
1496 case glslang::EbtUint:
1497 spvType = builder.makeUintType(32);
1498 break;
John Kessenich426394d2015-07-23 10:22:48 -06001499 case glslang::EbtAtomicUint:
1500 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1501 spvType = builder.makeUintType(32);
1502 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001503 case glslang::EbtSampler:
1504 {
1505 const glslang::TSampler& sampler = type.getSampler();
John Kessenich55e7d112015-11-15 21:33:39 -07001506 // an image is present, make its type
1507 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1508 sampler.image ? 2 : 1, TranslateImageFormat(type));
1509 if (! sampler.image) {
1510 spvType = builder.makeSampledImageType(spvType);
1511 }
1512 }
John Kessenich140f3df2015-06-26 16:58:36 -06001513 break;
1514 case glslang::EbtStruct:
1515 case glslang::EbtBlock:
1516 {
1517 // If we've seen this struct type, return it
1518 const glslang::TTypeList* glslangStruct = type.getStruct();
1519 std::vector<spv::Id> structFields;
John Kessenich3ac051e2015-12-20 11:29:16 -07001520 spvType = structMap[explicitLayout][matrixLayout][glslangStruct];
John Kessenich140f3df2015-06-26 16:58:36 -06001521 if (spvType)
1522 break;
1523
1524 // else, we haven't seen it...
1525
1526 // Create a vector of struct types for SPIR-V to consume
1527 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1528 if (type.getBasicType() == glslang::EbtBlock)
1529 memberRemapper[glslangStruct].resize(glslangStruct->size());
1530 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1531 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1532 if (glslangType.hiddenMember()) {
1533 ++memberDelta;
1534 if (type.getBasicType() == glslang::EbtBlock)
1535 memberRemapper[glslangStruct][i] = -1;
1536 } else {
1537 if (type.getBasicType() == glslang::EbtBlock)
1538 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kessenich3ac051e2015-12-20 11:29:16 -07001539 // modify just the children's view of matrix layout, if there is one for this member
1540 glslang::TLayoutMatrix subMatrixLayout = glslangType.getQualifier().layoutMatrix;
1541 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout,
1542 subMatrixLayout != glslang::ElmNone ? subMatrixLayout : matrixLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001543 }
1544 }
1545
1546 // Make the SPIR-V type
1547 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kessenich3ac051e2015-12-20 11:29:16 -07001548 structMap[explicitLayout][matrixLayout][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001549
1550 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001551 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001552 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1553 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1554 int member = i;
1555 if (type.getBasicType() == glslang::EbtBlock)
1556 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001557
1558 // modify just the children's view of matrix layout, if there is one for this member
1559 glslang::TLayoutMatrix subMatrixLayout = glslangType.getQualifier().layoutMatrix;
1560 if (subMatrixLayout == glslang::ElmNone)
1561 subMatrixLayout = matrixLayout;
1562
John Kessenich140f3df2015-06-26 16:58:36 -06001563 // using -1 above to indicate a hidden member
1564 if (member >= 0) {
1565 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kessenich3ac051e2015-12-20 11:29:16 -07001566 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subMatrixLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001567 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
1568 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(glslangType));
1569 addMemberDecoration(spvType, member, TranslateInvariantDecoration(glslangType));
1570 if (glslangType.getQualifier().hasLocation())
1571 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1572 if (glslangType.getQualifier().hasComponent())
1573 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1574 if (glslangType.getQualifier().hasXfbOffset())
1575 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001576 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001577 // figure out what to do with offset, which is accumulating
1578 int nextOffset;
John Kessenich3ac051e2015-12-20 11:29:16 -07001579 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subMatrixLayout);
John Kessenich5e4b1242015-08-06 22:53:06 -06001580 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001581 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001582 offset = nextOffset;
1583 }
John Kessenich140f3df2015-06-26 16:58:36 -06001584
John Kessenichf85e8062015-12-19 13:57:10 -07001585 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kessenich3ac051e2015-12-20 11:29:16 -07001586 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subMatrixLayout));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001587
John Kessenich140f3df2015-06-26 16:58:36 -06001588 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001589 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1590 if (builtIn != spv::BadValue)
1591 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001592 }
1593 }
1594
1595 // Decorate the structure
John Kessenich3ac051e2015-12-20 11:29:16 -07001596 addDecoration(spvType, TranslateLayoutDecoration(type, matrixLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001597 addDecoration(spvType, TranslateBlockDecoration(type));
1598 if (type.getQualifier().hasStream())
1599 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1600 if (glslangIntermediate->getXfbMode()) {
1601 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001602 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001603 if (type.getQualifier().hasXfbBuffer())
1604 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1605 }
1606 }
1607 break;
1608 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001609 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001610 break;
1611 }
1612
1613 if (type.isMatrix())
1614 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1615 else {
1616 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1617 if (type.getVectorSize() > 1)
1618 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1619 }
1620
1621 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001622 // Do all but the outer dimension
1623 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1624 assert(type.getArraySizes()->getDimSize(dim) > 0);
1625 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1626 }
John Kessenich31ed4832015-09-09 17:51:38 -06001627
John Kessenichc9a80832015-09-12 12:17:44 -06001628 // Do the outer dimension, which might not be known for a runtime-sized array
1629 if (type.isRuntimeSizedArray()) {
1630 spvType = builder.makeRuntimeArray(spvType);
1631 } else {
1632 assert(type.getOuterArraySize() > 0);
1633 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1634 }
1635
John Kessenich55e7d112015-11-15 21:33:39 -07001636 // TODO: explicit layout still needs to be done hierarchically for arrays of arrays, which
John Kessenichc9a80832015-09-12 12:17:44 -06001637 // may still require additional "link time" support from the front-end
1638 // for arrays of arrays
John Kessenich55e7d112015-11-15 21:33:39 -07001639
1640 // We need to decorate array strides for types needing explicit layout,
1641 // except for the very top if it is an array of blocks; that array is
1642 // not laid out in memory in a way needing a stride.
1643 if (explicitLayout && type.getBasicType() != glslang::EbtBlock)
John Kessenich3ac051e2015-12-20 11:29:16 -07001644 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type, explicitLayout, matrixLayout));
John Kessenich140f3df2015-06-26 16:58:36 -06001645 }
1646
1647 return spvType;
1648}
1649
John Kessenichf85e8062015-12-19 13:57:10 -07001650// Decide whether or not this type should be
1651// decorated with offsets and strides, and if so
1652// whether std140 or std430 rules should be applied.
1653glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001654{
John Kessenichf85e8062015-12-19 13:57:10 -07001655 // has to be a block
1656 if (type.getBasicType() != glslang::EbtBlock)
1657 return glslang::ElpNone;
1658
1659 // has to be a uniform or buffer block
1660 if (type.getQualifier().storage != glslang::EvqUniform &&
1661 type.getQualifier().storage != glslang::EvqBuffer)
1662 return glslang::ElpNone;
1663
1664 // return the layout to use
1665 switch (type.getQualifier().layoutPacking) {
1666 case glslang::ElpStd140:
1667 case glslang::ElpStd430:
1668 return type.getQualifier().layoutPacking;
1669 default:
1670 return glslang::ElpNone;
1671 }
John Kessenich31ed4832015-09-09 17:51:38 -06001672}
1673
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001674// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001675int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001676{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001677 int size;
John Kessenich3ac051e2015-12-20 11:29:16 -07001678 int stride = glslangIntermediate->getBaseAlignment(arrayType, size, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001679 if (arrayType.isMatrix()) {
1680 // GLSL strides are set to alignments of the matrix flattened to individual rows/cols,
1681 // but SPV needs an array stride for the whole matrix, not the rows/cols
John Kessenich3ac051e2015-12-20 11:29:16 -07001682 if (matrixLayout == glslang::ElmRowMajor)
John Kesseniche721f492015-12-06 19:17:49 -07001683 stride *= arrayType.getMatrixRows();
1684 else
1685 stride *= arrayType.getMatrixCols();
1686 }
1687
1688 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001689}
1690
1691// Given a matrix type, returns the integer stride required for that matrix
1692// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001693int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001694{
1695 int size;
John Kessenich3ac051e2015-12-20 11:29:16 -07001696 return glslangIntermediate->getBaseAlignment(matrixType, size, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001697}
1698
John Kessenich5e4b1242015-08-06 22:53:06 -06001699// Given a member type of a struct, realign the current offset for it, and compute
1700// the next (not yet aligned) offset for the next member, which will get aligned
1701// on the next call.
1702// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1703// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1704// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001705void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001706 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001707{
1708 // this will get a positive value when deemed necessary
1709 nextOffset = -1;
1710
John Kessenich5e4b1242015-08-06 22:53:06 -06001711 // override anything in currentOffset with user-set offset
1712 if (memberType.getQualifier().hasOffset())
1713 currentOffset = memberType.getQualifier().layoutOffset;
1714
1715 // It could be that current linker usage in glslang updated all the layoutOffset,
1716 // in which case the following code does not matter. But, that's not quite right
1717 // once cross-compilation unit GLSL validation is done, as the original user
1718 // settings are needed in layoutOffset, and then the following will come into play.
1719
John Kessenichf85e8062015-12-19 13:57:10 -07001720 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001721 if (! memberType.getQualifier().hasOffset())
1722 currentOffset = -1;
1723
1724 return;
1725 }
1726
John Kessenichf85e8062015-12-19 13:57:10 -07001727 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001728 if (currentOffset < 0)
1729 currentOffset = 0;
1730
1731 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1732 // but possibly not yet correctly aligned.
1733
1734 int memberSize;
John Kessenich3ac051e2015-12-20 11:29:16 -07001735 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001736 glslang::RoundToPow2(currentOffset, memberAlignment);
1737 nextOffset = currentOffset + memberSize;
1738}
1739
John Kessenich140f3df2015-06-26 16:58:36 -06001740bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1741{
1742 return node->getName() == "main(";
1743}
1744
1745// Make all the functions, skeletally, without actually visiting their bodies.
1746void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1747{
1748 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1749 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1750 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1751 continue;
1752
1753 // We're on a user function. Set up the basic interface for the function now,
1754 // so that it's available to call.
1755 // Translating the body will happen later.
1756 //
1757 // Typically (except for a "const in" parameter), an address will be passed to the
1758 // function. What it is an address of varies:
1759 //
1760 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1761 // so that write needs to be to a copy, hence the address of a copy works.
1762 //
1763 // - "const in" parameters can just be the r-value, as no writes need occur.
1764 //
1765 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1766 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1767
1768 std::vector<spv::Id> paramTypes;
1769 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1770
1771 for (int p = 0; p < (int)parameters.size(); ++p) {
1772 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1773 spv::Id typeId = convertGlslangToSpvType(paramType);
1774 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1775 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1776 else
1777 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1778 paramTypes.push_back(typeId);
1779 }
1780
1781 spv::Block* functionBlock;
1782 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1783 paramTypes, &functionBlock);
1784
1785 // Track function to emit/call later
1786 functionMap[glslFunction->getName().c_str()] = function;
1787
1788 // Set the parameter id's
1789 for (int p = 0; p < (int)parameters.size(); ++p) {
1790 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1791 // give a name too
1792 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1793 }
1794 }
1795}
1796
1797// Process all the initializers, while skipping the functions and link objects
1798void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1799{
1800 builder.setBuildPoint(shaderEntry->getLastBlock());
1801 for (int i = 0; i < (int)initializers.size(); ++i) {
1802 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1803 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1804
1805 // We're on a top-level node that's not a function. Treat as an initializer, whose
1806 // code goes into the beginning of main.
1807 initializer->traverse(this);
1808 }
1809 }
1810}
1811
1812// Process all the functions, while skipping initializers.
1813void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1814{
1815 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1816 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1817 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1818 node->traverse(this);
1819 }
1820}
1821
1822void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1823{
1824 // SPIR-V functions should already be in the functionMap from the prepass
1825 // that called makeFunctions().
1826 spv::Function* function = functionMap[node->getName().c_str()];
1827 spv::Block* functionBlock = function->getEntryBlock();
1828 builder.setBuildPoint(functionBlock);
1829}
1830
Rex Xu04db3f52015-09-16 11:44:02 +08001831void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001832{
Rex Xufc618912015-09-09 16:42:49 +08001833 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001834 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1835 builder.clearAccessChain();
1836 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001837
1838 // Special case l-value operands
1839 bool lvalue = false;
1840 switch (node.getOp()) {
1841 case glslang::EOpImageAtomicAdd:
1842 case glslang::EOpImageAtomicMin:
1843 case glslang::EOpImageAtomicMax:
1844 case glslang::EOpImageAtomicAnd:
1845 case glslang::EOpImageAtomicOr:
1846 case glslang::EOpImageAtomicXor:
1847 case glslang::EOpImageAtomicExchange:
1848 case glslang::EOpImageAtomicCompSwap:
1849 if (i == 0)
1850 lvalue = true;
1851 break;
1852 default:
1853 break;
1854 }
1855
Rex Xu6b86d492015-09-16 17:48:22 +08001856 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001857 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001858 else
Rex Xu30f92582015-09-14 10:38:56 +08001859 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001860 }
1861}
1862
John Kessenichfc51d282015-08-19 13:34:18 -06001863void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001864{
John Kessenichfc51d282015-08-19 13:34:18 -06001865 builder.clearAccessChain();
1866 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001867 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001868}
John Kessenich140f3df2015-06-26 16:58:36 -06001869
John Kessenichfc51d282015-08-19 13:34:18 -06001870spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1871{
Rex Xufc618912015-09-09 16:42:49 +08001872 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001873 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001874 }
1875
John Kessenichfc51d282015-08-19 13:34:18 -06001876 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001877 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1878 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1879 std::vector<spv::Id> arguments;
1880 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001881 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001882 else
1883 translateArguments(*node->getAsUnaryNode(), arguments);
1884 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1885
1886 spv::Builder::TextureParameters params = { };
1887 params.sampler = arguments[0];
1888
Rex Xu04db3f52015-09-16 11:44:02 +08001889 glslang::TCrackedTextureOp cracked;
1890 node->crackTexture(sampler, cracked);
1891
John Kessenichfc51d282015-08-19 13:34:18 -06001892 // Check for queries
1893 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07001894 // a sampled image needs to have the image extracted first
1895 if (builder.isSampledImage(params.sampler))
1896 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06001897 switch (node->getOp()) {
1898 case glslang::EOpImageQuerySize:
1899 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001900 if (arguments.size() > 1) {
1901 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001902 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001903 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001904 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001905 case glslang::EOpImageQuerySamples:
1906 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001907 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001908 case glslang::EOpTextureQueryLod:
1909 params.coords = arguments[1];
1910 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1911 case glslang::EOpTextureQueryLevels:
1912 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1913 default:
1914 assert(0);
1915 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001916 }
John Kessenich140f3df2015-06-26 16:58:36 -06001917 }
1918
Rex Xufc618912015-09-09 16:42:49 +08001919 // Check for image functions other than queries
1920 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001921 std::vector<spv::Id> operands;
1922 auto opIt = arguments.begin();
1923 operands.push_back(*(opIt++));
1924 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001925 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07001926 if (sampler.ms) {
1927 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08001928 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07001929 }
John Kessenich56bab042015-09-16 10:54:31 -06001930 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1931 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08001932 if (sampler.ms) {
1933 operands.push_back(*(opIt + 1));
1934 operands.push_back(spv::ImageOperandsSampleMask);
1935 operands.push_back(*opIt);
1936 } else
1937 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06001938 builder.createNoResultOp(spv::OpImageWrite, operands);
1939 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001940 } else {
1941 // Process image atomic operations
1942
1943 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1944 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001945 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001946
Rex Xufc618912015-09-09 16:42:49 +08001947 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001948 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001949
1950 std::vector<spv::Id> operands;
1951 operands.push_back(pointer);
1952 for (; opIt != arguments.end(); ++opIt)
1953 operands.push_back(*opIt);
1954
Rex Xu04db3f52015-09-16 11:44:02 +08001955 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001956 }
1957 }
1958
1959 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001960
Rex Xu71519fe2015-11-11 15:35:47 +08001961 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1962
John Kessenichfc51d282015-08-19 13:34:18 -06001963 // check for bias argument
1964 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08001965 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06001966 int nonBiasArgCount = 2;
1967 if (cracked.offset)
1968 ++nonBiasArgCount;
1969 if (cracked.grad)
1970 nonBiasArgCount += 2;
1971
1972 if ((int)arguments.size() > nonBiasArgCount)
1973 bias = true;
1974 }
1975
John Kessenichfc51d282015-08-19 13:34:18 -06001976 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07001977
John Kessenichfc51d282015-08-19 13:34:18 -06001978 params.coords = arguments[1];
1979 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001980
1981 // sort out where Dref is coming from
1982 if (sampler.shadow && sampler.dim == glslang::EsdCube && sampler.arrayed)
John Kessenichfc51d282015-08-19 13:34:18 -06001983 params.Dref = arguments[2];
John Kessenich55e7d112015-11-15 21:33:39 -07001984 else if (sampler.shadow && cracked.gather) {
1985 params.Dref = arguments[2];
1986 ++extraArgs;
1987 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06001988 std::vector<spv::Id> indexes;
1989 int comp;
1990 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07001991 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06001992 else
1993 comp = builder.getNumComponents(params.coords) - 1;
1994 indexes.push_back(comp);
1995 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
1996 }
1997 if (cracked.lod) {
1998 params.lod = arguments[2];
1999 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002000 } else if (sampler.ms) {
2001 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002002 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002003 }
2004 if (cracked.grad) {
2005 params.gradX = arguments[2 + extraArgs];
2006 params.gradY = arguments[3 + extraArgs];
2007 extraArgs += 2;
2008 }
John Kessenich55e7d112015-11-15 21:33:39 -07002009 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002010 params.offset = arguments[2 + extraArgs];
2011 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002012 } else if (cracked.offsets) {
2013 params.offsets = arguments[2 + extraArgs];
2014 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002015 }
2016 if (bias) {
2017 params.bias = arguments[2 + extraArgs];
2018 ++extraArgs;
2019 }
John Kessenich55e7d112015-11-15 21:33:39 -07002020 if (cracked.gather && ! sampler.shadow) {
2021 // default component is 0, if missing, otherwise an argument
2022 if (2 + extraArgs < (int)arguments.size()) {
2023 params.comp = arguments[2 + extraArgs];
2024 ++extraArgs;
2025 } else {
2026 params.comp = builder.makeIntConstant(0);
2027 }
2028 }
John Kessenichfc51d282015-08-19 13:34:18 -06002029
John Kessenich55e7d112015-11-15 21:33:39 -07002030 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002031}
2032
2033spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2034{
2035 // Grab the function's pointer from the previously created function
2036 spv::Function* function = functionMap[node->getName().c_str()];
2037 if (! function)
2038 return 0;
2039
2040 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2041 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2042
2043 // See comments in makeFunctions() for details about the semantics for parameter passing.
2044 //
2045 // These imply we need a four step process:
2046 // 1. Evaluate the arguments
2047 // 2. Allocate and make copies of in, out, and inout arguments
2048 // 3. Make the call
2049 // 4. Copy back the results
2050
2051 // 1. Evaluate the arguments
2052 std::vector<spv::Builder::AccessChain> lValues;
2053 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002054 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002055 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2056 // build l-value
2057 builder.clearAccessChain();
2058 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002059 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002060 // keep outputs as l-values, evaluate input-only as r-values
2061 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2062 // save l-value
2063 lValues.push_back(builder.getAccessChain());
2064 } else {
2065 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002066 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002067 }
2068 }
2069
2070 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2071 // copy the original into that space.
2072 //
2073 // Also, build up the list of actual arguments to pass in for the call
2074 int lValueCount = 0;
2075 int rValueCount = 0;
2076 std::vector<spv::Id> spvArgs;
2077 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2078 spv::Id arg;
2079 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2080 // need space to hold the copy
2081 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2082 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2083 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2084 // need to copy the input into output space
2085 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002086 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002087 builder.createStore(copy, arg);
2088 }
2089 ++lValueCount;
2090 } else {
2091 arg = rValues[rValueCount];
2092 ++rValueCount;
2093 }
2094 spvArgs.push_back(arg);
2095 }
2096
2097 // 3. Make the call.
2098 spv::Id result = builder.createFunctionCall(function, spvArgs);
2099
2100 // 4. Copy back out an "out" arguments.
2101 lValueCount = 0;
2102 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2103 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2104 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2105 spv::Id copy = builder.createLoad(spvArgs[a]);
2106 builder.setAccessChain(lValues[lValueCount]);
2107 builder.accessChainStore(copy);
2108 }
2109 ++lValueCount;
2110 }
2111 }
2112
2113 return result;
2114}
2115
2116// Translate AST operation to SPV operation, already having SPV-based operands/types.
2117spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2118 spv::Id typeId, spv::Id left, spv::Id right,
2119 glslang::TBasicType typeProxy, bool reduceComparison)
2120{
2121 bool isUnsigned = typeProxy == glslang::EbtUint;
2122 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2123
2124 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002125 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002126 bool comparison = false;
2127
2128 switch (op) {
2129 case glslang::EOpAdd:
2130 case glslang::EOpAddAssign:
2131 if (isFloat)
2132 binOp = spv::OpFAdd;
2133 else
2134 binOp = spv::OpIAdd;
2135 break;
2136 case glslang::EOpSub:
2137 case glslang::EOpSubAssign:
2138 if (isFloat)
2139 binOp = spv::OpFSub;
2140 else
2141 binOp = spv::OpISub;
2142 break;
2143 case glslang::EOpMul:
2144 case glslang::EOpMulAssign:
2145 if (isFloat)
2146 binOp = spv::OpFMul;
2147 else
2148 binOp = spv::OpIMul;
2149 break;
2150 case glslang::EOpVectorTimesScalar:
2151 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002152 if (isFloat) {
2153 if (builder.isVector(right))
2154 std::swap(left, right);
2155 assert(builder.isScalar(right));
2156 needMatchingVectors = false;
2157 binOp = spv::OpVectorTimesScalar;
2158 } else
2159 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002160 break;
2161 case glslang::EOpVectorTimesMatrix:
2162 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002163 binOp = spv::OpVectorTimesMatrix;
2164 break;
2165 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002166 binOp = spv::OpMatrixTimesVector;
2167 break;
2168 case glslang::EOpMatrixTimesScalar:
2169 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002170 binOp = spv::OpMatrixTimesScalar;
2171 break;
2172 case glslang::EOpMatrixTimesMatrix:
2173 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002174 binOp = spv::OpMatrixTimesMatrix;
2175 break;
2176 case glslang::EOpOuterProduct:
2177 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002178 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002179 break;
2180
2181 case glslang::EOpDiv:
2182 case glslang::EOpDivAssign:
2183 if (isFloat)
2184 binOp = spv::OpFDiv;
2185 else if (isUnsigned)
2186 binOp = spv::OpUDiv;
2187 else
2188 binOp = spv::OpSDiv;
2189 break;
2190 case glslang::EOpMod:
2191 case glslang::EOpModAssign:
2192 if (isFloat)
2193 binOp = spv::OpFMod;
2194 else if (isUnsigned)
2195 binOp = spv::OpUMod;
2196 else
2197 binOp = spv::OpSMod;
2198 break;
2199 case glslang::EOpRightShift:
2200 case glslang::EOpRightShiftAssign:
2201 if (isUnsigned)
2202 binOp = spv::OpShiftRightLogical;
2203 else
2204 binOp = spv::OpShiftRightArithmetic;
2205 break;
2206 case glslang::EOpLeftShift:
2207 case glslang::EOpLeftShiftAssign:
2208 binOp = spv::OpShiftLeftLogical;
2209 break;
2210 case glslang::EOpAnd:
2211 case glslang::EOpAndAssign:
2212 binOp = spv::OpBitwiseAnd;
2213 break;
2214 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002215 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002216 binOp = spv::OpLogicalAnd;
2217 break;
2218 case glslang::EOpInclusiveOr:
2219 case glslang::EOpInclusiveOrAssign:
2220 binOp = spv::OpBitwiseOr;
2221 break;
2222 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002223 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002224 binOp = spv::OpLogicalOr;
2225 break;
2226 case glslang::EOpExclusiveOr:
2227 case glslang::EOpExclusiveOrAssign:
2228 binOp = spv::OpBitwiseXor;
2229 break;
2230 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002231 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002232 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002233 break;
2234
2235 case glslang::EOpLessThan:
2236 case glslang::EOpGreaterThan:
2237 case glslang::EOpLessThanEqual:
2238 case glslang::EOpGreaterThanEqual:
2239 case glslang::EOpEqual:
2240 case glslang::EOpNotEqual:
2241 case glslang::EOpVectorEqual:
2242 case glslang::EOpVectorNotEqual:
2243 comparison = true;
2244 break;
2245 default:
2246 break;
2247 }
2248
John Kessenich7c1aa102015-10-15 13:29:11 -06002249 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002250 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002251 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002252 if (builder.isMatrix(left) || builder.isMatrix(right))
2253 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002254
2255 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002256 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002257 builder.promoteScalar(precision, left, right);
2258
2259 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2260 builder.setPrecision(id, precision);
2261
2262 return id;
2263 }
2264
2265 if (! comparison)
2266 return 0;
2267
John Kessenich7c1aa102015-10-15 13:29:11 -06002268 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002269
2270 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2271 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2272
John Kessenich22118352015-12-21 20:54:09 -07002273 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002274 }
2275
2276 switch (op) {
2277 case glslang::EOpLessThan:
2278 if (isFloat)
2279 binOp = spv::OpFOrdLessThan;
2280 else if (isUnsigned)
2281 binOp = spv::OpULessThan;
2282 else
2283 binOp = spv::OpSLessThan;
2284 break;
2285 case glslang::EOpGreaterThan:
2286 if (isFloat)
2287 binOp = spv::OpFOrdGreaterThan;
2288 else if (isUnsigned)
2289 binOp = spv::OpUGreaterThan;
2290 else
2291 binOp = spv::OpSGreaterThan;
2292 break;
2293 case glslang::EOpLessThanEqual:
2294 if (isFloat)
2295 binOp = spv::OpFOrdLessThanEqual;
2296 else if (isUnsigned)
2297 binOp = spv::OpULessThanEqual;
2298 else
2299 binOp = spv::OpSLessThanEqual;
2300 break;
2301 case glslang::EOpGreaterThanEqual:
2302 if (isFloat)
2303 binOp = spv::OpFOrdGreaterThanEqual;
2304 else if (isUnsigned)
2305 binOp = spv::OpUGreaterThanEqual;
2306 else
2307 binOp = spv::OpSGreaterThanEqual;
2308 break;
2309 case glslang::EOpEqual:
2310 case glslang::EOpVectorEqual:
2311 if (isFloat)
2312 binOp = spv::OpFOrdEqual;
2313 else
2314 binOp = spv::OpIEqual;
2315 break;
2316 case glslang::EOpNotEqual:
2317 case glslang::EOpVectorNotEqual:
2318 if (isFloat)
2319 binOp = spv::OpFOrdNotEqual;
2320 else
2321 binOp = spv::OpINotEqual;
2322 break;
2323 default:
2324 break;
2325 }
2326
2327 if (binOp != spv::OpNop) {
2328 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2329 builder.setPrecision(id, precision);
2330
2331 return id;
2332 }
2333
2334 return 0;
2335}
2336
John Kessenich04bb8a02015-12-12 12:28:14 -07002337//
2338// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2339// These can be any of:
2340//
2341// matrix * scalar
2342// scalar * matrix
2343// matrix * matrix linear algebraic
2344// matrix * vector
2345// vector * matrix
2346// matrix * matrix componentwise
2347// matrix op matrix op in {+, -, /}
2348// matrix op scalar op in {+, -, /}
2349// scalar op matrix op in {+, -, /}
2350//
2351spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2352{
2353 bool firstClass = true;
2354
2355 // First, handle first-class matrix operations (* and matrix/scalar)
2356 switch (op) {
2357 case spv::OpFDiv:
2358 if (builder.isMatrix(left) && builder.isScalar(right)) {
2359 // turn matrix / scalar into a multiply...
2360 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2361 op = spv::OpMatrixTimesScalar;
2362 } else
2363 firstClass = false;
2364 break;
2365 case spv::OpMatrixTimesScalar:
2366 if (builder.isMatrix(right))
2367 std::swap(left, right);
2368 assert(builder.isScalar(right));
2369 break;
2370 case spv::OpVectorTimesMatrix:
2371 assert(builder.isVector(left));
2372 assert(builder.isMatrix(right));
2373 break;
2374 case spv::OpMatrixTimesVector:
2375 assert(builder.isMatrix(left));
2376 assert(builder.isVector(right));
2377 break;
2378 case spv::OpMatrixTimesMatrix:
2379 assert(builder.isMatrix(left));
2380 assert(builder.isMatrix(right));
2381 break;
2382 default:
2383 firstClass = false;
2384 break;
2385 }
2386
2387 if (firstClass) {
2388 spv::Id id = builder.createBinOp(op, typeId, left, right);
2389 builder.setPrecision(id, precision);
2390
2391 return id;
2392 }
2393
2394 // Handle component-wise +, -, *, and / for all combinations of type.
2395 // The result type of all of them is the same type as the (a) matrix operand.
2396 // The algorithm is to:
2397 // - break the matrix(es) into vectors
2398 // - smear any scalar to a vector
2399 // - do vector operations
2400 // - make a matrix out the vector results
2401 switch (op) {
2402 case spv::OpFAdd:
2403 case spv::OpFSub:
2404 case spv::OpFDiv:
2405 case spv::OpFMul:
2406 {
2407 // one time set up...
2408 bool leftMat = builder.isMatrix(left);
2409 bool rightMat = builder.isMatrix(right);
2410 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2411 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2412 spv::Id scalarType = builder.getScalarTypeId(typeId);
2413 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2414 std::vector<spv::Id> results;
2415 spv::Id smearVec = spv::NoResult;
2416 if (builder.isScalar(left))
2417 smearVec = builder.smearScalar(precision, left, vecType);
2418 else if (builder.isScalar(right))
2419 smearVec = builder.smearScalar(precision, right, vecType);
2420
2421 // do each vector op
2422 for (unsigned int c = 0; c < numCols; ++c) {
2423 std::vector<unsigned int> indexes;
2424 indexes.push_back(c);
2425 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2426 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2427 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2428 builder.setPrecision(results.back(), precision);
2429 }
2430
2431 // put the pieces together
2432 spv::Id id = builder.createCompositeConstruct(typeId, results);
2433 builder.setPrecision(id, precision);
2434 return id;
2435 }
2436 default:
2437 assert(0);
2438 return spv::NoResult;
2439 }
2440}
2441
Rex Xu04db3f52015-09-16 11:44:02 +08002442spv::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 -06002443{
2444 spv::Op unaryOp = spv::OpNop;
2445 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002446 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002447 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002448
2449 switch (op) {
2450 case glslang::EOpNegative:
2451 if (isFloat)
2452 unaryOp = spv::OpFNegate;
2453 else
2454 unaryOp = spv::OpSNegate;
2455 break;
2456
2457 case glslang::EOpLogicalNot:
2458 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002459 unaryOp = spv::OpLogicalNot;
2460 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002461 case glslang::EOpBitwiseNot:
2462 unaryOp = spv::OpNot;
2463 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002464
John Kessenich140f3df2015-06-26 16:58:36 -06002465 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002466 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002467 break;
2468 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002469 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002470 break;
2471 case glslang::EOpTranspose:
2472 unaryOp = spv::OpTranspose;
2473 break;
2474
2475 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002476 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002477 break;
2478 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002479 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002480 break;
2481 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002482 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002483 break;
2484 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002485 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002486 break;
2487 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002488 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002489 break;
2490 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002491 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002492 break;
2493 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002494 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002495 break;
2496 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002497 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002498 break;
2499
2500 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002501 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002502 break;
2503 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002504 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002505 break;
2506 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002507 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002508 break;
2509 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002510 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002511 break;
2512 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002513 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002514 break;
2515 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002516 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002517 break;
2518
2519 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002520 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002521 break;
2522 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002523 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002524 break;
2525
2526 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002527 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002528 break;
2529 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002530 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002531 break;
2532 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002533 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002534 break;
2535 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002536 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002537 break;
2538 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002539 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002540 break;
2541 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002542 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002543 break;
2544
2545 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002546 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002547 break;
2548 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002549 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002550 break;
2551 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002552 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002553 break;
2554 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002555 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002556 break;
2557 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002558 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002559 break;
2560 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002561 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002562 break;
2563
2564 case glslang::EOpIsNan:
2565 unaryOp = spv::OpIsNan;
2566 break;
2567 case glslang::EOpIsInf:
2568 unaryOp = spv::OpIsInf;
2569 break;
2570
Rex Xucbc426e2015-12-15 16:03:10 +08002571 case glslang::EOpFloatBitsToInt:
2572 case glslang::EOpFloatBitsToUint:
2573 case glslang::EOpIntBitsToFloat:
2574 case glslang::EOpUintBitsToFloat:
2575 unaryOp = spv::OpBitcast;
2576 break;
2577
John Kessenich140f3df2015-06-26 16:58:36 -06002578 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002579 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002580 break;
2581 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002582 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002583 break;
2584 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002585 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002586 break;
2587 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002588 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002589 break;
2590 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002591 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002592 break;
2593 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002594 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002595 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002596 case glslang::EOpPackSnorm4x8:
2597 libCall = spv::GLSLstd450PackSnorm4x8;
2598 break;
2599 case glslang::EOpUnpackSnorm4x8:
2600 libCall = spv::GLSLstd450UnpackSnorm4x8;
2601 break;
2602 case glslang::EOpPackUnorm4x8:
2603 libCall = spv::GLSLstd450PackUnorm4x8;
2604 break;
2605 case glslang::EOpUnpackUnorm4x8:
2606 libCall = spv::GLSLstd450UnpackUnorm4x8;
2607 break;
2608 case glslang::EOpPackDouble2x32:
2609 libCall = spv::GLSLstd450PackDouble2x32;
2610 break;
2611 case glslang::EOpUnpackDouble2x32:
2612 libCall = spv::GLSLstd450UnpackDouble2x32;
2613 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002614
2615 case glslang::EOpDPdx:
2616 unaryOp = spv::OpDPdx;
2617 break;
2618 case glslang::EOpDPdy:
2619 unaryOp = spv::OpDPdy;
2620 break;
2621 case glslang::EOpFwidth:
2622 unaryOp = spv::OpFwidth;
2623 break;
2624 case glslang::EOpDPdxFine:
2625 unaryOp = spv::OpDPdxFine;
2626 break;
2627 case glslang::EOpDPdyFine:
2628 unaryOp = spv::OpDPdyFine;
2629 break;
2630 case glslang::EOpFwidthFine:
2631 unaryOp = spv::OpFwidthFine;
2632 break;
2633 case glslang::EOpDPdxCoarse:
2634 unaryOp = spv::OpDPdxCoarse;
2635 break;
2636 case glslang::EOpDPdyCoarse:
2637 unaryOp = spv::OpDPdyCoarse;
2638 break;
2639 case glslang::EOpFwidthCoarse:
2640 unaryOp = spv::OpFwidthCoarse;
2641 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002642 case glslang::EOpInterpolateAtCentroid:
2643 libCall = spv::GLSLstd450InterpolateAtCentroid;
2644 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002645 case glslang::EOpAny:
2646 unaryOp = spv::OpAny;
2647 break;
2648 case glslang::EOpAll:
2649 unaryOp = spv::OpAll;
2650 break;
2651
2652 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002653 if (isFloat)
2654 libCall = spv::GLSLstd450FAbs;
2655 else
2656 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002657 break;
2658 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002659 if (isFloat)
2660 libCall = spv::GLSLstd450FSign;
2661 else
2662 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002663 break;
2664
John Kessenichfc51d282015-08-19 13:34:18 -06002665 case glslang::EOpAtomicCounterIncrement:
2666 case glslang::EOpAtomicCounterDecrement:
2667 case glslang::EOpAtomicCounter:
2668 {
2669 // Handle all of the atomics in one place, in createAtomicOperation()
2670 std::vector<spv::Id> operands;
2671 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002672 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002673 }
2674
2675 case glslang::EOpImageLoad:
2676 unaryOp = spv::OpImageRead;
2677 break;
2678
2679 case glslang::EOpBitFieldReverse:
2680 unaryOp = spv::OpBitReverse;
2681 break;
2682 case glslang::EOpBitCount:
2683 unaryOp = spv::OpBitCount;
2684 break;
2685 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002686 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002687 break;
2688 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002689 if (isUnsigned)
2690 libCall = spv::GLSLstd450FindUMsb;
2691 else
2692 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002693 break;
2694
John Kessenich140f3df2015-06-26 16:58:36 -06002695 default:
2696 return 0;
2697 }
2698
2699 spv::Id id;
2700 if (libCall >= 0) {
2701 std::vector<spv::Id> args;
2702 args.push_back(operand);
2703 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2704 } else
2705 id = builder.createUnaryOp(unaryOp, typeId, operand);
2706
2707 builder.setPrecision(id, precision);
2708
2709 return id;
2710}
2711
2712spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2713{
2714 spv::Op convOp = spv::OpNop;
2715 spv::Id zero = 0;
2716 spv::Id one = 0;
2717
2718 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2719
2720 switch (op) {
2721 case glslang::EOpConvIntToBool:
2722 case glslang::EOpConvUintToBool:
2723 zero = builder.makeUintConstant(0);
2724 zero = makeSmearedConstant(zero, vectorSize);
2725 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2726
2727 case glslang::EOpConvFloatToBool:
2728 zero = builder.makeFloatConstant(0.0F);
2729 zero = makeSmearedConstant(zero, vectorSize);
2730 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2731
2732 case glslang::EOpConvDoubleToBool:
2733 zero = builder.makeDoubleConstant(0.0);
2734 zero = makeSmearedConstant(zero, vectorSize);
2735 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2736
2737 case glslang::EOpConvBoolToFloat:
2738 convOp = spv::OpSelect;
2739 zero = builder.makeFloatConstant(0.0);
2740 one = builder.makeFloatConstant(1.0);
2741 break;
2742 case glslang::EOpConvBoolToDouble:
2743 convOp = spv::OpSelect;
2744 zero = builder.makeDoubleConstant(0.0);
2745 one = builder.makeDoubleConstant(1.0);
2746 break;
2747 case glslang::EOpConvBoolToInt:
2748 zero = builder.makeIntConstant(0);
2749 one = builder.makeIntConstant(1);
2750 convOp = spv::OpSelect;
2751 break;
2752 case glslang::EOpConvBoolToUint:
2753 zero = builder.makeUintConstant(0);
2754 one = builder.makeUintConstant(1);
2755 convOp = spv::OpSelect;
2756 break;
2757
2758 case glslang::EOpConvIntToFloat:
2759 case glslang::EOpConvIntToDouble:
2760 convOp = spv::OpConvertSToF;
2761 break;
2762
2763 case glslang::EOpConvUintToFloat:
2764 case glslang::EOpConvUintToDouble:
2765 convOp = spv::OpConvertUToF;
2766 break;
2767
2768 case glslang::EOpConvDoubleToFloat:
2769 case glslang::EOpConvFloatToDouble:
2770 convOp = spv::OpFConvert;
2771 break;
2772
2773 case glslang::EOpConvFloatToInt:
2774 case glslang::EOpConvDoubleToInt:
2775 convOp = spv::OpConvertFToS;
2776 break;
2777
2778 case glslang::EOpConvUintToInt:
2779 case glslang::EOpConvIntToUint:
2780 convOp = spv::OpBitcast;
2781 break;
2782
2783 case glslang::EOpConvFloatToUint:
2784 case glslang::EOpConvDoubleToUint:
2785 convOp = spv::OpConvertFToU;
2786 break;
2787 default:
2788 break;
2789 }
2790
2791 spv::Id result = 0;
2792 if (convOp == spv::OpNop)
2793 return result;
2794
2795 if (convOp == spv::OpSelect) {
2796 zero = makeSmearedConstant(zero, vectorSize);
2797 one = makeSmearedConstant(one, vectorSize);
2798 result = builder.createTriOp(convOp, destType, operand, one, zero);
2799 } else
2800 result = builder.createUnaryOp(convOp, destType, operand);
2801
2802 builder.setPrecision(result, precision);
2803
2804 return result;
2805}
2806
2807spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2808{
2809 if (vectorSize == 0)
2810 return constant;
2811
2812 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2813 std::vector<spv::Id> components;
2814 for (int c = 0; c < vectorSize; ++c)
2815 components.push_back(constant);
2816 return builder.makeCompositeConstant(vectorTypeId, components);
2817}
2818
John Kessenich426394d2015-07-23 10:22:48 -06002819// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002820spv::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 -06002821{
2822 spv::Op opCode = spv::OpNop;
2823
2824 switch (op) {
2825 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002826 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002827 opCode = spv::OpAtomicIAdd;
2828 break;
2829 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002830 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002831 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002832 break;
2833 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002834 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002835 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002836 break;
2837 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002838 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002839 opCode = spv::OpAtomicAnd;
2840 break;
2841 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002842 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002843 opCode = spv::OpAtomicOr;
2844 break;
2845 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002846 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002847 opCode = spv::OpAtomicXor;
2848 break;
2849 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002850 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002851 opCode = spv::OpAtomicExchange;
2852 break;
2853 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002854 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002855 opCode = spv::OpAtomicCompareExchange;
2856 break;
2857 case glslang::EOpAtomicCounterIncrement:
2858 opCode = spv::OpAtomicIIncrement;
2859 break;
2860 case glslang::EOpAtomicCounterDecrement:
2861 opCode = spv::OpAtomicIDecrement;
2862 break;
2863 case glslang::EOpAtomicCounter:
2864 opCode = spv::OpAtomicLoad;
2865 break;
2866 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002867 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06002868 break;
2869 }
2870
2871 // Sort out the operands
2872 // - mapping from glslang -> SPV
2873 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002874 // - compare-exchange swaps the value and comparator
2875 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002876 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2877 auto opIt = operands.begin(); // walk the glslang operands
2878 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002879 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2880 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2881 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002882 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2883 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002884 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002885 spvAtomicOperands.push_back(*(opIt + 1));
2886 spvAtomicOperands.push_back(*opIt);
2887 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002888 }
John Kessenich426394d2015-07-23 10:22:48 -06002889
John Kessenich3e60a6f2015-09-14 22:45:16 -06002890 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002891 for (; opIt != operands.end(); ++opIt)
2892 spvAtomicOperands.push_back(*opIt);
2893
2894 return builder.createOp(opCode, typeId, spvAtomicOperands);
2895}
2896
John Kessenich5e4b1242015-08-06 22:53:06 -06002897spv::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 -06002898{
John Kessenich5e4b1242015-08-06 22:53:06 -06002899 bool isUnsigned = typeProxy == glslang::EbtUint;
2900 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2901
John Kessenich140f3df2015-06-26 16:58:36 -06002902 spv::Op opCode = spv::OpNop;
2903 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002904 int consumedOperands = operands.size();
2905 spv::Id typeId0 = 0;
2906 if (consumedOperands > 0)
2907 typeId0 = builder.getTypeId(operands[0]);
2908 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002909
2910 switch (op) {
2911 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002912 if (isFloat)
2913 libCall = spv::GLSLstd450FMin;
2914 else if (isUnsigned)
2915 libCall = spv::GLSLstd450UMin;
2916 else
2917 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002918 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002919 break;
2920 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002921 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002922 break;
2923 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002924 if (isFloat)
2925 libCall = spv::GLSLstd450FMax;
2926 else if (isUnsigned)
2927 libCall = spv::GLSLstd450UMax;
2928 else
2929 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002930 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002931 break;
2932 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002933 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002934 break;
2935 case glslang::EOpDot:
2936 opCode = spv::OpDot;
2937 break;
2938 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002939 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002940 break;
2941
2942 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002943 if (isFloat)
2944 libCall = spv::GLSLstd450FClamp;
2945 else if (isUnsigned)
2946 libCall = spv::GLSLstd450UClamp;
2947 else
2948 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002949 builder.promoteScalar(precision, operands.front(), operands[1]);
2950 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002951 break;
2952 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07002953 if (isFloat)
2954 libCall = spv::GLSLstd450FMix;
2955 else
2956 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002957 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002958 break;
2959 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002960 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002961 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002962 break;
2963 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002964 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002965 builder.promoteScalar(precision, operands[0], operands[2]);
2966 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002967 break;
2968
2969 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06002970 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06002971 break;
2972 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06002973 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06002974 break;
2975 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06002976 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06002977 break;
2978 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06002979 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06002980 break;
2981 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002982 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06002983 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002984 case glslang::EOpInterpolateAtSample:
2985 libCall = spv::GLSLstd450InterpolateAtSample;
2986 break;
2987 case glslang::EOpInterpolateAtOffset:
2988 libCall = spv::GLSLstd450InterpolateAtOffset;
2989 break;
John Kessenich55e7d112015-11-15 21:33:39 -07002990 case glslang::EOpAddCarry:
2991 opCode = spv::OpIAddCarry;
2992 typeId = builder.makeStructResultType(typeId0, typeId0);
2993 consumedOperands = 2;
2994 break;
2995 case glslang::EOpSubBorrow:
2996 opCode = spv::OpISubBorrow;
2997 typeId = builder.makeStructResultType(typeId0, typeId0);
2998 consumedOperands = 2;
2999 break;
3000 case glslang::EOpUMulExtended:
3001 opCode = spv::OpUMulExtended;
3002 typeId = builder.makeStructResultType(typeId0, typeId0);
3003 consumedOperands = 2;
3004 break;
3005 case glslang::EOpIMulExtended:
3006 opCode = spv::OpSMulExtended;
3007 typeId = builder.makeStructResultType(typeId0, typeId0);
3008 consumedOperands = 2;
3009 break;
3010 case glslang::EOpBitfieldExtract:
3011 if (isUnsigned)
3012 opCode = spv::OpBitFieldUExtract;
3013 else
3014 opCode = spv::OpBitFieldSExtract;
3015 break;
3016 case glslang::EOpBitfieldInsert:
3017 opCode = spv::OpBitFieldInsert;
3018 break;
3019
3020 case glslang::EOpFma:
3021 libCall = spv::GLSLstd450Fma;
3022 break;
3023 case glslang::EOpFrexp:
3024 libCall = spv::GLSLstd450FrexpStruct;
3025 if (builder.getNumComponents(operands[0]) == 1)
3026 frexpIntType = builder.makeIntegerType(32, true);
3027 else
3028 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3029 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3030 consumedOperands = 1;
3031 break;
3032 case glslang::EOpLdexp:
3033 libCall = spv::GLSLstd450Ldexp;
3034 break;
3035
John Kessenich140f3df2015-06-26 16:58:36 -06003036 default:
3037 return 0;
3038 }
3039
3040 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003041 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003042 // Use an extended instruction from the standard library.
3043 // Construct the call arguments, without modifying the original operands vector.
3044 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3045 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
3046 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003047 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003048 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003049 case 0:
3050 // should all be handled by visitAggregate and createNoArgOperation
3051 assert(0);
3052 return 0;
3053 case 1:
3054 // should all be handled by createUnaryOperation
3055 assert(0);
3056 return 0;
3057 case 2:
3058 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3059 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003060 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003061 // anything 3 or over doesn't have l-value operands, so all should be consumed
3062 assert(consumedOperands == operands.size());
3063 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003064 break;
3065 }
3066 }
3067
John Kessenich55e7d112015-11-15 21:33:39 -07003068 // Decode the return types that were structures
3069 switch (op) {
3070 case glslang::EOpAddCarry:
3071 case glslang::EOpSubBorrow:
3072 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3073 id = builder.createCompositeExtract(id, typeId0, 0);
3074 break;
3075 case glslang::EOpUMulExtended:
3076 case glslang::EOpIMulExtended:
3077 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3078 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3079 break;
3080 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003081 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003082 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3083 id = builder.createCompositeExtract(id, typeId0, 0);
3084 break;
3085 default:
3086 break;
3087 }
3088
John Kessenich140f3df2015-06-26 16:58:36 -06003089 builder.setPrecision(id, precision);
3090
3091 return id;
3092}
3093
3094// Intrinsics with no arguments, no return value, and no precision.
3095spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3096{
3097 // TODO: get the barrier operands correct
3098
3099 switch (op) {
3100 case glslang::EOpEmitVertex:
3101 builder.createNoResultOp(spv::OpEmitVertex);
3102 return 0;
3103 case glslang::EOpEndPrimitive:
3104 builder.createNoResultOp(spv::OpEndPrimitive);
3105 return 0;
3106 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003107 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3108 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003109 return 0;
3110 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003111 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003112 return 0;
3113 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003114 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003115 return 0;
3116 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003117 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003118 return 0;
3119 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003121 return 0;
3122 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003123 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003124 return 0;
3125 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003126 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003127 return 0;
3128 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003129 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003130 return 0;
3131 }
3132}
3133
3134spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3135{
John Kessenich2f273362015-07-18 22:34:27 -06003136 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003137 spv::Id id;
3138 if (symbolValues.end() != iter) {
3139 id = iter->second;
3140 return id;
3141 }
3142
3143 // it was not found, create it
3144 id = createSpvVariable(symbol);
3145 symbolValues[symbol->getId()] = id;
3146
3147 if (! symbol->getType().isStruct()) {
3148 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
3149 addDecoration(id, TranslateInterpolationDecoration(symbol->getType()));
3150 if (symbol->getQualifier().hasLocation())
3151 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3152 if (symbol->getQualifier().hasIndex())
3153 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3154 if (symbol->getQualifier().hasComponent())
3155 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3156 if (glslangIntermediate->getXfbMode()) {
3157 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003158 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003159 if (symbol->getQualifier().hasXfbBuffer())
3160 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3161 if (symbol->getQualifier().hasXfbOffset())
3162 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3163 }
3164 }
3165
3166 addDecoration(id, TranslateInvariantDecoration(symbol->getType()));
3167 if (symbol->getQualifier().hasStream())
3168 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3169 if (symbol->getQualifier().hasSet())
3170 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3171 if (symbol->getQualifier().hasBinding())
3172 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3173 if (glslangIntermediate->getXfbMode()) {
3174 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003175 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003176 if (symbol->getQualifier().hasXfbBuffer())
3177 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3178 }
3179
3180 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003181 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003182 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003183 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003184
John Kessenich140f3df2015-06-26 16:58:36 -06003185 return id;
3186}
3187
John Kessenich55e7d112015-11-15 21:33:39 -07003188// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003189void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3190{
3191 if (dec != spv::BadValue)
3192 builder.addDecoration(id, dec);
3193}
3194
John Kessenich55e7d112015-11-15 21:33:39 -07003195// If 'dec' is valid, add a one-operand decoration to an object
3196void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3197{
3198 if (dec != spv::BadValue)
3199 builder.addDecoration(id, dec, value);
3200}
3201
3202// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003203void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3204{
3205 if (dec != spv::BadValue)
3206 builder.addMemberDecoration(id, (unsigned)member, dec);
3207}
3208
John Kessenich55e7d112015-11-15 21:33:39 -07003209// Make a full tree of instructions to build a SPIR-V specialization constant,
3210// or regularly constant if possible.
3211//
3212// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3213//
3214// Recursively walk the nodes. The nodes form a tree whose leaves are
3215// regular constants, which themselves are trees that createSpvConstant()
3216// recursively walks. So, this function walks the "top" of the tree:
3217// - emit specialization constant-building instructions for specConstant
3218// - when running into a non-spec-constant, switch to createSpvConstant()
3219spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3220{
3221 assert(node.getQualifier().storage == glslang::EvqConst);
3222
3223 // hand off to the non-spec-constant path
3224 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3225 int nextConst = 0;
3226 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3227}
3228
John Kessenich140f3df2015-06-26 16:58:36 -06003229// Use 'consts' as the flattened glslang source of scalar constants to recursively
3230// build the aggregate SPIR-V constant.
3231//
3232// If there are not enough elements present in 'consts', 0 will be substituted;
3233// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3234//
John Kessenich55e7d112015-11-15 21:33:39 -07003235spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003236{
3237 // vector of constants for SPIR-V
3238 std::vector<spv::Id> spvConsts;
3239
3240 // Type is used for struct and array constants
3241 spv::Id typeId = convertGlslangToSpvType(glslangType);
3242
3243 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003244 glslang::TType elementType(glslangType, 0);
3245 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003246 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003247 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003248 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003249 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003250 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003251 } else if (glslangType.getStruct()) {
3252 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3253 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003254 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003255 } else if (glslangType.isVector()) {
3256 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3257 bool zero = nextConst >= consts.size();
3258 switch (glslangType.getBasicType()) {
3259 case glslang::EbtInt:
3260 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3261 break;
3262 case glslang::EbtUint:
3263 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3264 break;
3265 case glslang::EbtFloat:
3266 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3267 break;
3268 case glslang::EbtDouble:
3269 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3270 break;
3271 case glslang::EbtBool:
3272 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3273 break;
3274 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003275 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003276 break;
3277 }
3278 ++nextConst;
3279 }
3280 } else {
3281 // we have a non-aggregate (scalar) constant
3282 bool zero = nextConst >= consts.size();
3283 spv::Id scalar = 0;
3284 switch (glslangType.getBasicType()) {
3285 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003286 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003287 break;
3288 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003289 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003290 break;
3291 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003292 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003293 break;
3294 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003295 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003296 break;
3297 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003298 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003299 break;
3300 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003301 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003302 break;
3303 }
3304 ++nextConst;
3305 return scalar;
3306 }
3307
3308 return builder.makeCompositeConstant(typeId, spvConsts);
3309}
3310
John Kessenich7c1aa102015-10-15 13:29:11 -06003311// Return true if the node is a constant or symbol whose reading has no
3312// non-trivial observable cost or effect.
3313bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3314{
3315 // don't know what this is
3316 if (node == nullptr)
3317 return false;
3318
3319 // a constant is safe
3320 if (node->getAsConstantUnion() != nullptr)
3321 return true;
3322
3323 // not a symbol means non-trivial
3324 if (node->getAsSymbolNode() == nullptr)
3325 return false;
3326
3327 // a symbol, depends on what's being read
3328 switch (node->getType().getQualifier().storage) {
3329 case glslang::EvqTemporary:
3330 case glslang::EvqGlobal:
3331 case glslang::EvqIn:
3332 case glslang::EvqInOut:
3333 case glslang::EvqConst:
3334 case glslang::EvqConstReadOnly:
3335 case glslang::EvqUniform:
3336 return true;
3337 default:
3338 return false;
3339 }
3340}
3341
3342// A node is trivial if it is a single operation with no side effects.
3343// Error on the side of saying non-trivial.
3344// Return true if trivial.
3345bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3346{
3347 if (node == nullptr)
3348 return false;
3349
3350 // symbols and constants are trivial
3351 if (isTrivialLeaf(node))
3352 return true;
3353
3354 // otherwise, it needs to be a simple operation or one or two leaf nodes
3355
3356 // not a simple operation
3357 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3358 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3359 if (binaryNode == nullptr && unaryNode == nullptr)
3360 return false;
3361
3362 // not on leaf nodes
3363 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3364 return false;
3365
3366 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3367 return false;
3368 }
3369
3370 switch (node->getAsOperator()->getOp()) {
3371 case glslang::EOpLogicalNot:
3372 case glslang::EOpConvIntToBool:
3373 case glslang::EOpConvUintToBool:
3374 case glslang::EOpConvFloatToBool:
3375 case glslang::EOpConvDoubleToBool:
3376 case glslang::EOpEqual:
3377 case glslang::EOpNotEqual:
3378 case glslang::EOpLessThan:
3379 case glslang::EOpGreaterThan:
3380 case glslang::EOpLessThanEqual:
3381 case glslang::EOpGreaterThanEqual:
3382 case glslang::EOpIndexDirect:
3383 case glslang::EOpIndexDirectStruct:
3384 case glslang::EOpLogicalXor:
3385 case glslang::EOpAny:
3386 case glslang::EOpAll:
3387 return true;
3388 default:
3389 return false;
3390 }
3391}
3392
3393// Emit short-circuiting code, where 'right' is never evaluated unless
3394// the left side is true (for &&) or false (for ||).
3395spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3396{
3397 spv::Id boolTypeId = builder.makeBoolType();
3398
3399 // emit left operand
3400 builder.clearAccessChain();
3401 left.traverse(this);
3402 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3403
3404 // Operands to accumulate OpPhi operands
3405 std::vector<spv::Id> phiOperands;
3406 // accumulate left operand's phi information
3407 phiOperands.push_back(leftId);
3408 phiOperands.push_back(builder.getBuildPoint()->getId());
3409
3410 // Make the two kinds of operation symmetric with a "!"
3411 // || => emit "if (! left) result = right"
3412 // && => emit "if ( left) result = right"
3413 //
3414 // TODO: this runtime "not" for || could be avoided by adding functionality
3415 // to 'builder' to have an "else" without an "then"
3416 if (op == glslang::EOpLogicalOr)
3417 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3418
3419 // make an "if" based on the left value
3420 spv::Builder::If ifBuilder(leftId, builder);
3421
3422 // emit right operand as the "then" part of the "if"
3423 builder.clearAccessChain();
3424 right.traverse(this);
3425 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3426
3427 // accumulate left operand's phi information
3428 phiOperands.push_back(rightId);
3429 phiOperands.push_back(builder.getBuildPoint()->getId());
3430
3431 // finish the "if"
3432 ifBuilder.makeEndIf();
3433
3434 // phi together the two results
3435 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3436}
3437
John Kessenich140f3df2015-06-26 16:58:36 -06003438}; // end anonymous namespace
3439
3440namespace glslang {
3441
John Kessenich68d78fd2015-07-12 19:28:10 -06003442void GetSpirvVersion(std::string& version)
3443{
John Kessenich9e55f632015-07-15 10:03:39 -06003444 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003445 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003446 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003447 version = buf;
3448}
3449
John Kessenich140f3df2015-06-26 16:58:36 -06003450// Write SPIR-V out to a binary file
3451void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3452{
3453 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003454 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003455 for (int i = 0; i < (int)spirv.size(); ++i) {
3456 unsigned int word = spirv[i];
3457 out.write((const char*)&word, 4);
3458 }
3459 out.close();
3460}
3461
3462//
3463// Set up the glslang traversal
3464//
3465void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3466{
3467 TIntermNode* root = intermediate.getTreeRoot();
3468
3469 if (root == 0)
3470 return;
3471
3472 glslang::GetThreadPoolAllocator().push();
3473
3474 TGlslangToSpvTraverser it(&intermediate);
3475
3476 root->traverse(&it);
3477
3478 it.dumpSpv(spirv);
3479
3480 glslang::GetThreadPoolAllocator().pop();
3481}
3482
3483}; // end namespace glslang