blob: c17a73e96dff526a7a36ae6a52729b8d51f0bb27 [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 Kesseniche0b6cad2015-12-24 10:30:13 -070094 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
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 Kesseniche0b6cad2015-12-24 10:30:13 -0700302spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600303{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700304 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700305 // Smooth decoration doesn't exist in SPIR-V 1.0
306 return (spv::Decoration)spv::BadValue;
307 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700308 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700309 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700310 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600311 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700312 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600313 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700314 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return spv::DecorationCentroid;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700316 else if (qualifier.sample)
John Kessenich140f3df2015-06-26 16:58:36 -0600317 return spv::DecorationSample;
318 else
319 return (spv::Decoration)spv::BadValue;
320}
321
322// If glslang type is invaraiant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700323spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600324{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700325 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600326 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 Kesseniche0b6cad2015-12-24 10:30:13 -0700423void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
424{
425 if (child.layoutMatrix == glslang::ElmNone)
426 child.layoutMatrix = parent.layoutMatrix;
427
428 if (parent.invariant)
429 child.invariant = true;
430 if (parent.nopersp)
431 child.nopersp = true;
432 if (parent.flat)
433 child.flat = true;
434 if (parent.centroid)
435 child.centroid = true;
436 if (parent.patch)
437 child.patch = true;
438 if (parent.sample)
439 child.sample = true;
440}
441
442bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
443{
444 // This should list qualifiers that simultaneous satisify:
445 // - struct members can inherit from a struct declaration
446 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
447 // - are not part of the offset/st430/etc or row/column-major layout
448 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample;
449}
450
John Kessenich140f3df2015-06-26 16:58:36 -0600451//
452// Implement the TGlslangToSpvTraverser class.
453//
454
455TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
456 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700457 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600458 inMain(false), mainTerminated(false), linkageOnly(false),
459 glslangIntermediate(glslangIntermediate)
460{
461 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
462
463 builder.clearAccessChain();
464 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
465 stdBuiltins = builder.import("GLSL.std.450");
466 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
467 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700468 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600469
470 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600471 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
472 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600473 builder.addSourceExtension(it->c_str());
474
475 // Add the top-level modes for this shader.
476
477 if (glslangIntermediate->getXfbMode())
478 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
479
480 unsigned int mode;
481 switch (glslangIntermediate->getStage()) {
482 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600483 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600484 break;
485
486 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600487 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600488 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
489 break;
490
491 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600492 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600493 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700494 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
495 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
496 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600497 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600498 }
499 if (mode != spv::BadValue)
500 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
501
John Kesseniche6903322015-10-13 16:29:02 -0600502 switch (glslangIntermediate->getVertexSpacing()) {
503 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
504 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
505 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
506 default: mode = spv::BadValue; break;
507 }
508 if (mode != spv::BadValue)
509 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
510
511 switch (glslangIntermediate->getVertexOrder()) {
512 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
513 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
514 default: mode = spv::BadValue; break;
515 }
516 if (mode != spv::BadValue)
517 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
518
519 if (glslangIntermediate->getPointMode())
520 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600521 break;
522
523 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600524 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600525 switch (glslangIntermediate->getInputPrimitive()) {
526 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
527 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
528 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700529 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
531 default: mode = spv::BadValue; break;
532 }
533 if (mode != spv::BadValue)
534 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600535
John Kessenich140f3df2015-06-26 16:58:36 -0600536 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
537
538 switch (glslangIntermediate->getOutputPrimitive()) {
539 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
540 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
541 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
542 default: mode = spv::BadValue; break;
543 }
544 if (mode != spv::BadValue)
545 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
546 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
547 break;
548
549 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600550 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600551 if (glslangIntermediate->getPixelCenterInteger())
552 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600553
John Kessenich140f3df2015-06-26 16:58:36 -0600554 if (glslangIntermediate->getOriginUpperLeft())
555 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600556 else
557 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600558
559 if (glslangIntermediate->getEarlyFragmentTests())
560 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
561
562 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600563 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
564 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
565 default: mode = spv::BadValue; break;
566 }
567 if (mode != spv::BadValue)
568 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
569
570 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
571 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600572 break;
573
574 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600575 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600576 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
577 glslangIntermediate->getLocalSize(1),
578 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600579 break;
580
581 default:
582 break;
583 }
584
585}
586
John Kessenich7ba63412015-12-20 17:37:07 -0700587// Finish everything and dump
588void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
589{
590 // finish off the entry-point SPV instruction by adding the Input/Output <id>
591 for (auto it : iOSet)
592 entryPoint->addIdOperand(it);
593
594 builder.dump(out);
595}
596
John Kessenich140f3df2015-06-26 16:58:36 -0600597TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
598{
599 if (! mainTerminated) {
600 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
601 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600602 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600603 }
604}
605
606//
607// Implement the traversal functions.
608//
609// Return true from interior nodes to have the external traversal
610// continue on to children. Return false if children were
611// already processed.
612//
613
614//
615// Symbols can turn into
616// - uniform/input reads
617// - output writes
618// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
619// - something simple that degenerates into the last bullet
620//
621void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
622{
623 // getSymbolId() will set up all the IO decorations on the first call.
624 // Formal function parameters were mapped during makeFunctions().
625 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700626
627 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
628 if (builder.isPointer(id)) {
629 spv::StorageClass sc = builder.getStorageClass(id);
630 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
631 iOSet.insert(id);
632 }
633
634 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600635 if (! linkageOnly) {
636 // Prepare to generate code for the access
637
638 // L-value chains will be computed left to right. We're on the symbol now,
639 // which is the left-most part of the access chain, so now is "clear" time,
640 // followed by setting the base.
641 builder.clearAccessChain();
642
643 // For now, we consider all user variables as being in memory, so they are pointers,
644 // except for "const in" arguments to a function, which are an intermediate object.
645 // See comments in handleUserFunctionCall().
646 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
647 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
648 builder.setAccessChainRValue(id);
649 else
650 builder.setAccessChainLValue(id);
651 }
652}
653
654bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
655{
656 // First, handle special cases
657 switch (node->getOp()) {
658 case glslang::EOpAssign:
659 case glslang::EOpAddAssign:
660 case glslang::EOpSubAssign:
661 case glslang::EOpMulAssign:
662 case glslang::EOpVectorTimesMatrixAssign:
663 case glslang::EOpVectorTimesScalarAssign:
664 case glslang::EOpMatrixTimesScalarAssign:
665 case glslang::EOpMatrixTimesMatrixAssign:
666 case glslang::EOpDivAssign:
667 case glslang::EOpModAssign:
668 case glslang::EOpAndAssign:
669 case glslang::EOpInclusiveOrAssign:
670 case glslang::EOpExclusiveOrAssign:
671 case glslang::EOpLeftShiftAssign:
672 case glslang::EOpRightShiftAssign:
673 // A bin-op assign "a += b" means the same thing as "a = a + b"
674 // where a is evaluated before b. For a simple assignment, GLSL
675 // says to evaluate the left before the right. So, always, left
676 // node then right node.
677 {
678 // get the left l-value, save it away
679 builder.clearAccessChain();
680 node->getLeft()->traverse(this);
681 spv::Builder::AccessChain lValue = builder.getAccessChain();
682
683 // evaluate the right
684 builder.clearAccessChain();
685 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600686 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600687
688 if (node->getOp() != glslang::EOpAssign) {
689 // the left is also an r-value
690 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600691 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600692
693 // do the operation
694 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
695 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
696 node->getType().getBasicType());
697
698 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700699 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600700 }
701
702 // store the result
703 builder.setAccessChain(lValue);
704 builder.accessChainStore(rValue);
705
706 // assignments are expressions having an rValue after they are evaluated...
707 builder.clearAccessChain();
708 builder.setAccessChainRValue(rValue);
709 }
710 return false;
711 case glslang::EOpIndexDirect:
712 case glslang::EOpIndexDirectStruct:
713 {
714 // Get the left part of the access chain.
715 node->getLeft()->traverse(this);
716
717 // Add the next element in the chain
718
John Kessenich55e7d112015-11-15 21:33:39 -0700719 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600720 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
721 // This may be, e.g., an anonymous block-member selection, which generally need
722 // index remapping due to hidden members in anonymous blocks.
723 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700724 assert(remapper.size() > 0);
725 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600726 }
727
728 if (! node->getLeft()->getType().isArray() &&
729 node->getLeft()->getType().isVector() &&
730 node->getOp() == glslang::EOpIndexDirect) {
731 // This is essentially a hard-coded vector swizzle of size 1,
732 // so short circuit the access-chain stuff with a swizzle.
733 std::vector<unsigned> swizzle;
734 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600735 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600736 } else {
737 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600738 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600739 }
740 }
741 return false;
742 case glslang::EOpIndexIndirect:
743 {
744 // Structure or array or vector indirection.
745 // Will use native SPIR-V access-chain for struct and array indirection;
746 // matrices are arrays of vectors, so will also work for a matrix.
747 // Will use the access chain's 'component' for variable index into a vector.
748
749 // This adapter is building access chains left to right.
750 // Set up the access chain to the left.
751 node->getLeft()->traverse(this);
752
753 // save it so that computing the right side doesn't trash it
754 spv::Builder::AccessChain partial = builder.getAccessChain();
755
756 // compute the next index in the chain
757 builder.clearAccessChain();
758 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600759 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600760
761 // restore the saved access chain
762 builder.setAccessChain(partial);
763
764 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600765 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600766 else
John Kessenichfa668da2015-09-13 14:46:30 -0600767 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600768 }
769 return false;
770 case glslang::EOpVectorSwizzle:
771 {
772 node->getLeft()->traverse(this);
773 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
774 std::vector<unsigned> swizzle;
775 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
776 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600777 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600778 }
779 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600780 case glslang::EOpLogicalOr:
781 case glslang::EOpLogicalAnd:
782 {
783
784 // These may require short circuiting, but can sometimes be done as straight
785 // binary operations. The right operand must be short circuited if it has
786 // side effects, and should probably be if it is complex.
787 if (isTrivial(node->getRight()->getAsTyped()))
788 break; // handle below as a normal binary operation
789 // otherwise, we need to do dynamic short circuiting on the right operand
790 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
791 builder.clearAccessChain();
792 builder.setAccessChainRValue(result);
793 }
794 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600795 default:
796 break;
797 }
798
799 // Assume generic binary op...
800
801 // Get the operands
802 builder.clearAccessChain();
803 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600804 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600805
806 builder.clearAccessChain();
807 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600808 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600809
810 spv::Id result;
811 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
812
813 result = createBinaryOperation(node->getOp(), precision,
814 convertGlslangToSpvType(node->getType()), left, right,
815 node->getLeft()->getType().getBasicType());
816
John Kessenich50e57562015-12-21 21:21:11 -0700817 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600818 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700819 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700820 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600821 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600822 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600823 return false;
824 }
John Kessenich140f3df2015-06-26 16:58:36 -0600825}
826
827bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
828{
John Kessenichfc51d282015-08-19 13:34:18 -0600829 spv::Id result = spv::NoResult;
830
831 // try texturing first
832 result = createImageTextureFunctionCall(node);
833 if (result != spv::NoResult) {
834 builder.clearAccessChain();
835 builder.setAccessChainRValue(result);
836
837 return false; // done with this node
838 }
839
840 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600841
842 if (node->getOp() == glslang::EOpArrayLength) {
843 // Quite special; won't want to evaluate the operand.
844
845 // Normal .length() would have been constant folded by the front-end.
846 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600847 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600848 assert(node->getOperand()->getType().isRuntimeSizedArray());
849 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
850 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600851 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
852 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600853
854 builder.clearAccessChain();
855 builder.setAccessChainRValue(length);
856
857 return false;
858 }
859
John Kessenichfc51d282015-08-19 13:34:18 -0600860 // Start by evaluating the operand
861
John Kessenich140f3df2015-06-26 16:58:36 -0600862 builder.clearAccessChain();
863 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800864
Rex Xufc618912015-09-09 16:42:49 +0800865 spv::Id operand = spv::NoResult;
866
867 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
868 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800869 node->getOp() == glslang::EOpAtomicCounter ||
870 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800871 operand = builder.accessChainGetLValue(); // Special case l-value operands
872 else
Rex Xu30f92582015-09-14 10:38:56 +0800873 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600874
875 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
876
877 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600878 if (! result)
879 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600880
881 // if not, then possibly an operation
882 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700883 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600884
885 if (result) {
886 builder.clearAccessChain();
887 builder.setAccessChainRValue(result);
888
889 return false; // done with this node
890 }
891
892 // it must be a special case, check...
893 switch (node->getOp()) {
894 case glslang::EOpPostIncrement:
895 case glslang::EOpPostDecrement:
896 case glslang::EOpPreIncrement:
897 case glslang::EOpPreDecrement:
898 {
899 // we need the integer value "1" or the floating point "1.0" to add/subtract
900 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
901 builder.makeFloatConstant(1.0F) :
902 builder.makeIntConstant(1);
903 glslang::TOperator op;
904 if (node->getOp() == glslang::EOpPreIncrement ||
905 node->getOp() == glslang::EOpPostIncrement)
906 op = glslang::EOpAdd;
907 else
908 op = glslang::EOpSub;
909
910 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
911 convertGlslangToSpvType(node->getType()), operand, one,
912 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700913 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600914
915 // The result of operation is always stored, but conditionally the
916 // consumed result. The consumed result is always an r-value.
917 builder.accessChainStore(result);
918 builder.clearAccessChain();
919 if (node->getOp() == glslang::EOpPreIncrement ||
920 node->getOp() == glslang::EOpPreDecrement)
921 builder.setAccessChainRValue(result);
922 else
923 builder.setAccessChainRValue(operand);
924 }
925
926 return false;
927
928 case glslang::EOpEmitStreamVertex:
929 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
930 return false;
931 case glslang::EOpEndStreamPrimitive:
932 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
933 return false;
934
935 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700936 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -0700937 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -0600938 }
John Kessenich140f3df2015-06-26 16:58:36 -0600939}
940
941bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
942{
John Kessenichfc51d282015-08-19 13:34:18 -0600943 spv::Id result = spv::NoResult;
944
945 // try texturing
946 result = createImageTextureFunctionCall(node);
947 if (result != spv::NoResult) {
948 builder.clearAccessChain();
949 builder.setAccessChainRValue(result);
950
951 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600952 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800953 // "imageStore" is a special case, which has no result
954 return false;
955 }
John Kessenichfc51d282015-08-19 13:34:18 -0600956
John Kessenich140f3df2015-06-26 16:58:36 -0600957 glslang::TOperator binOp = glslang::EOpNull;
958 bool reduceComparison = true;
959 bool isMatrix = false;
960 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600961 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600962
963 assert(node->getOp());
964
965 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
966
967 switch (node->getOp()) {
968 case glslang::EOpSequence:
969 {
970 if (preVisit)
971 ++sequenceDepth;
972 else
973 --sequenceDepth;
974
975 if (sequenceDepth == 1) {
976 // If this is the parent node of all the functions, we want to see them
977 // early, so all call points have actual SPIR-V functions to reference.
978 // In all cases, still let the traverser visit the children for us.
979 makeFunctions(node->getAsAggregate()->getSequence());
980
981 // Also, we want all globals initializers to go into the entry of main(), before
982 // anything else gets there, so visit out of order, doing them all now.
983 makeGlobalInitializers(node->getAsAggregate()->getSequence());
984
985 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
986 // so do them manually.
987 visitFunctions(node->getAsAggregate()->getSequence());
988
989 return false;
990 }
991
992 return true;
993 }
994 case glslang::EOpLinkerObjects:
995 {
996 if (visit == glslang::EvPreVisit)
997 linkageOnly = true;
998 else
999 linkageOnly = false;
1000
1001 return true;
1002 }
1003 case glslang::EOpComma:
1004 {
1005 // processing from left to right naturally leaves the right-most
1006 // lying around in the access chain
1007 glslang::TIntermSequence& glslangOperands = node->getSequence();
1008 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1009 glslangOperands[i]->traverse(this);
1010
1011 return false;
1012 }
1013 case glslang::EOpFunction:
1014 if (visit == glslang::EvPreVisit) {
1015 if (isShaderEntrypoint(node)) {
1016 inMain = true;
1017 builder.setBuildPoint(shaderEntry->getLastBlock());
1018 } else {
1019 handleFunctionEntry(node);
1020 }
1021 } else {
1022 if (inMain)
1023 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001024 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001025 inMain = false;
1026 }
1027
1028 return true;
1029 case glslang::EOpParameters:
1030 // Parameters will have been consumed by EOpFunction processing, but not
1031 // the body, so we still visited the function node's children, making this
1032 // child redundant.
1033 return false;
1034 case glslang::EOpFunctionCall:
1035 {
1036 if (node->isUserDefined())
1037 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001038 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001039 builder.clearAccessChain();
1040 builder.setAccessChainRValue(result);
1041
1042 return false;
1043 }
1044 case glslang::EOpConstructMat2x2:
1045 case glslang::EOpConstructMat2x3:
1046 case glslang::EOpConstructMat2x4:
1047 case glslang::EOpConstructMat3x2:
1048 case glslang::EOpConstructMat3x3:
1049 case glslang::EOpConstructMat3x4:
1050 case glslang::EOpConstructMat4x2:
1051 case glslang::EOpConstructMat4x3:
1052 case glslang::EOpConstructMat4x4:
1053 case glslang::EOpConstructDMat2x2:
1054 case glslang::EOpConstructDMat2x3:
1055 case glslang::EOpConstructDMat2x4:
1056 case glslang::EOpConstructDMat3x2:
1057 case glslang::EOpConstructDMat3x3:
1058 case glslang::EOpConstructDMat3x4:
1059 case glslang::EOpConstructDMat4x2:
1060 case glslang::EOpConstructDMat4x3:
1061 case glslang::EOpConstructDMat4x4:
1062 isMatrix = true;
1063 // fall through
1064 case glslang::EOpConstructFloat:
1065 case glslang::EOpConstructVec2:
1066 case glslang::EOpConstructVec3:
1067 case glslang::EOpConstructVec4:
1068 case glslang::EOpConstructDouble:
1069 case glslang::EOpConstructDVec2:
1070 case glslang::EOpConstructDVec3:
1071 case glslang::EOpConstructDVec4:
1072 case glslang::EOpConstructBool:
1073 case glslang::EOpConstructBVec2:
1074 case glslang::EOpConstructBVec3:
1075 case glslang::EOpConstructBVec4:
1076 case glslang::EOpConstructInt:
1077 case glslang::EOpConstructIVec2:
1078 case glslang::EOpConstructIVec3:
1079 case glslang::EOpConstructIVec4:
1080 case glslang::EOpConstructUint:
1081 case glslang::EOpConstructUVec2:
1082 case glslang::EOpConstructUVec3:
1083 case glslang::EOpConstructUVec4:
1084 case glslang::EOpConstructStruct:
1085 {
1086 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001087 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001088 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1089 spv::Id constructed;
1090 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1091 std::vector<spv::Id> constituents;
1092 for (int c = 0; c < (int)arguments.size(); ++c)
1093 constituents.push_back(arguments[c]);
1094 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001095 } else if (isMatrix)
1096 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1097 else
1098 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001099
1100 builder.clearAccessChain();
1101 builder.setAccessChainRValue(constructed);
1102
1103 return false;
1104 }
1105
1106 // These six are component-wise compares with component-wise results.
1107 // Forward on to createBinaryOperation(), requesting a vector result.
1108 case glslang::EOpLessThan:
1109 case glslang::EOpGreaterThan:
1110 case glslang::EOpLessThanEqual:
1111 case glslang::EOpGreaterThanEqual:
1112 case glslang::EOpVectorEqual:
1113 case glslang::EOpVectorNotEqual:
1114 {
1115 // Map the operation to a binary
1116 binOp = node->getOp();
1117 reduceComparison = false;
1118 switch (node->getOp()) {
1119 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1120 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1121 default: binOp = node->getOp(); break;
1122 }
1123
1124 break;
1125 }
1126 case glslang::EOpMul:
1127 // compontent-wise matrix multiply
1128 binOp = glslang::EOpMul;
1129 break;
1130 case glslang::EOpOuterProduct:
1131 // two vectors multiplied to make a matrix
1132 binOp = glslang::EOpOuterProduct;
1133 break;
1134 case glslang::EOpDot:
1135 {
1136 // for scalar dot product, use multiply
1137 glslang::TIntermSequence& glslangOperands = node->getSequence();
1138 if (! glslangOperands[0]->getAsTyped()->isVector())
1139 binOp = glslang::EOpMul;
1140 break;
1141 }
1142 case glslang::EOpMod:
1143 // when an aggregate, this is the floating-point mod built-in function,
1144 // which can be emitted by the one in createBinaryOperation()
1145 binOp = glslang::EOpMod;
1146 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001147 case glslang::EOpEmitVertex:
1148 case glslang::EOpEndPrimitive:
1149 case glslang::EOpBarrier:
1150 case glslang::EOpMemoryBarrier:
1151 case glslang::EOpMemoryBarrierAtomicCounter:
1152 case glslang::EOpMemoryBarrierBuffer:
1153 case glslang::EOpMemoryBarrierImage:
1154 case glslang::EOpMemoryBarrierShared:
1155 case glslang::EOpGroupMemoryBarrier:
1156 noReturnValue = true;
1157 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1158 break;
1159
John Kessenich426394d2015-07-23 10:22:48 -06001160 case glslang::EOpAtomicAdd:
1161 case glslang::EOpAtomicMin:
1162 case glslang::EOpAtomicMax:
1163 case glslang::EOpAtomicAnd:
1164 case glslang::EOpAtomicOr:
1165 case glslang::EOpAtomicXor:
1166 case glslang::EOpAtomicExchange:
1167 case glslang::EOpAtomicCompSwap:
1168 atomic = true;
1169 break;
1170
John Kessenich140f3df2015-06-26 16:58:36 -06001171 default:
1172 break;
1173 }
1174
1175 //
1176 // See if it maps to a regular operation.
1177 //
John Kessenich140f3df2015-06-26 16:58:36 -06001178 if (binOp != glslang::EOpNull) {
1179 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1180 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1181 assert(left && right);
1182
1183 builder.clearAccessChain();
1184 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001185 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001186
1187 builder.clearAccessChain();
1188 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001189 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001190
1191 result = createBinaryOperation(binOp, precision,
1192 convertGlslangToSpvType(node->getType()), leftId, rightId,
1193 left->getType().getBasicType(), reduceComparison);
1194
1195 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001196 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 builder.clearAccessChain();
1198 builder.setAccessChainRValue(result);
1199
1200 return false;
1201 }
1202
John Kessenich426394d2015-07-23 10:22:48 -06001203 //
1204 // Create the list of operands.
1205 //
John Kessenich140f3df2015-06-26 16:58:36 -06001206 glslang::TIntermSequence& glslangOperands = node->getSequence();
1207 std::vector<spv::Id> operands;
1208 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1209 builder.clearAccessChain();
1210 glslangOperands[arg]->traverse(this);
1211
1212 // special case l-value operands; there are just a few
1213 bool lvalue = false;
1214 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001215 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001216 case glslang::EOpModf:
1217 if (arg == 1)
1218 lvalue = true;
1219 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001220 case glslang::EOpInterpolateAtSample:
1221 case glslang::EOpInterpolateAtOffset:
1222 if (arg == 0)
1223 lvalue = true;
1224 break;
Rex Xud4782c12015-09-06 16:30:11 +08001225 case glslang::EOpAtomicAdd:
1226 case glslang::EOpAtomicMin:
1227 case glslang::EOpAtomicMax:
1228 case glslang::EOpAtomicAnd:
1229 case glslang::EOpAtomicOr:
1230 case glslang::EOpAtomicXor:
1231 case glslang::EOpAtomicExchange:
1232 case glslang::EOpAtomicCompSwap:
1233 if (arg == 0)
1234 lvalue = true;
1235 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001236 case glslang::EOpAddCarry:
1237 case glslang::EOpSubBorrow:
1238 if (arg == 2)
1239 lvalue = true;
1240 break;
1241 case glslang::EOpUMulExtended:
1242 case glslang::EOpIMulExtended:
1243 if (arg >= 2)
1244 lvalue = true;
1245 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001246 default:
1247 break;
1248 }
1249 if (lvalue)
1250 operands.push_back(builder.accessChainGetLValue());
1251 else
John Kessenichfa668da2015-09-13 14:46:30 -06001252 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001253 }
John Kessenich426394d2015-07-23 10:22:48 -06001254
1255 if (atomic) {
1256 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001257 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001258 } else {
1259 // Pass through to generic operations.
1260 switch (glslangOperands.size()) {
1261 case 0:
1262 result = createNoArgOperation(node->getOp());
1263 break;
1264 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001265 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001266 break;
1267 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001268 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001269 break;
1270 }
John Kessenich140f3df2015-06-26 16:58:36 -06001271 }
1272
1273 if (noReturnValue)
1274 return false;
1275
1276 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001277 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001278 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001279 } else {
1280 builder.clearAccessChain();
1281 builder.setAccessChainRValue(result);
1282 return false;
1283 }
1284}
1285
1286bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1287{
1288 // This path handles both if-then-else and ?:
1289 // The if-then-else has a node type of void, while
1290 // ?: has a non-void node type
1291 spv::Id result = 0;
1292 if (node->getBasicType() != glslang::EbtVoid) {
1293 // don't handle this as just on-the-fly temporaries, because there will be two names
1294 // and better to leave SSA to later passes
1295 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1296 }
1297
1298 // emit the condition before doing anything with selection
1299 node->getCondition()->traverse(this);
1300
1301 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001302 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001303
1304 if (node->getTrueBlock()) {
1305 // emit the "then" statement
1306 node->getTrueBlock()->traverse(this);
1307 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001308 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001309 }
1310
1311 if (node->getFalseBlock()) {
1312 ifBuilder.makeBeginElse();
1313 // emit the "else" statement
1314 node->getFalseBlock()->traverse(this);
1315 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001316 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001317 }
1318
1319 ifBuilder.makeEndIf();
1320
1321 if (result) {
1322 // GLSL only has r-values as the result of a :?, but
1323 // if we have an l-value, that can be more efficient if it will
1324 // become the base of a complex r-value expression, because the
1325 // next layer copies r-values into memory to use the access-chain mechanism
1326 builder.clearAccessChain();
1327 builder.setAccessChainLValue(result);
1328 }
1329
1330 return false;
1331}
1332
1333bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1334{
1335 // emit and get the condition before doing anything with switch
1336 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001337 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001338
1339 // browse the children to sort out code segments
1340 int defaultSegment = -1;
1341 std::vector<TIntermNode*> codeSegments;
1342 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1343 std::vector<int> caseValues;
1344 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1345 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1346 TIntermNode* child = *c;
1347 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001348 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001349 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001350 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001351 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1352 } else
1353 codeSegments.push_back(child);
1354 }
1355
1356 // handle the case where the last code segment is missing, due to no code
1357 // statements between the last case and the end of the switch statement
1358 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1359 (int)codeSegments.size() == defaultSegment)
1360 codeSegments.push_back(nullptr);
1361
1362 // make the switch statement
1363 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001364 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001365
1366 // emit all the code in the segments
1367 breakForLoop.push(false);
1368 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1369 builder.nextSwitchSegment(segmentBlocks, s);
1370 if (codeSegments[s])
1371 codeSegments[s]->traverse(this);
1372 else
1373 builder.addSwitchBreak();
1374 }
1375 breakForLoop.pop();
1376
1377 builder.endSwitch(segmentBlocks);
1378
1379 return false;
1380}
1381
1382void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1383{
1384 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001385 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001386
1387 builder.clearAccessChain();
1388 builder.setAccessChainRValue(constant);
1389}
1390
1391bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1392{
1393 // body emission needs to know what the for-loop terminal is when it sees a "continue"
1394 loopTerminal.push(node->getTerminal());
1395
David Netoc22f37c2015-07-15 16:21:26 -04001396 builder.makeNewLoop(node->testFirst());
John Kessenich140f3df2015-06-26 16:58:36 -06001397
1398 if (node->getTest()) {
1399 node->getTest()->traverse(this);
1400 // the AST only contained the test computation, not the branch, we have to add it
John Kessenichfa668da2015-09-13 14:46:30 -06001401 spv::Id condition = builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001402 builder.createLoopTestBranch(condition);
David Netoc22f37c2015-07-15 16:21:26 -04001403 } else {
1404 builder.createBranchToBody();
John Kessenich140f3df2015-06-26 16:58:36 -06001405 }
1406
David Netoc22f37c2015-07-15 16:21:26 -04001407 if (node->getBody()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001408 breakForLoop.push(true);
1409 node->getBody()->traverse(this);
1410 breakForLoop.pop();
1411 }
1412
1413 if (loopTerminal.top())
1414 loopTerminal.top()->traverse(this);
1415
1416 builder.closeLoop();
1417
1418 loopTerminal.pop();
1419
1420 return false;
1421}
1422
1423bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1424{
1425 if (node->getExpression())
1426 node->getExpression()->traverse(this);
1427
1428 switch (node->getFlowOp()) {
1429 case glslang::EOpKill:
1430 builder.makeDiscard();
1431 break;
1432 case glslang::EOpBreak:
1433 if (breakForLoop.top())
1434 builder.createLoopExit();
1435 else
1436 builder.addSwitchBreak();
1437 break;
1438 case glslang::EOpContinue:
1439 if (loopTerminal.top())
1440 loopTerminal.top()->traverse(this);
1441 builder.createLoopContinue();
1442 break;
1443 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001444 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001445 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001446 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001447 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001448
1449 builder.clearAccessChain();
1450 break;
1451
1452 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001453 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001454 break;
1455 }
1456
1457 return false;
1458}
1459
1460spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1461{
1462 // First, steer off constants, which are not SPIR-V variables, but
1463 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001464 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001465 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001466 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001467 }
1468
1469 // Now, handle actual variables
1470 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1471 spv::Id spvType = convertGlslangToSpvType(node->getType());
1472
1473 const char* name = node->getName().c_str();
1474 if (glslang::IsAnonymous(name))
1475 name = "";
1476
1477 return builder.createVariable(storageClass, spvType, name);
1478}
1479
1480// Return type Id of the sampled type.
1481spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1482{
1483 switch (sampler.type) {
1484 case glslang::EbtFloat: return builder.makeFloatType(32);
1485 case glslang::EbtInt: return builder.makeIntType(32);
1486 case glslang::EbtUint: return builder.makeUintType(32);
1487 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001488 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001489 return builder.makeFloatType(32);
1490 }
1491}
1492
John Kessenich3ac051e2015-12-20 11:29:16 -07001493// Convert from a glslang type to an SPV type, by calling into a
1494// recursive version of this function. This establishes the inherited
1495// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001496spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1497{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001498 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001499}
1500
1501// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
1502// explicitLayout can be kept the same throughout the heirarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001503spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001504{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001505 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001506
1507 switch (type.getBasicType()) {
1508 case glslang::EbtVoid:
1509 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001510 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001511 break;
1512 case glslang::EbtFloat:
1513 spvType = builder.makeFloatType(32);
1514 break;
1515 case glslang::EbtDouble:
1516 spvType = builder.makeFloatType(64);
1517 break;
1518 case glslang::EbtBool:
1519 spvType = builder.makeBoolType();
1520 break;
1521 case glslang::EbtInt:
1522 spvType = builder.makeIntType(32);
1523 break;
1524 case glslang::EbtUint:
1525 spvType = builder.makeUintType(32);
1526 break;
John Kessenich426394d2015-07-23 10:22:48 -06001527 case glslang::EbtAtomicUint:
1528 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1529 spvType = builder.makeUintType(32);
1530 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001531 case glslang::EbtSampler:
1532 {
1533 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001534 // an image is present, make its type
1535 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1536 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001537 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001538 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001539 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001540 }
John Kessenich140f3df2015-06-26 16:58:36 -06001541 break;
1542 case glslang::EbtStruct:
1543 case glslang::EbtBlock:
1544 {
1545 // If we've seen this struct type, return it
1546 const glslang::TTypeList* glslangStruct = type.getStruct();
1547 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001548
1549 // Try to share structs for different layouts, but not yet for other
1550 // kinds of qualification (primarily not yet including interpolant qualification).
1551 if (! HasNonLayoutQualifiers(qualifier))
1552 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1553 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001554 break;
1555
1556 // else, we haven't seen it...
1557
1558 // Create a vector of struct types for SPIR-V to consume
1559 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1560 if (type.getBasicType() == glslang::EbtBlock)
1561 memberRemapper[glslangStruct].resize(glslangStruct->size());
1562 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1563 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1564 if (glslangType.hiddenMember()) {
1565 ++memberDelta;
1566 if (type.getBasicType() == glslang::EbtBlock)
1567 memberRemapper[glslangStruct][i] = -1;
1568 } else {
1569 if (type.getBasicType() == glslang::EbtBlock)
1570 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001571 // modify just this child's view of the qualifier
1572 glslang::TQualifier subQualifier = glslangType.getQualifier();
1573 InheritQualifiers(subQualifier, qualifier);
1574 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001575 }
1576 }
1577
1578 // Make the SPIR-V type
1579 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001580 if (! HasNonLayoutQualifiers(qualifier))
1581 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001582
1583 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001584 int offset = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06001585 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1586 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1587 int member = i;
1588 if (type.getBasicType() == glslang::EbtBlock)
1589 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001590
John Kesseniche0b6cad2015-12-24 10:30:13 -07001591 // modify just this child's view of the qualifier
1592 glslang::TQualifier subQualifier = glslangType.getQualifier();
1593 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001594
John Kessenich140f3df2015-06-26 16:58:36 -06001595 // using -1 above to indicate a hidden member
1596 if (member >= 0) {
1597 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001598 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001599 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001600 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1601 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001602 if (glslangType.getQualifier().hasLocation())
1603 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, glslangType.getQualifier().layoutLocation);
1604 if (glslangType.getQualifier().hasComponent())
1605 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1606 if (glslangType.getQualifier().hasXfbOffset())
1607 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001608 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001609 // figure out what to do with offset, which is accumulating
1610 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001611 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001612 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001613 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001614 offset = nextOffset;
1615 }
John Kessenich140f3df2015-06-26 16:58:36 -06001616
John Kessenichf85e8062015-12-19 13:57:10 -07001617 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001618 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001619
John Kessenich140f3df2015-06-26 16:58:36 -06001620 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001621 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1622 if (builtIn != spv::BadValue)
1623 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001624 }
1625 }
1626
1627 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001628 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001629 addDecoration(spvType, TranslateBlockDecoration(type));
1630 if (type.getQualifier().hasStream())
1631 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1632 if (glslangIntermediate->getXfbMode()) {
1633 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001634 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001635 if (type.getQualifier().hasXfbBuffer())
1636 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1637 }
1638 }
1639 break;
1640 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001641 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001642 break;
1643 }
1644
1645 if (type.isMatrix())
1646 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1647 else {
1648 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1649 if (type.getVectorSize() > 1)
1650 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1651 }
1652
1653 if (type.isArray()) {
John Kessenichc9a80832015-09-12 12:17:44 -06001654 // Do all but the outer dimension
1655 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1656 assert(type.getArraySizes()->getDimSize(dim) > 0);
1657 spvType = builder.makeArrayType(spvType, type.getArraySizes()->getDimSize(dim));
1658 }
John Kessenich31ed4832015-09-09 17:51:38 -06001659
John Kessenichc9a80832015-09-12 12:17:44 -06001660 // Do the outer dimension, which might not be known for a runtime-sized array
1661 if (type.isRuntimeSizedArray()) {
1662 spvType = builder.makeRuntimeArray(spvType);
1663 } else {
1664 assert(type.getOuterArraySize() > 0);
1665 spvType = builder.makeArrayType(spvType, type.getOuterArraySize());
1666 }
1667
John Kessenich55e7d112015-11-15 21:33:39 -07001668 // TODO: explicit layout still needs to be done hierarchically for arrays of arrays, which
John Kessenichc9a80832015-09-12 12:17:44 -06001669 // may still require additional "link time" support from the front-end
1670 // for arrays of arrays
John Kessenich55e7d112015-11-15 21:33:39 -07001671
1672 // We need to decorate array strides for types needing explicit layout,
1673 // except for the very top if it is an array of blocks; that array is
1674 // not laid out in memory in a way needing a stride.
1675 if (explicitLayout && type.getBasicType() != glslang::EbtBlock)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001676 builder.addDecoration(spvType, spv::DecorationArrayStride, getArrayStride(type, explicitLayout, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001677 }
1678
1679 return spvType;
1680}
1681
John Kessenichf85e8062015-12-19 13:57:10 -07001682// Decide whether or not this type should be
1683// decorated with offsets and strides, and if so
1684// whether std140 or std430 rules should be applied.
1685glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001686{
John Kessenichf85e8062015-12-19 13:57:10 -07001687 // has to be a block
1688 if (type.getBasicType() != glslang::EbtBlock)
1689 return glslang::ElpNone;
1690
1691 // has to be a uniform or buffer block
1692 if (type.getQualifier().storage != glslang::EvqUniform &&
1693 type.getQualifier().storage != glslang::EvqBuffer)
1694 return glslang::ElpNone;
1695
1696 // return the layout to use
1697 switch (type.getQualifier().layoutPacking) {
1698 case glslang::ElpStd140:
1699 case glslang::ElpStd430:
1700 return type.getQualifier().layoutPacking;
1701 default:
1702 return glslang::ElpNone;
1703 }
John Kessenich31ed4832015-09-09 17:51:38 -06001704}
1705
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001706// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001707int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001708{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001709 int size;
John Kessenich49987892015-12-29 17:11:44 -07001710 int stride;
1711 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001712
1713 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001714}
1715
John Kessenich49987892015-12-29 17:11:44 -07001716// Given a matrix type, or array (of array) of matrixes type, returns the integer stride required for that matrix
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001717// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001718int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001719{
John Kessenich49987892015-12-29 17:11:44 -07001720 glslang::TType elementType;
1721 elementType.shallowCopy(matrixType);
1722 elementType.clearArraySizes();
1723
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001724 int size;
John Kessenich49987892015-12-29 17:11:44 -07001725 int stride;
1726 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1727
1728 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001729}
1730
John Kessenich5e4b1242015-08-06 22:53:06 -06001731// Given a member type of a struct, realign the current offset for it, and compute
1732// the next (not yet aligned) offset for the next member, which will get aligned
1733// on the next call.
1734// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1735// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1736// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001737void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001738 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001739{
1740 // this will get a positive value when deemed necessary
1741 nextOffset = -1;
1742
John Kessenich5e4b1242015-08-06 22:53:06 -06001743 // override anything in currentOffset with user-set offset
1744 if (memberType.getQualifier().hasOffset())
1745 currentOffset = memberType.getQualifier().layoutOffset;
1746
1747 // It could be that current linker usage in glslang updated all the layoutOffset,
1748 // in which case the following code does not matter. But, that's not quite right
1749 // once cross-compilation unit GLSL validation is done, as the original user
1750 // settings are needed in layoutOffset, and then the following will come into play.
1751
John Kessenichf85e8062015-12-19 13:57:10 -07001752 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001753 if (! memberType.getQualifier().hasOffset())
1754 currentOffset = -1;
1755
1756 return;
1757 }
1758
John Kessenichf85e8062015-12-19 13:57:10 -07001759 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001760 if (currentOffset < 0)
1761 currentOffset = 0;
1762
1763 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1764 // but possibly not yet correctly aligned.
1765
1766 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001767 int dummyStride;
1768 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001769 glslang::RoundToPow2(currentOffset, memberAlignment);
1770 nextOffset = currentOffset + memberSize;
1771}
1772
John Kessenich140f3df2015-06-26 16:58:36 -06001773bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1774{
1775 return node->getName() == "main(";
1776}
1777
1778// Make all the functions, skeletally, without actually visiting their bodies.
1779void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1780{
1781 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1782 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1783 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1784 continue;
1785
1786 // We're on a user function. Set up the basic interface for the function now,
1787 // so that it's available to call.
1788 // Translating the body will happen later.
1789 //
1790 // Typically (except for a "const in" parameter), an address will be passed to the
1791 // function. What it is an address of varies:
1792 //
1793 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1794 // so that write needs to be to a copy, hence the address of a copy works.
1795 //
1796 // - "const in" parameters can just be the r-value, as no writes need occur.
1797 //
1798 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1799 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1800
1801 std::vector<spv::Id> paramTypes;
1802 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1803
1804 for (int p = 0; p < (int)parameters.size(); ++p) {
1805 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1806 spv::Id typeId = convertGlslangToSpvType(paramType);
1807 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1808 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1809 else
1810 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1811 paramTypes.push_back(typeId);
1812 }
1813
1814 spv::Block* functionBlock;
1815 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1816 paramTypes, &functionBlock);
1817
1818 // Track function to emit/call later
1819 functionMap[glslFunction->getName().c_str()] = function;
1820
1821 // Set the parameter id's
1822 for (int p = 0; p < (int)parameters.size(); ++p) {
1823 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1824 // give a name too
1825 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1826 }
1827 }
1828}
1829
1830// Process all the initializers, while skipping the functions and link objects
1831void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1832{
1833 builder.setBuildPoint(shaderEntry->getLastBlock());
1834 for (int i = 0; i < (int)initializers.size(); ++i) {
1835 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1836 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1837
1838 // We're on a top-level node that's not a function. Treat as an initializer, whose
1839 // code goes into the beginning of main.
1840 initializer->traverse(this);
1841 }
1842 }
1843}
1844
1845// Process all the functions, while skipping initializers.
1846void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1847{
1848 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1849 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1850 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1851 node->traverse(this);
1852 }
1853}
1854
1855void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1856{
1857 // SPIR-V functions should already be in the functionMap from the prepass
1858 // that called makeFunctions().
1859 spv::Function* function = functionMap[node->getName().c_str()];
1860 spv::Block* functionBlock = function->getEntryBlock();
1861 builder.setBuildPoint(functionBlock);
1862}
1863
Rex Xu04db3f52015-09-16 11:44:02 +08001864void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001865{
Rex Xufc618912015-09-09 16:42:49 +08001866 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001867 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1868 builder.clearAccessChain();
1869 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001870
1871 // Special case l-value operands
1872 bool lvalue = false;
1873 switch (node.getOp()) {
1874 case glslang::EOpImageAtomicAdd:
1875 case glslang::EOpImageAtomicMin:
1876 case glslang::EOpImageAtomicMax:
1877 case glslang::EOpImageAtomicAnd:
1878 case glslang::EOpImageAtomicOr:
1879 case glslang::EOpImageAtomicXor:
1880 case glslang::EOpImageAtomicExchange:
1881 case glslang::EOpImageAtomicCompSwap:
1882 if (i == 0)
1883 lvalue = true;
1884 break;
1885 default:
1886 break;
1887 }
1888
Rex Xu6b86d492015-09-16 17:48:22 +08001889 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001890 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001891 else
Rex Xu30f92582015-09-14 10:38:56 +08001892 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001893 }
1894}
1895
John Kessenichfc51d282015-08-19 13:34:18 -06001896void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001897{
John Kessenichfc51d282015-08-19 13:34:18 -06001898 builder.clearAccessChain();
1899 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001900 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001901}
John Kessenich140f3df2015-06-26 16:58:36 -06001902
John Kessenichfc51d282015-08-19 13:34:18 -06001903spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1904{
Rex Xufc618912015-09-09 16:42:49 +08001905 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001906 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001907 }
1908
John Kessenichfc51d282015-08-19 13:34:18 -06001909 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001910 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1911 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1912 std::vector<spv::Id> arguments;
1913 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001914 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001915 else
1916 translateArguments(*node->getAsUnaryNode(), arguments);
1917 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1918
1919 spv::Builder::TextureParameters params = { };
1920 params.sampler = arguments[0];
1921
Rex Xu04db3f52015-09-16 11:44:02 +08001922 glslang::TCrackedTextureOp cracked;
1923 node->crackTexture(sampler, cracked);
1924
John Kessenichfc51d282015-08-19 13:34:18 -06001925 // Check for queries
1926 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07001927 // a sampled image needs to have the image extracted first
1928 if (builder.isSampledImage(params.sampler))
1929 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06001930 switch (node->getOp()) {
1931 case glslang::EOpImageQuerySize:
1932 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001933 if (arguments.size() > 1) {
1934 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001935 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001936 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001937 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001938 case glslang::EOpImageQuerySamples:
1939 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001940 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001941 case glslang::EOpTextureQueryLod:
1942 params.coords = arguments[1];
1943 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1944 case glslang::EOpTextureQueryLevels:
1945 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1946 default:
1947 assert(0);
1948 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001949 }
John Kessenich140f3df2015-06-26 16:58:36 -06001950 }
1951
Rex Xufc618912015-09-09 16:42:49 +08001952 // Check for image functions other than queries
1953 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001954 std::vector<spv::Id> operands;
1955 auto opIt = arguments.begin();
1956 operands.push_back(*(opIt++));
1957 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001958 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07001959 if (sampler.ms) {
1960 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08001961 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07001962 }
John Kessenich56bab042015-09-16 10:54:31 -06001963 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1964 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08001965 if (sampler.ms) {
1966 operands.push_back(*(opIt + 1));
1967 operands.push_back(spv::ImageOperandsSampleMask);
1968 operands.push_back(*opIt);
1969 } else
1970 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06001971 builder.createNoResultOp(spv::OpImageWrite, operands);
1972 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001973 } else {
1974 // Process image atomic operations
1975
1976 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1977 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001978 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001979
Rex Xufc618912015-09-09 16:42:49 +08001980 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06001981 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08001982
1983 std::vector<spv::Id> operands;
1984 operands.push_back(pointer);
1985 for (; opIt != arguments.end(); ++opIt)
1986 operands.push_back(*opIt);
1987
Rex Xu04db3f52015-09-16 11:44:02 +08001988 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08001989 }
1990 }
1991
1992 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06001993
Rex Xu71519fe2015-11-11 15:35:47 +08001994 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1995
John Kessenichfc51d282015-08-19 13:34:18 -06001996 // check for bias argument
1997 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08001998 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06001999 int nonBiasArgCount = 2;
2000 if (cracked.offset)
2001 ++nonBiasArgCount;
2002 if (cracked.grad)
2003 nonBiasArgCount += 2;
2004
2005 if ((int)arguments.size() > nonBiasArgCount)
2006 bias = true;
2007 }
2008
John Kessenichfc51d282015-08-19 13:34:18 -06002009 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002010
John Kessenichfc51d282015-08-19 13:34:18 -06002011 params.coords = arguments[1];
2012 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002013
2014 // sort out where Dref is coming from
2015 if (sampler.shadow && sampler.dim == glslang::EsdCube && sampler.arrayed)
John Kessenichfc51d282015-08-19 13:34:18 -06002016 params.Dref = arguments[2];
John Kessenich55e7d112015-11-15 21:33:39 -07002017 else if (sampler.shadow && cracked.gather) {
2018 params.Dref = arguments[2];
2019 ++extraArgs;
2020 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002021 std::vector<spv::Id> indexes;
2022 int comp;
2023 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002024 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002025 else
2026 comp = builder.getNumComponents(params.coords) - 1;
2027 indexes.push_back(comp);
2028 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2029 }
2030 if (cracked.lod) {
2031 params.lod = arguments[2];
2032 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002033 } else if (sampler.ms) {
2034 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002035 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002036 }
2037 if (cracked.grad) {
2038 params.gradX = arguments[2 + extraArgs];
2039 params.gradY = arguments[3 + extraArgs];
2040 extraArgs += 2;
2041 }
John Kessenich55e7d112015-11-15 21:33:39 -07002042 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002043 params.offset = arguments[2 + extraArgs];
2044 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002045 } else if (cracked.offsets) {
2046 params.offsets = arguments[2 + extraArgs];
2047 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002048 }
2049 if (bias) {
2050 params.bias = arguments[2 + extraArgs];
2051 ++extraArgs;
2052 }
John Kessenich55e7d112015-11-15 21:33:39 -07002053 if (cracked.gather && ! sampler.shadow) {
2054 // default component is 0, if missing, otherwise an argument
2055 if (2 + extraArgs < (int)arguments.size()) {
2056 params.comp = arguments[2 + extraArgs];
2057 ++extraArgs;
2058 } else {
2059 params.comp = builder.makeIntConstant(0);
2060 }
2061 }
John Kessenichfc51d282015-08-19 13:34:18 -06002062
John Kessenich55e7d112015-11-15 21:33:39 -07002063 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002064}
2065
2066spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2067{
2068 // Grab the function's pointer from the previously created function
2069 spv::Function* function = functionMap[node->getName().c_str()];
2070 if (! function)
2071 return 0;
2072
2073 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2074 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2075
2076 // See comments in makeFunctions() for details about the semantics for parameter passing.
2077 //
2078 // These imply we need a four step process:
2079 // 1. Evaluate the arguments
2080 // 2. Allocate and make copies of in, out, and inout arguments
2081 // 3. Make the call
2082 // 4. Copy back the results
2083
2084 // 1. Evaluate the arguments
2085 std::vector<spv::Builder::AccessChain> lValues;
2086 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002087 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002088 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2089 // build l-value
2090 builder.clearAccessChain();
2091 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002092 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002093 // keep outputs as l-values, evaluate input-only as r-values
2094 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2095 // save l-value
2096 lValues.push_back(builder.getAccessChain());
2097 } else {
2098 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002099 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002100 }
2101 }
2102
2103 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2104 // copy the original into that space.
2105 //
2106 // Also, build up the list of actual arguments to pass in for the call
2107 int lValueCount = 0;
2108 int rValueCount = 0;
2109 std::vector<spv::Id> spvArgs;
2110 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2111 spv::Id arg;
2112 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2113 // need space to hold the copy
2114 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2115 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2116 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2117 // need to copy the input into output space
2118 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002119 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002120 builder.createStore(copy, arg);
2121 }
2122 ++lValueCount;
2123 } else {
2124 arg = rValues[rValueCount];
2125 ++rValueCount;
2126 }
2127 spvArgs.push_back(arg);
2128 }
2129
2130 // 3. Make the call.
2131 spv::Id result = builder.createFunctionCall(function, spvArgs);
2132
2133 // 4. Copy back out an "out" arguments.
2134 lValueCount = 0;
2135 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2136 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2137 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2138 spv::Id copy = builder.createLoad(spvArgs[a]);
2139 builder.setAccessChain(lValues[lValueCount]);
2140 builder.accessChainStore(copy);
2141 }
2142 ++lValueCount;
2143 }
2144 }
2145
2146 return result;
2147}
2148
2149// Translate AST operation to SPV operation, already having SPV-based operands/types.
2150spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2151 spv::Id typeId, spv::Id left, spv::Id right,
2152 glslang::TBasicType typeProxy, bool reduceComparison)
2153{
2154 bool isUnsigned = typeProxy == glslang::EbtUint;
2155 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2156
2157 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002158 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002159 bool comparison = false;
2160
2161 switch (op) {
2162 case glslang::EOpAdd:
2163 case glslang::EOpAddAssign:
2164 if (isFloat)
2165 binOp = spv::OpFAdd;
2166 else
2167 binOp = spv::OpIAdd;
2168 break;
2169 case glslang::EOpSub:
2170 case glslang::EOpSubAssign:
2171 if (isFloat)
2172 binOp = spv::OpFSub;
2173 else
2174 binOp = spv::OpISub;
2175 break;
2176 case glslang::EOpMul:
2177 case glslang::EOpMulAssign:
2178 if (isFloat)
2179 binOp = spv::OpFMul;
2180 else
2181 binOp = spv::OpIMul;
2182 break;
2183 case glslang::EOpVectorTimesScalar:
2184 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002185 if (isFloat) {
2186 if (builder.isVector(right))
2187 std::swap(left, right);
2188 assert(builder.isScalar(right));
2189 needMatchingVectors = false;
2190 binOp = spv::OpVectorTimesScalar;
2191 } else
2192 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002193 break;
2194 case glslang::EOpVectorTimesMatrix:
2195 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002196 binOp = spv::OpVectorTimesMatrix;
2197 break;
2198 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002199 binOp = spv::OpMatrixTimesVector;
2200 break;
2201 case glslang::EOpMatrixTimesScalar:
2202 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002203 binOp = spv::OpMatrixTimesScalar;
2204 break;
2205 case glslang::EOpMatrixTimesMatrix:
2206 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002207 binOp = spv::OpMatrixTimesMatrix;
2208 break;
2209 case glslang::EOpOuterProduct:
2210 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002211 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002212 break;
2213
2214 case glslang::EOpDiv:
2215 case glslang::EOpDivAssign:
2216 if (isFloat)
2217 binOp = spv::OpFDiv;
2218 else if (isUnsigned)
2219 binOp = spv::OpUDiv;
2220 else
2221 binOp = spv::OpSDiv;
2222 break;
2223 case glslang::EOpMod:
2224 case glslang::EOpModAssign:
2225 if (isFloat)
2226 binOp = spv::OpFMod;
2227 else if (isUnsigned)
2228 binOp = spv::OpUMod;
2229 else
2230 binOp = spv::OpSMod;
2231 break;
2232 case glslang::EOpRightShift:
2233 case glslang::EOpRightShiftAssign:
2234 if (isUnsigned)
2235 binOp = spv::OpShiftRightLogical;
2236 else
2237 binOp = spv::OpShiftRightArithmetic;
2238 break;
2239 case glslang::EOpLeftShift:
2240 case glslang::EOpLeftShiftAssign:
2241 binOp = spv::OpShiftLeftLogical;
2242 break;
2243 case glslang::EOpAnd:
2244 case glslang::EOpAndAssign:
2245 binOp = spv::OpBitwiseAnd;
2246 break;
2247 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002248 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002249 binOp = spv::OpLogicalAnd;
2250 break;
2251 case glslang::EOpInclusiveOr:
2252 case glslang::EOpInclusiveOrAssign:
2253 binOp = spv::OpBitwiseOr;
2254 break;
2255 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002256 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002257 binOp = spv::OpLogicalOr;
2258 break;
2259 case glslang::EOpExclusiveOr:
2260 case glslang::EOpExclusiveOrAssign:
2261 binOp = spv::OpBitwiseXor;
2262 break;
2263 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002264 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002265 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002266 break;
2267
2268 case glslang::EOpLessThan:
2269 case glslang::EOpGreaterThan:
2270 case glslang::EOpLessThanEqual:
2271 case glslang::EOpGreaterThanEqual:
2272 case glslang::EOpEqual:
2273 case glslang::EOpNotEqual:
2274 case glslang::EOpVectorEqual:
2275 case glslang::EOpVectorNotEqual:
2276 comparison = true;
2277 break;
2278 default:
2279 break;
2280 }
2281
John Kessenich7c1aa102015-10-15 13:29:11 -06002282 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002283 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002284 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002285 if (builder.isMatrix(left) || builder.isMatrix(right))
2286 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002287
2288 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002289 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002290 builder.promoteScalar(precision, left, right);
2291
2292 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2293 builder.setPrecision(id, precision);
2294
2295 return id;
2296 }
2297
2298 if (! comparison)
2299 return 0;
2300
John Kessenich7c1aa102015-10-15 13:29:11 -06002301 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002302
2303 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2304 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2305
John Kessenich22118352015-12-21 20:54:09 -07002306 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002307 }
2308
2309 switch (op) {
2310 case glslang::EOpLessThan:
2311 if (isFloat)
2312 binOp = spv::OpFOrdLessThan;
2313 else if (isUnsigned)
2314 binOp = spv::OpULessThan;
2315 else
2316 binOp = spv::OpSLessThan;
2317 break;
2318 case glslang::EOpGreaterThan:
2319 if (isFloat)
2320 binOp = spv::OpFOrdGreaterThan;
2321 else if (isUnsigned)
2322 binOp = spv::OpUGreaterThan;
2323 else
2324 binOp = spv::OpSGreaterThan;
2325 break;
2326 case glslang::EOpLessThanEqual:
2327 if (isFloat)
2328 binOp = spv::OpFOrdLessThanEqual;
2329 else if (isUnsigned)
2330 binOp = spv::OpULessThanEqual;
2331 else
2332 binOp = spv::OpSLessThanEqual;
2333 break;
2334 case glslang::EOpGreaterThanEqual:
2335 if (isFloat)
2336 binOp = spv::OpFOrdGreaterThanEqual;
2337 else if (isUnsigned)
2338 binOp = spv::OpUGreaterThanEqual;
2339 else
2340 binOp = spv::OpSGreaterThanEqual;
2341 break;
2342 case glslang::EOpEqual:
2343 case glslang::EOpVectorEqual:
2344 if (isFloat)
2345 binOp = spv::OpFOrdEqual;
2346 else
2347 binOp = spv::OpIEqual;
2348 break;
2349 case glslang::EOpNotEqual:
2350 case glslang::EOpVectorNotEqual:
2351 if (isFloat)
2352 binOp = spv::OpFOrdNotEqual;
2353 else
2354 binOp = spv::OpINotEqual;
2355 break;
2356 default:
2357 break;
2358 }
2359
2360 if (binOp != spv::OpNop) {
2361 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2362 builder.setPrecision(id, precision);
2363
2364 return id;
2365 }
2366
2367 return 0;
2368}
2369
John Kessenich04bb8a02015-12-12 12:28:14 -07002370//
2371// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2372// These can be any of:
2373//
2374// matrix * scalar
2375// scalar * matrix
2376// matrix * matrix linear algebraic
2377// matrix * vector
2378// vector * matrix
2379// matrix * matrix componentwise
2380// matrix op matrix op in {+, -, /}
2381// matrix op scalar op in {+, -, /}
2382// scalar op matrix op in {+, -, /}
2383//
2384spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2385{
2386 bool firstClass = true;
2387
2388 // First, handle first-class matrix operations (* and matrix/scalar)
2389 switch (op) {
2390 case spv::OpFDiv:
2391 if (builder.isMatrix(left) && builder.isScalar(right)) {
2392 // turn matrix / scalar into a multiply...
2393 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2394 op = spv::OpMatrixTimesScalar;
2395 } else
2396 firstClass = false;
2397 break;
2398 case spv::OpMatrixTimesScalar:
2399 if (builder.isMatrix(right))
2400 std::swap(left, right);
2401 assert(builder.isScalar(right));
2402 break;
2403 case spv::OpVectorTimesMatrix:
2404 assert(builder.isVector(left));
2405 assert(builder.isMatrix(right));
2406 break;
2407 case spv::OpMatrixTimesVector:
2408 assert(builder.isMatrix(left));
2409 assert(builder.isVector(right));
2410 break;
2411 case spv::OpMatrixTimesMatrix:
2412 assert(builder.isMatrix(left));
2413 assert(builder.isMatrix(right));
2414 break;
2415 default:
2416 firstClass = false;
2417 break;
2418 }
2419
2420 if (firstClass) {
2421 spv::Id id = builder.createBinOp(op, typeId, left, right);
2422 builder.setPrecision(id, precision);
2423
2424 return id;
2425 }
2426
2427 // Handle component-wise +, -, *, and / for all combinations of type.
2428 // The result type of all of them is the same type as the (a) matrix operand.
2429 // The algorithm is to:
2430 // - break the matrix(es) into vectors
2431 // - smear any scalar to a vector
2432 // - do vector operations
2433 // - make a matrix out the vector results
2434 switch (op) {
2435 case spv::OpFAdd:
2436 case spv::OpFSub:
2437 case spv::OpFDiv:
2438 case spv::OpFMul:
2439 {
2440 // one time set up...
2441 bool leftMat = builder.isMatrix(left);
2442 bool rightMat = builder.isMatrix(right);
2443 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2444 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2445 spv::Id scalarType = builder.getScalarTypeId(typeId);
2446 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2447 std::vector<spv::Id> results;
2448 spv::Id smearVec = spv::NoResult;
2449 if (builder.isScalar(left))
2450 smearVec = builder.smearScalar(precision, left, vecType);
2451 else if (builder.isScalar(right))
2452 smearVec = builder.smearScalar(precision, right, vecType);
2453
2454 // do each vector op
2455 for (unsigned int c = 0; c < numCols; ++c) {
2456 std::vector<unsigned int> indexes;
2457 indexes.push_back(c);
2458 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2459 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2460 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2461 builder.setPrecision(results.back(), precision);
2462 }
2463
2464 // put the pieces together
2465 spv::Id id = builder.createCompositeConstruct(typeId, results);
2466 builder.setPrecision(id, precision);
2467 return id;
2468 }
2469 default:
2470 assert(0);
2471 return spv::NoResult;
2472 }
2473}
2474
Rex Xu04db3f52015-09-16 11:44:02 +08002475spv::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 -06002476{
2477 spv::Op unaryOp = spv::OpNop;
2478 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002479 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002480 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002481
2482 switch (op) {
2483 case glslang::EOpNegative:
2484 if (isFloat)
2485 unaryOp = spv::OpFNegate;
2486 else
2487 unaryOp = spv::OpSNegate;
2488 break;
2489
2490 case glslang::EOpLogicalNot:
2491 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002492 unaryOp = spv::OpLogicalNot;
2493 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002494 case glslang::EOpBitwiseNot:
2495 unaryOp = spv::OpNot;
2496 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002497
John Kessenich140f3df2015-06-26 16:58:36 -06002498 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002499 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002500 break;
2501 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002502 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002503 break;
2504 case glslang::EOpTranspose:
2505 unaryOp = spv::OpTranspose;
2506 break;
2507
2508 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002509 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002510 break;
2511 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002512 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002513 break;
2514 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002515 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002516 break;
2517 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002518 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002519 break;
2520 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002521 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002522 break;
2523 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002524 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002525 break;
2526 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002527 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002528 break;
2529 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002530 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002531 break;
2532
2533 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002534 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002535 break;
2536 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002537 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002538 break;
2539 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002540 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002541 break;
2542 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002543 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002544 break;
2545 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002546 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002547 break;
2548 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002549 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002550 break;
2551
2552 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002553 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002554 break;
2555 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002556 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002557 break;
2558
2559 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002560 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002561 break;
2562 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002563 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002564 break;
2565 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002566 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002567 break;
2568 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002569 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002570 break;
2571 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002572 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002573 break;
2574 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002575 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002576 break;
2577
2578 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002579 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002580 break;
2581 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002582 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002583 break;
2584 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002585 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002586 break;
2587 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002588 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002589 break;
2590 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002591 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002592 break;
2593 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002594 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002595 break;
2596
2597 case glslang::EOpIsNan:
2598 unaryOp = spv::OpIsNan;
2599 break;
2600 case glslang::EOpIsInf:
2601 unaryOp = spv::OpIsInf;
2602 break;
2603
Rex Xucbc426e2015-12-15 16:03:10 +08002604 case glslang::EOpFloatBitsToInt:
2605 case glslang::EOpFloatBitsToUint:
2606 case glslang::EOpIntBitsToFloat:
2607 case glslang::EOpUintBitsToFloat:
2608 unaryOp = spv::OpBitcast;
2609 break;
2610
John Kessenich140f3df2015-06-26 16:58:36 -06002611 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002612 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002613 break;
2614 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002615 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002616 break;
2617 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002618 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002619 break;
2620 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002621 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002622 break;
2623 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002624 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002625 break;
2626 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002627 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002628 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002629 case glslang::EOpPackSnorm4x8:
2630 libCall = spv::GLSLstd450PackSnorm4x8;
2631 break;
2632 case glslang::EOpUnpackSnorm4x8:
2633 libCall = spv::GLSLstd450UnpackSnorm4x8;
2634 break;
2635 case glslang::EOpPackUnorm4x8:
2636 libCall = spv::GLSLstd450PackUnorm4x8;
2637 break;
2638 case glslang::EOpUnpackUnorm4x8:
2639 libCall = spv::GLSLstd450UnpackUnorm4x8;
2640 break;
2641 case glslang::EOpPackDouble2x32:
2642 libCall = spv::GLSLstd450PackDouble2x32;
2643 break;
2644 case glslang::EOpUnpackDouble2x32:
2645 libCall = spv::GLSLstd450UnpackDouble2x32;
2646 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002647
2648 case glslang::EOpDPdx:
2649 unaryOp = spv::OpDPdx;
2650 break;
2651 case glslang::EOpDPdy:
2652 unaryOp = spv::OpDPdy;
2653 break;
2654 case glslang::EOpFwidth:
2655 unaryOp = spv::OpFwidth;
2656 break;
2657 case glslang::EOpDPdxFine:
2658 unaryOp = spv::OpDPdxFine;
2659 break;
2660 case glslang::EOpDPdyFine:
2661 unaryOp = spv::OpDPdyFine;
2662 break;
2663 case glslang::EOpFwidthFine:
2664 unaryOp = spv::OpFwidthFine;
2665 break;
2666 case glslang::EOpDPdxCoarse:
2667 unaryOp = spv::OpDPdxCoarse;
2668 break;
2669 case glslang::EOpDPdyCoarse:
2670 unaryOp = spv::OpDPdyCoarse;
2671 break;
2672 case glslang::EOpFwidthCoarse:
2673 unaryOp = spv::OpFwidthCoarse;
2674 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002675 case glslang::EOpInterpolateAtCentroid:
2676 libCall = spv::GLSLstd450InterpolateAtCentroid;
2677 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002678 case glslang::EOpAny:
2679 unaryOp = spv::OpAny;
2680 break;
2681 case glslang::EOpAll:
2682 unaryOp = spv::OpAll;
2683 break;
2684
2685 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002686 if (isFloat)
2687 libCall = spv::GLSLstd450FAbs;
2688 else
2689 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002690 break;
2691 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002692 if (isFloat)
2693 libCall = spv::GLSLstd450FSign;
2694 else
2695 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002696 break;
2697
John Kessenichfc51d282015-08-19 13:34:18 -06002698 case glslang::EOpAtomicCounterIncrement:
2699 case glslang::EOpAtomicCounterDecrement:
2700 case glslang::EOpAtomicCounter:
2701 {
2702 // Handle all of the atomics in one place, in createAtomicOperation()
2703 std::vector<spv::Id> operands;
2704 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002705 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002706 }
2707
2708 case glslang::EOpImageLoad:
2709 unaryOp = spv::OpImageRead;
2710 break;
2711
2712 case glslang::EOpBitFieldReverse:
2713 unaryOp = spv::OpBitReverse;
2714 break;
2715 case glslang::EOpBitCount:
2716 unaryOp = spv::OpBitCount;
2717 break;
2718 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002719 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002720 break;
2721 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002722 if (isUnsigned)
2723 libCall = spv::GLSLstd450FindUMsb;
2724 else
2725 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002726 break;
2727
John Kessenich140f3df2015-06-26 16:58:36 -06002728 default:
2729 return 0;
2730 }
2731
2732 spv::Id id;
2733 if (libCall >= 0) {
2734 std::vector<spv::Id> args;
2735 args.push_back(operand);
2736 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2737 } else
2738 id = builder.createUnaryOp(unaryOp, typeId, operand);
2739
2740 builder.setPrecision(id, precision);
2741
2742 return id;
2743}
2744
2745spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2746{
2747 spv::Op convOp = spv::OpNop;
2748 spv::Id zero = 0;
2749 spv::Id one = 0;
2750
2751 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2752
2753 switch (op) {
2754 case glslang::EOpConvIntToBool:
2755 case glslang::EOpConvUintToBool:
2756 zero = builder.makeUintConstant(0);
2757 zero = makeSmearedConstant(zero, vectorSize);
2758 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2759
2760 case glslang::EOpConvFloatToBool:
2761 zero = builder.makeFloatConstant(0.0F);
2762 zero = makeSmearedConstant(zero, vectorSize);
2763 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2764
2765 case glslang::EOpConvDoubleToBool:
2766 zero = builder.makeDoubleConstant(0.0);
2767 zero = makeSmearedConstant(zero, vectorSize);
2768 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2769
2770 case glslang::EOpConvBoolToFloat:
2771 convOp = spv::OpSelect;
2772 zero = builder.makeFloatConstant(0.0);
2773 one = builder.makeFloatConstant(1.0);
2774 break;
2775 case glslang::EOpConvBoolToDouble:
2776 convOp = spv::OpSelect;
2777 zero = builder.makeDoubleConstant(0.0);
2778 one = builder.makeDoubleConstant(1.0);
2779 break;
2780 case glslang::EOpConvBoolToInt:
2781 zero = builder.makeIntConstant(0);
2782 one = builder.makeIntConstant(1);
2783 convOp = spv::OpSelect;
2784 break;
2785 case glslang::EOpConvBoolToUint:
2786 zero = builder.makeUintConstant(0);
2787 one = builder.makeUintConstant(1);
2788 convOp = spv::OpSelect;
2789 break;
2790
2791 case glslang::EOpConvIntToFloat:
2792 case glslang::EOpConvIntToDouble:
2793 convOp = spv::OpConvertSToF;
2794 break;
2795
2796 case glslang::EOpConvUintToFloat:
2797 case glslang::EOpConvUintToDouble:
2798 convOp = spv::OpConvertUToF;
2799 break;
2800
2801 case glslang::EOpConvDoubleToFloat:
2802 case glslang::EOpConvFloatToDouble:
2803 convOp = spv::OpFConvert;
2804 break;
2805
2806 case glslang::EOpConvFloatToInt:
2807 case glslang::EOpConvDoubleToInt:
2808 convOp = spv::OpConvertFToS;
2809 break;
2810
2811 case glslang::EOpConvUintToInt:
2812 case glslang::EOpConvIntToUint:
2813 convOp = spv::OpBitcast;
2814 break;
2815
2816 case glslang::EOpConvFloatToUint:
2817 case glslang::EOpConvDoubleToUint:
2818 convOp = spv::OpConvertFToU;
2819 break;
2820 default:
2821 break;
2822 }
2823
2824 spv::Id result = 0;
2825 if (convOp == spv::OpNop)
2826 return result;
2827
2828 if (convOp == spv::OpSelect) {
2829 zero = makeSmearedConstant(zero, vectorSize);
2830 one = makeSmearedConstant(one, vectorSize);
2831 result = builder.createTriOp(convOp, destType, operand, one, zero);
2832 } else
2833 result = builder.createUnaryOp(convOp, destType, operand);
2834
2835 builder.setPrecision(result, precision);
2836
2837 return result;
2838}
2839
2840spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2841{
2842 if (vectorSize == 0)
2843 return constant;
2844
2845 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2846 std::vector<spv::Id> components;
2847 for (int c = 0; c < vectorSize; ++c)
2848 components.push_back(constant);
2849 return builder.makeCompositeConstant(vectorTypeId, components);
2850}
2851
John Kessenich426394d2015-07-23 10:22:48 -06002852// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002853spv::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 -06002854{
2855 spv::Op opCode = spv::OpNop;
2856
2857 switch (op) {
2858 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002859 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002860 opCode = spv::OpAtomicIAdd;
2861 break;
2862 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002863 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002864 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002865 break;
2866 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002867 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002868 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002869 break;
2870 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002871 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002872 opCode = spv::OpAtomicAnd;
2873 break;
2874 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002875 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002876 opCode = spv::OpAtomicOr;
2877 break;
2878 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002879 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002880 opCode = spv::OpAtomicXor;
2881 break;
2882 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002883 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002884 opCode = spv::OpAtomicExchange;
2885 break;
2886 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002887 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002888 opCode = spv::OpAtomicCompareExchange;
2889 break;
2890 case glslang::EOpAtomicCounterIncrement:
2891 opCode = spv::OpAtomicIIncrement;
2892 break;
2893 case glslang::EOpAtomicCounterDecrement:
2894 opCode = spv::OpAtomicIDecrement;
2895 break;
2896 case glslang::EOpAtomicCounter:
2897 opCode = spv::OpAtomicLoad;
2898 break;
2899 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002900 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06002901 break;
2902 }
2903
2904 // Sort out the operands
2905 // - mapping from glslang -> SPV
2906 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002907 // - compare-exchange swaps the value and comparator
2908 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002909 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2910 auto opIt = operands.begin(); // walk the glslang operands
2911 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002912 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2913 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2914 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002915 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2916 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002917 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002918 spvAtomicOperands.push_back(*(opIt + 1));
2919 spvAtomicOperands.push_back(*opIt);
2920 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002921 }
John Kessenich426394d2015-07-23 10:22:48 -06002922
John Kessenich3e60a6f2015-09-14 22:45:16 -06002923 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002924 for (; opIt != operands.end(); ++opIt)
2925 spvAtomicOperands.push_back(*opIt);
2926
2927 return builder.createOp(opCode, typeId, spvAtomicOperands);
2928}
2929
John Kessenich5e4b1242015-08-06 22:53:06 -06002930spv::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 -06002931{
John Kessenich5e4b1242015-08-06 22:53:06 -06002932 bool isUnsigned = typeProxy == glslang::EbtUint;
2933 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2934
John Kessenich140f3df2015-06-26 16:58:36 -06002935 spv::Op opCode = spv::OpNop;
2936 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002937 int consumedOperands = operands.size();
2938 spv::Id typeId0 = 0;
2939 if (consumedOperands > 0)
2940 typeId0 = builder.getTypeId(operands[0]);
2941 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002942
2943 switch (op) {
2944 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002945 if (isFloat)
2946 libCall = spv::GLSLstd450FMin;
2947 else if (isUnsigned)
2948 libCall = spv::GLSLstd450UMin;
2949 else
2950 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002951 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002952 break;
2953 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002954 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002955 break;
2956 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002957 if (isFloat)
2958 libCall = spv::GLSLstd450FMax;
2959 else if (isUnsigned)
2960 libCall = spv::GLSLstd450UMax;
2961 else
2962 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002963 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002964 break;
2965 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002966 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002967 break;
2968 case glslang::EOpDot:
2969 opCode = spv::OpDot;
2970 break;
2971 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002972 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002973 break;
2974
2975 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002976 if (isFloat)
2977 libCall = spv::GLSLstd450FClamp;
2978 else if (isUnsigned)
2979 libCall = spv::GLSLstd450UClamp;
2980 else
2981 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002982 builder.promoteScalar(precision, operands.front(), operands[1]);
2983 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06002984 break;
2985 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07002986 if (isFloat)
2987 libCall = spv::GLSLstd450FMix;
2988 else
2989 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002990 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002991 break;
2992 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002993 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002994 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002995 break;
2996 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06002997 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002998 builder.promoteScalar(precision, operands[0], operands[2]);
2999 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003000 break;
3001
3002 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003003 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003004 break;
3005 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003006 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 break;
3008 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003009 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003010 break;
3011 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003012 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003013 break;
3014 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003015 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003016 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003017 case glslang::EOpInterpolateAtSample:
3018 libCall = spv::GLSLstd450InterpolateAtSample;
3019 break;
3020 case glslang::EOpInterpolateAtOffset:
3021 libCall = spv::GLSLstd450InterpolateAtOffset;
3022 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003023 case glslang::EOpAddCarry:
3024 opCode = spv::OpIAddCarry;
3025 typeId = builder.makeStructResultType(typeId0, typeId0);
3026 consumedOperands = 2;
3027 break;
3028 case glslang::EOpSubBorrow:
3029 opCode = spv::OpISubBorrow;
3030 typeId = builder.makeStructResultType(typeId0, typeId0);
3031 consumedOperands = 2;
3032 break;
3033 case glslang::EOpUMulExtended:
3034 opCode = spv::OpUMulExtended;
3035 typeId = builder.makeStructResultType(typeId0, typeId0);
3036 consumedOperands = 2;
3037 break;
3038 case glslang::EOpIMulExtended:
3039 opCode = spv::OpSMulExtended;
3040 typeId = builder.makeStructResultType(typeId0, typeId0);
3041 consumedOperands = 2;
3042 break;
3043 case glslang::EOpBitfieldExtract:
3044 if (isUnsigned)
3045 opCode = spv::OpBitFieldUExtract;
3046 else
3047 opCode = spv::OpBitFieldSExtract;
3048 break;
3049 case glslang::EOpBitfieldInsert:
3050 opCode = spv::OpBitFieldInsert;
3051 break;
3052
3053 case glslang::EOpFma:
3054 libCall = spv::GLSLstd450Fma;
3055 break;
3056 case glslang::EOpFrexp:
3057 libCall = spv::GLSLstd450FrexpStruct;
3058 if (builder.getNumComponents(operands[0]) == 1)
3059 frexpIntType = builder.makeIntegerType(32, true);
3060 else
3061 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3062 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3063 consumedOperands = 1;
3064 break;
3065 case glslang::EOpLdexp:
3066 libCall = spv::GLSLstd450Ldexp;
3067 break;
3068
John Kessenich140f3df2015-06-26 16:58:36 -06003069 default:
3070 return 0;
3071 }
3072
3073 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003074 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003075 // Use an extended instruction from the standard library.
3076 // Construct the call arguments, without modifying the original operands vector.
3077 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3078 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
3079 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003080 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003081 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003082 case 0:
3083 // should all be handled by visitAggregate and createNoArgOperation
3084 assert(0);
3085 return 0;
3086 case 1:
3087 // should all be handled by createUnaryOperation
3088 assert(0);
3089 return 0;
3090 case 2:
3091 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3092 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003093 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003094 // anything 3 or over doesn't have l-value operands, so all should be consumed
3095 assert(consumedOperands == operands.size());
3096 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003097 break;
3098 }
3099 }
3100
John Kessenich55e7d112015-11-15 21:33:39 -07003101 // Decode the return types that were structures
3102 switch (op) {
3103 case glslang::EOpAddCarry:
3104 case glslang::EOpSubBorrow:
3105 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3106 id = builder.createCompositeExtract(id, typeId0, 0);
3107 break;
3108 case glslang::EOpUMulExtended:
3109 case glslang::EOpIMulExtended:
3110 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3111 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3112 break;
3113 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003114 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003115 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3116 id = builder.createCompositeExtract(id, typeId0, 0);
3117 break;
3118 default:
3119 break;
3120 }
3121
John Kessenich140f3df2015-06-26 16:58:36 -06003122 builder.setPrecision(id, precision);
3123
3124 return id;
3125}
3126
3127// Intrinsics with no arguments, no return value, and no precision.
3128spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3129{
3130 // TODO: get the barrier operands correct
3131
3132 switch (op) {
3133 case glslang::EOpEmitVertex:
3134 builder.createNoResultOp(spv::OpEmitVertex);
3135 return 0;
3136 case glslang::EOpEndPrimitive:
3137 builder.createNoResultOp(spv::OpEndPrimitive);
3138 return 0;
3139 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003140 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3141 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003142 return 0;
3143 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003144 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003145 return 0;
3146 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003147 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003148 return 0;
3149 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003150 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003151 return 0;
3152 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003153 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003154 return 0;
3155 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003156 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003157 return 0;
3158 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003159 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003160 return 0;
3161 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003162 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003163 return 0;
3164 }
3165}
3166
3167spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3168{
John Kessenich2f273362015-07-18 22:34:27 -06003169 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003170 spv::Id id;
3171 if (symbolValues.end() != iter) {
3172 id = iter->second;
3173 return id;
3174 }
3175
3176 // it was not found, create it
3177 id = createSpvVariable(symbol);
3178 symbolValues[symbol->getId()] = id;
3179
3180 if (! symbol->getType().isStruct()) {
3181 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003182 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003183 if (symbol->getQualifier().hasLocation())
3184 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3185 if (symbol->getQualifier().hasIndex())
3186 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3187 if (symbol->getQualifier().hasComponent())
3188 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3189 if (glslangIntermediate->getXfbMode()) {
3190 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003191 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003192 if (symbol->getQualifier().hasXfbBuffer())
3193 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3194 if (symbol->getQualifier().hasXfbOffset())
3195 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3196 }
3197 }
3198
John Kesseniche0b6cad2015-12-24 10:30:13 -07003199 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003200 if (symbol->getQualifier().hasStream())
3201 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3202 if (symbol->getQualifier().hasSet())
3203 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3204 if (symbol->getQualifier().hasBinding())
3205 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3206 if (glslangIntermediate->getXfbMode()) {
3207 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003208 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003209 if (symbol->getQualifier().hasXfbBuffer())
3210 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3211 }
3212
3213 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003214 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003215 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003216 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003217
John Kessenich140f3df2015-06-26 16:58:36 -06003218 return id;
3219}
3220
John Kessenich55e7d112015-11-15 21:33:39 -07003221// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003222void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3223{
3224 if (dec != spv::BadValue)
3225 builder.addDecoration(id, dec);
3226}
3227
John Kessenich55e7d112015-11-15 21:33:39 -07003228// If 'dec' is valid, add a one-operand decoration to an object
3229void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3230{
3231 if (dec != spv::BadValue)
3232 builder.addDecoration(id, dec, value);
3233}
3234
3235// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003236void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3237{
3238 if (dec != spv::BadValue)
3239 builder.addMemberDecoration(id, (unsigned)member, dec);
3240}
3241
John Kessenich55e7d112015-11-15 21:33:39 -07003242// Make a full tree of instructions to build a SPIR-V specialization constant,
3243// or regularly constant if possible.
3244//
3245// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3246//
3247// Recursively walk the nodes. The nodes form a tree whose leaves are
3248// regular constants, which themselves are trees that createSpvConstant()
3249// recursively walks. So, this function walks the "top" of the tree:
3250// - emit specialization constant-building instructions for specConstant
3251// - when running into a non-spec-constant, switch to createSpvConstant()
3252spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3253{
3254 assert(node.getQualifier().storage == glslang::EvqConst);
3255
3256 // hand off to the non-spec-constant path
3257 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3258 int nextConst = 0;
3259 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3260}
3261
John Kessenich140f3df2015-06-26 16:58:36 -06003262// Use 'consts' as the flattened glslang source of scalar constants to recursively
3263// build the aggregate SPIR-V constant.
3264//
3265// If there are not enough elements present in 'consts', 0 will be substituted;
3266// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3267//
John Kessenich55e7d112015-11-15 21:33:39 -07003268spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003269{
3270 // vector of constants for SPIR-V
3271 std::vector<spv::Id> spvConsts;
3272
3273 // Type is used for struct and array constants
3274 spv::Id typeId = convertGlslangToSpvType(glslangType);
3275
3276 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003277 glslang::TType elementType(glslangType, 0);
3278 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003279 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003280 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003281 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003282 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003283 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003284 } else if (glslangType.getStruct()) {
3285 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3286 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003287 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003288 } else if (glslangType.isVector()) {
3289 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3290 bool zero = nextConst >= consts.size();
3291 switch (glslangType.getBasicType()) {
3292 case glslang::EbtInt:
3293 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3294 break;
3295 case glslang::EbtUint:
3296 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3297 break;
3298 case glslang::EbtFloat:
3299 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3300 break;
3301 case glslang::EbtDouble:
3302 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3303 break;
3304 case glslang::EbtBool:
3305 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3306 break;
3307 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003308 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003309 break;
3310 }
3311 ++nextConst;
3312 }
3313 } else {
3314 // we have a non-aggregate (scalar) constant
3315 bool zero = nextConst >= consts.size();
3316 spv::Id scalar = 0;
3317 switch (glslangType.getBasicType()) {
3318 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003319 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003320 break;
3321 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003322 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003323 break;
3324 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003325 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003326 break;
3327 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003328 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003329 break;
3330 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003331 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003332 break;
3333 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003334 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003335 break;
3336 }
3337 ++nextConst;
3338 return scalar;
3339 }
3340
3341 return builder.makeCompositeConstant(typeId, spvConsts);
3342}
3343
John Kessenich7c1aa102015-10-15 13:29:11 -06003344// Return true if the node is a constant or symbol whose reading has no
3345// non-trivial observable cost or effect.
3346bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3347{
3348 // don't know what this is
3349 if (node == nullptr)
3350 return false;
3351
3352 // a constant is safe
3353 if (node->getAsConstantUnion() != nullptr)
3354 return true;
3355
3356 // not a symbol means non-trivial
3357 if (node->getAsSymbolNode() == nullptr)
3358 return false;
3359
3360 // a symbol, depends on what's being read
3361 switch (node->getType().getQualifier().storage) {
3362 case glslang::EvqTemporary:
3363 case glslang::EvqGlobal:
3364 case glslang::EvqIn:
3365 case glslang::EvqInOut:
3366 case glslang::EvqConst:
3367 case glslang::EvqConstReadOnly:
3368 case glslang::EvqUniform:
3369 return true;
3370 default:
3371 return false;
3372 }
3373}
3374
3375// A node is trivial if it is a single operation with no side effects.
3376// Error on the side of saying non-trivial.
3377// Return true if trivial.
3378bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3379{
3380 if (node == nullptr)
3381 return false;
3382
3383 // symbols and constants are trivial
3384 if (isTrivialLeaf(node))
3385 return true;
3386
3387 // otherwise, it needs to be a simple operation or one or two leaf nodes
3388
3389 // not a simple operation
3390 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3391 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3392 if (binaryNode == nullptr && unaryNode == nullptr)
3393 return false;
3394
3395 // not on leaf nodes
3396 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3397 return false;
3398
3399 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3400 return false;
3401 }
3402
3403 switch (node->getAsOperator()->getOp()) {
3404 case glslang::EOpLogicalNot:
3405 case glslang::EOpConvIntToBool:
3406 case glslang::EOpConvUintToBool:
3407 case glslang::EOpConvFloatToBool:
3408 case glslang::EOpConvDoubleToBool:
3409 case glslang::EOpEqual:
3410 case glslang::EOpNotEqual:
3411 case glslang::EOpLessThan:
3412 case glslang::EOpGreaterThan:
3413 case glslang::EOpLessThanEqual:
3414 case glslang::EOpGreaterThanEqual:
3415 case glslang::EOpIndexDirect:
3416 case glslang::EOpIndexDirectStruct:
3417 case glslang::EOpLogicalXor:
3418 case glslang::EOpAny:
3419 case glslang::EOpAll:
3420 return true;
3421 default:
3422 return false;
3423 }
3424}
3425
3426// Emit short-circuiting code, where 'right' is never evaluated unless
3427// the left side is true (for &&) or false (for ||).
3428spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3429{
3430 spv::Id boolTypeId = builder.makeBoolType();
3431
3432 // emit left operand
3433 builder.clearAccessChain();
3434 left.traverse(this);
3435 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3436
3437 // Operands to accumulate OpPhi operands
3438 std::vector<spv::Id> phiOperands;
3439 // accumulate left operand's phi information
3440 phiOperands.push_back(leftId);
3441 phiOperands.push_back(builder.getBuildPoint()->getId());
3442
3443 // Make the two kinds of operation symmetric with a "!"
3444 // || => emit "if (! left) result = right"
3445 // && => emit "if ( left) result = right"
3446 //
3447 // TODO: this runtime "not" for || could be avoided by adding functionality
3448 // to 'builder' to have an "else" without an "then"
3449 if (op == glslang::EOpLogicalOr)
3450 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3451
3452 // make an "if" based on the left value
3453 spv::Builder::If ifBuilder(leftId, builder);
3454
3455 // emit right operand as the "then" part of the "if"
3456 builder.clearAccessChain();
3457 right.traverse(this);
3458 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3459
3460 // accumulate left operand's phi information
3461 phiOperands.push_back(rightId);
3462 phiOperands.push_back(builder.getBuildPoint()->getId());
3463
3464 // finish the "if"
3465 ifBuilder.makeEndIf();
3466
3467 // phi together the two results
3468 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3469}
3470
John Kessenich140f3df2015-06-26 16:58:36 -06003471}; // end anonymous namespace
3472
3473namespace glslang {
3474
John Kessenich68d78fd2015-07-12 19:28:10 -06003475void GetSpirvVersion(std::string& version)
3476{
John Kessenich9e55f632015-07-15 10:03:39 -06003477 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003478 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003479 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003480 version = buf;
3481}
3482
John Kessenich140f3df2015-06-26 16:58:36 -06003483// Write SPIR-V out to a binary file
3484void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3485{
3486 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003487 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003488 for (int i = 0; i < (int)spirv.size(); ++i) {
3489 unsigned int word = spirv[i];
3490 out.write((const char*)&word, 4);
3491 }
3492 out.close();
3493}
3494
3495//
3496// Set up the glslang traversal
3497//
3498void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3499{
3500 TIntermNode* root = intermediate.getTreeRoot();
3501
3502 if (root == 0)
3503 return;
3504
3505 glslang::GetThreadPoolAllocator().push();
3506
3507 TGlslangToSpvTraverser it(&intermediate);
3508
3509 root->traverse(&it);
3510
3511 it.dumpSpv(spirv);
3512
3513 glslang::GetThreadPoolAllocator().pop();
3514}
3515
3516}; // end namespace glslang