blob: e468705c154fb91ae8cf47afa8000b13773bf7dc [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 Kessenichc9e0a422015-12-29 21:27:24 -07001654 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1655
John Kessenichc9a80832015-09-12 12:17:44 -06001656 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001657 if (type.getArraySizes()->getNumDims() > 1) {
1658 if (explicitLayout != glslang::ElpNone) {
1659 // Use a dummy glslang type for querying internal strides of
1660 // arrays of arrays, but using just a one-dimensional array.
1661 glslang::TType simpleArrayType(type, 0); // deference type of the array
1662 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1663 simpleArrayType.getArraySizes().dereference();
1664
1665 // Will compute the higher-order strides here, rather than making a whole
1666 // pile of types and doing repetitive recursion on their contents.
1667 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1668 }
1669 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1670 int size = type.getArraySizes()->getDimSize(dim);
1671 assert(size > 0);
1672 spvType = builder.makeArrayType(spvType, size, stride);
1673 if (stride > 0)
1674 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1675 stride *= size;
1676 }
1677 } else {
1678 // single-dimensional array, and don't yet have stride
1679
1680 // We need to decorate array strides for types needing explicit layout,
1681 // except for the very top if it is an array of blocks; that array is
1682 // not laid out in memory in a way needing a stride.
1683 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1684 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001685 }
John Kessenich31ed4832015-09-09 17:51:38 -06001686
John Kessenichc9a80832015-09-12 12:17:44 -06001687 // Do the outer dimension, which might not be known for a runtime-sized array
1688 if (type.isRuntimeSizedArray()) {
1689 spvType = builder.makeRuntimeArray(spvType);
1690 } else {
1691 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001692 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001693 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001694 if (stride > 0)
1695 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001696 }
1697
1698 return spvType;
1699}
1700
John Kessenichf85e8062015-12-19 13:57:10 -07001701// Decide whether or not this type should be
1702// decorated with offsets and strides, and if so
1703// whether std140 or std430 rules should be applied.
1704glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001705{
John Kessenichf85e8062015-12-19 13:57:10 -07001706 // has to be a block
1707 if (type.getBasicType() != glslang::EbtBlock)
1708 return glslang::ElpNone;
1709
1710 // has to be a uniform or buffer block
1711 if (type.getQualifier().storage != glslang::EvqUniform &&
1712 type.getQualifier().storage != glslang::EvqBuffer)
1713 return glslang::ElpNone;
1714
1715 // return the layout to use
1716 switch (type.getQualifier().layoutPacking) {
1717 case glslang::ElpStd140:
1718 case glslang::ElpStd430:
1719 return type.getQualifier().layoutPacking;
1720 default:
1721 return glslang::ElpNone;
1722 }
John Kessenich31ed4832015-09-09 17:51:38 -06001723}
1724
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001725// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001726int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001727{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001728 int size;
John Kessenich49987892015-12-29 17:11:44 -07001729 int stride;
1730 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001731
1732 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001733}
1734
John Kessenich49987892015-12-29 17:11:44 -07001735// 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 -07001736// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001737int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001738{
John Kessenich49987892015-12-29 17:11:44 -07001739 glslang::TType elementType;
1740 elementType.shallowCopy(matrixType);
1741 elementType.clearArraySizes();
1742
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001743 int size;
John Kessenich49987892015-12-29 17:11:44 -07001744 int stride;
1745 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1746
1747 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001748}
1749
John Kessenich5e4b1242015-08-06 22:53:06 -06001750// Given a member type of a struct, realign the current offset for it, and compute
1751// the next (not yet aligned) offset for the next member, which will get aligned
1752// on the next call.
1753// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1754// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1755// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001756void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001757 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001758{
1759 // this will get a positive value when deemed necessary
1760 nextOffset = -1;
1761
John Kessenich5e4b1242015-08-06 22:53:06 -06001762 // override anything in currentOffset with user-set offset
1763 if (memberType.getQualifier().hasOffset())
1764 currentOffset = memberType.getQualifier().layoutOffset;
1765
1766 // It could be that current linker usage in glslang updated all the layoutOffset,
1767 // in which case the following code does not matter. But, that's not quite right
1768 // once cross-compilation unit GLSL validation is done, as the original user
1769 // settings are needed in layoutOffset, and then the following will come into play.
1770
John Kessenichf85e8062015-12-19 13:57:10 -07001771 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001772 if (! memberType.getQualifier().hasOffset())
1773 currentOffset = -1;
1774
1775 return;
1776 }
1777
John Kessenichf85e8062015-12-19 13:57:10 -07001778 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001779 if (currentOffset < 0)
1780 currentOffset = 0;
1781
1782 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1783 // but possibly not yet correctly aligned.
1784
1785 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001786 int dummyStride;
1787 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001788 glslang::RoundToPow2(currentOffset, memberAlignment);
1789 nextOffset = currentOffset + memberSize;
1790}
1791
John Kessenich140f3df2015-06-26 16:58:36 -06001792bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1793{
1794 return node->getName() == "main(";
1795}
1796
1797// Make all the functions, skeletally, without actually visiting their bodies.
1798void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1799{
1800 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1801 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1802 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1803 continue;
1804
1805 // We're on a user function. Set up the basic interface for the function now,
1806 // so that it's available to call.
1807 // Translating the body will happen later.
1808 //
1809 // Typically (except for a "const in" parameter), an address will be passed to the
1810 // function. What it is an address of varies:
1811 //
1812 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1813 // so that write needs to be to a copy, hence the address of a copy works.
1814 //
1815 // - "const in" parameters can just be the r-value, as no writes need occur.
1816 //
1817 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1818 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1819
1820 std::vector<spv::Id> paramTypes;
1821 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1822
1823 for (int p = 0; p < (int)parameters.size(); ++p) {
1824 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1825 spv::Id typeId = convertGlslangToSpvType(paramType);
1826 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1827 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1828 else
1829 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1830 paramTypes.push_back(typeId);
1831 }
1832
1833 spv::Block* functionBlock;
1834 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1835 paramTypes, &functionBlock);
1836
1837 // Track function to emit/call later
1838 functionMap[glslFunction->getName().c_str()] = function;
1839
1840 // Set the parameter id's
1841 for (int p = 0; p < (int)parameters.size(); ++p) {
1842 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1843 // give a name too
1844 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1845 }
1846 }
1847}
1848
1849// Process all the initializers, while skipping the functions and link objects
1850void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1851{
1852 builder.setBuildPoint(shaderEntry->getLastBlock());
1853 for (int i = 0; i < (int)initializers.size(); ++i) {
1854 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1855 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1856
1857 // We're on a top-level node that's not a function. Treat as an initializer, whose
1858 // code goes into the beginning of main.
1859 initializer->traverse(this);
1860 }
1861 }
1862}
1863
1864// Process all the functions, while skipping initializers.
1865void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1866{
1867 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1868 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1869 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1870 node->traverse(this);
1871 }
1872}
1873
1874void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1875{
1876 // SPIR-V functions should already be in the functionMap from the prepass
1877 // that called makeFunctions().
1878 spv::Function* function = functionMap[node->getName().c_str()];
1879 spv::Block* functionBlock = function->getEntryBlock();
1880 builder.setBuildPoint(functionBlock);
1881}
1882
Rex Xu04db3f52015-09-16 11:44:02 +08001883void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001884{
Rex Xufc618912015-09-09 16:42:49 +08001885 const glslang::TIntermSequence& glslangArguments = node.getSequence();
John Kessenich140f3df2015-06-26 16:58:36 -06001886 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1887 builder.clearAccessChain();
1888 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001889
1890 // Special case l-value operands
1891 bool lvalue = false;
1892 switch (node.getOp()) {
1893 case glslang::EOpImageAtomicAdd:
1894 case glslang::EOpImageAtomicMin:
1895 case glslang::EOpImageAtomicMax:
1896 case glslang::EOpImageAtomicAnd:
1897 case glslang::EOpImageAtomicOr:
1898 case glslang::EOpImageAtomicXor:
1899 case glslang::EOpImageAtomicExchange:
1900 case glslang::EOpImageAtomicCompSwap:
1901 if (i == 0)
1902 lvalue = true;
1903 break;
1904 default:
1905 break;
1906 }
1907
Rex Xu6b86d492015-09-16 17:48:22 +08001908 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08001909 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08001910 else
Rex Xu30f92582015-09-14 10:38:56 +08001911 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001912 }
1913}
1914
John Kessenichfc51d282015-08-19 13:34:18 -06001915void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001916{
John Kessenichfc51d282015-08-19 13:34:18 -06001917 builder.clearAccessChain();
1918 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001919 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06001920}
John Kessenich140f3df2015-06-26 16:58:36 -06001921
John Kessenichfc51d282015-08-19 13:34:18 -06001922spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
1923{
Rex Xufc618912015-09-09 16:42:49 +08001924 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06001925 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001926 }
1927
John Kessenichfc51d282015-08-19 13:34:18 -06001928 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06001929 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
1930 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
1931 std::vector<spv::Id> arguments;
1932 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08001933 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06001934 else
1935 translateArguments(*node->getAsUnaryNode(), arguments);
1936 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1937
1938 spv::Builder::TextureParameters params = { };
1939 params.sampler = arguments[0];
1940
Rex Xu04db3f52015-09-16 11:44:02 +08001941 glslang::TCrackedTextureOp cracked;
1942 node->crackTexture(sampler, cracked);
1943
John Kessenichfc51d282015-08-19 13:34:18 -06001944 // Check for queries
1945 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07001946 // a sampled image needs to have the image extracted first
1947 if (builder.isSampledImage(params.sampler))
1948 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06001949 switch (node->getOp()) {
1950 case glslang::EOpImageQuerySize:
1951 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06001952 if (arguments.size() > 1) {
1953 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06001954 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06001955 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06001956 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001957 case glslang::EOpImageQuerySamples:
1958 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06001959 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06001960 case glslang::EOpTextureQueryLod:
1961 params.coords = arguments[1];
1962 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
1963 case glslang::EOpTextureQueryLevels:
1964 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
1965 default:
1966 assert(0);
1967 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001968 }
John Kessenich140f3df2015-06-26 16:58:36 -06001969 }
1970
Rex Xufc618912015-09-09 16:42:49 +08001971 // Check for image functions other than queries
1972 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06001973 std::vector<spv::Id> operands;
1974 auto opIt = arguments.begin();
1975 operands.push_back(*(opIt++));
1976 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06001977 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07001978 if (sampler.ms) {
1979 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08001980 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07001981 }
John Kessenich56bab042015-09-16 10:54:31 -06001982 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
1983 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08001984 if (sampler.ms) {
1985 operands.push_back(*(opIt + 1));
1986 operands.push_back(spv::ImageOperandsSampleMask);
1987 operands.push_back(*opIt);
1988 } else
1989 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06001990 builder.createNoResultOp(spv::OpImageWrite, operands);
1991 return spv::NoResult;
Rex Xu6b86d492015-09-16 17:48:22 +08001992 } else {
1993 // Process image atomic operations
1994
1995 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
1996 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06001997 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06001998
Rex Xufc618912015-09-09 16:42:49 +08001999 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002000 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002001
2002 std::vector<spv::Id> operands;
2003 operands.push_back(pointer);
2004 for (; opIt != arguments.end(); ++opIt)
2005 operands.push_back(*opIt);
2006
Rex Xu04db3f52015-09-16 11:44:02 +08002007 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002008 }
2009 }
2010
2011 // Check for texture functions other than queries
John Kessenichfc51d282015-08-19 13:34:18 -06002012
Rex Xu71519fe2015-11-11 15:35:47 +08002013 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2014
John Kessenichfc51d282015-08-19 13:34:18 -06002015 // check for bias argument
2016 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002017 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002018 int nonBiasArgCount = 2;
2019 if (cracked.offset)
2020 ++nonBiasArgCount;
2021 if (cracked.grad)
2022 nonBiasArgCount += 2;
2023
2024 if ((int)arguments.size() > nonBiasArgCount)
2025 bias = true;
2026 }
2027
John Kessenichfc51d282015-08-19 13:34:18 -06002028 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002029
John Kessenichfc51d282015-08-19 13:34:18 -06002030 params.coords = arguments[1];
2031 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002032
2033 // sort out where Dref is coming from
2034 if (sampler.shadow && sampler.dim == glslang::EsdCube && sampler.arrayed)
John Kessenichfc51d282015-08-19 13:34:18 -06002035 params.Dref = arguments[2];
John Kessenich55e7d112015-11-15 21:33:39 -07002036 else if (sampler.shadow && cracked.gather) {
2037 params.Dref = arguments[2];
2038 ++extraArgs;
2039 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002040 std::vector<spv::Id> indexes;
2041 int comp;
2042 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002043 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002044 else
2045 comp = builder.getNumComponents(params.coords) - 1;
2046 indexes.push_back(comp);
2047 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2048 }
2049 if (cracked.lod) {
2050 params.lod = arguments[2];
2051 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002052 } else if (sampler.ms) {
2053 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002054 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002055 }
2056 if (cracked.grad) {
2057 params.gradX = arguments[2 + extraArgs];
2058 params.gradY = arguments[3 + extraArgs];
2059 extraArgs += 2;
2060 }
John Kessenich55e7d112015-11-15 21:33:39 -07002061 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002062 params.offset = arguments[2 + extraArgs];
2063 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002064 } else if (cracked.offsets) {
2065 params.offsets = arguments[2 + extraArgs];
2066 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002067 }
2068 if (bias) {
2069 params.bias = arguments[2 + extraArgs];
2070 ++extraArgs;
2071 }
John Kessenich55e7d112015-11-15 21:33:39 -07002072 if (cracked.gather && ! sampler.shadow) {
2073 // default component is 0, if missing, otherwise an argument
2074 if (2 + extraArgs < (int)arguments.size()) {
2075 params.comp = arguments[2 + extraArgs];
2076 ++extraArgs;
2077 } else {
2078 params.comp = builder.makeIntConstant(0);
2079 }
2080 }
John Kessenichfc51d282015-08-19 13:34:18 -06002081
John Kessenich55e7d112015-11-15 21:33:39 -07002082 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002083}
2084
2085spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2086{
2087 // Grab the function's pointer from the previously created function
2088 spv::Function* function = functionMap[node->getName().c_str()];
2089 if (! function)
2090 return 0;
2091
2092 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2093 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2094
2095 // See comments in makeFunctions() for details about the semantics for parameter passing.
2096 //
2097 // These imply we need a four step process:
2098 // 1. Evaluate the arguments
2099 // 2. Allocate and make copies of in, out, and inout arguments
2100 // 3. Make the call
2101 // 4. Copy back the results
2102
2103 // 1. Evaluate the arguments
2104 std::vector<spv::Builder::AccessChain> lValues;
2105 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002106 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002107 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2108 // build l-value
2109 builder.clearAccessChain();
2110 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002111 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002112 // keep outputs as l-values, evaluate input-only as r-values
2113 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2114 // save l-value
2115 lValues.push_back(builder.getAccessChain());
2116 } else {
2117 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002118 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002119 }
2120 }
2121
2122 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2123 // copy the original into that space.
2124 //
2125 // Also, build up the list of actual arguments to pass in for the call
2126 int lValueCount = 0;
2127 int rValueCount = 0;
2128 std::vector<spv::Id> spvArgs;
2129 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2130 spv::Id arg;
2131 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2132 // need space to hold the copy
2133 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2134 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2135 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2136 // need to copy the input into output space
2137 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002138 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002139 builder.createStore(copy, arg);
2140 }
2141 ++lValueCount;
2142 } else {
2143 arg = rValues[rValueCount];
2144 ++rValueCount;
2145 }
2146 spvArgs.push_back(arg);
2147 }
2148
2149 // 3. Make the call.
2150 spv::Id result = builder.createFunctionCall(function, spvArgs);
2151
2152 // 4. Copy back out an "out" arguments.
2153 lValueCount = 0;
2154 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2155 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2156 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2157 spv::Id copy = builder.createLoad(spvArgs[a]);
2158 builder.setAccessChain(lValues[lValueCount]);
2159 builder.accessChainStore(copy);
2160 }
2161 ++lValueCount;
2162 }
2163 }
2164
2165 return result;
2166}
2167
2168// Translate AST operation to SPV operation, already having SPV-based operands/types.
2169spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2170 spv::Id typeId, spv::Id left, spv::Id right,
2171 glslang::TBasicType typeProxy, bool reduceComparison)
2172{
2173 bool isUnsigned = typeProxy == glslang::EbtUint;
2174 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2175
2176 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002177 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002178 bool comparison = false;
2179
2180 switch (op) {
2181 case glslang::EOpAdd:
2182 case glslang::EOpAddAssign:
2183 if (isFloat)
2184 binOp = spv::OpFAdd;
2185 else
2186 binOp = spv::OpIAdd;
2187 break;
2188 case glslang::EOpSub:
2189 case glslang::EOpSubAssign:
2190 if (isFloat)
2191 binOp = spv::OpFSub;
2192 else
2193 binOp = spv::OpISub;
2194 break;
2195 case glslang::EOpMul:
2196 case glslang::EOpMulAssign:
2197 if (isFloat)
2198 binOp = spv::OpFMul;
2199 else
2200 binOp = spv::OpIMul;
2201 break;
2202 case glslang::EOpVectorTimesScalar:
2203 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002204 if (isFloat) {
2205 if (builder.isVector(right))
2206 std::swap(left, right);
2207 assert(builder.isScalar(right));
2208 needMatchingVectors = false;
2209 binOp = spv::OpVectorTimesScalar;
2210 } else
2211 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002212 break;
2213 case glslang::EOpVectorTimesMatrix:
2214 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002215 binOp = spv::OpVectorTimesMatrix;
2216 break;
2217 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002218 binOp = spv::OpMatrixTimesVector;
2219 break;
2220 case glslang::EOpMatrixTimesScalar:
2221 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002222 binOp = spv::OpMatrixTimesScalar;
2223 break;
2224 case glslang::EOpMatrixTimesMatrix:
2225 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002226 binOp = spv::OpMatrixTimesMatrix;
2227 break;
2228 case glslang::EOpOuterProduct:
2229 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002230 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002231 break;
2232
2233 case glslang::EOpDiv:
2234 case glslang::EOpDivAssign:
2235 if (isFloat)
2236 binOp = spv::OpFDiv;
2237 else if (isUnsigned)
2238 binOp = spv::OpUDiv;
2239 else
2240 binOp = spv::OpSDiv;
2241 break;
2242 case glslang::EOpMod:
2243 case glslang::EOpModAssign:
2244 if (isFloat)
2245 binOp = spv::OpFMod;
2246 else if (isUnsigned)
2247 binOp = spv::OpUMod;
2248 else
2249 binOp = spv::OpSMod;
2250 break;
2251 case glslang::EOpRightShift:
2252 case glslang::EOpRightShiftAssign:
2253 if (isUnsigned)
2254 binOp = spv::OpShiftRightLogical;
2255 else
2256 binOp = spv::OpShiftRightArithmetic;
2257 break;
2258 case glslang::EOpLeftShift:
2259 case glslang::EOpLeftShiftAssign:
2260 binOp = spv::OpShiftLeftLogical;
2261 break;
2262 case glslang::EOpAnd:
2263 case glslang::EOpAndAssign:
2264 binOp = spv::OpBitwiseAnd;
2265 break;
2266 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002267 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002268 binOp = spv::OpLogicalAnd;
2269 break;
2270 case glslang::EOpInclusiveOr:
2271 case glslang::EOpInclusiveOrAssign:
2272 binOp = spv::OpBitwiseOr;
2273 break;
2274 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002275 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002276 binOp = spv::OpLogicalOr;
2277 break;
2278 case glslang::EOpExclusiveOr:
2279 case glslang::EOpExclusiveOrAssign:
2280 binOp = spv::OpBitwiseXor;
2281 break;
2282 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002283 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002284 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002285 break;
2286
2287 case glslang::EOpLessThan:
2288 case glslang::EOpGreaterThan:
2289 case glslang::EOpLessThanEqual:
2290 case glslang::EOpGreaterThanEqual:
2291 case glslang::EOpEqual:
2292 case glslang::EOpNotEqual:
2293 case glslang::EOpVectorEqual:
2294 case glslang::EOpVectorNotEqual:
2295 comparison = true;
2296 break;
2297 default:
2298 break;
2299 }
2300
John Kessenich7c1aa102015-10-15 13:29:11 -06002301 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002302 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002303 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002304 if (builder.isMatrix(left) || builder.isMatrix(right))
2305 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002306
2307 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002308 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002309 builder.promoteScalar(precision, left, right);
2310
2311 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2312 builder.setPrecision(id, precision);
2313
2314 return id;
2315 }
2316
2317 if (! comparison)
2318 return 0;
2319
John Kessenich7c1aa102015-10-15 13:29:11 -06002320 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002321
2322 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2323 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2324
John Kessenich22118352015-12-21 20:54:09 -07002325 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002326 }
2327
2328 switch (op) {
2329 case glslang::EOpLessThan:
2330 if (isFloat)
2331 binOp = spv::OpFOrdLessThan;
2332 else if (isUnsigned)
2333 binOp = spv::OpULessThan;
2334 else
2335 binOp = spv::OpSLessThan;
2336 break;
2337 case glslang::EOpGreaterThan:
2338 if (isFloat)
2339 binOp = spv::OpFOrdGreaterThan;
2340 else if (isUnsigned)
2341 binOp = spv::OpUGreaterThan;
2342 else
2343 binOp = spv::OpSGreaterThan;
2344 break;
2345 case glslang::EOpLessThanEqual:
2346 if (isFloat)
2347 binOp = spv::OpFOrdLessThanEqual;
2348 else if (isUnsigned)
2349 binOp = spv::OpULessThanEqual;
2350 else
2351 binOp = spv::OpSLessThanEqual;
2352 break;
2353 case glslang::EOpGreaterThanEqual:
2354 if (isFloat)
2355 binOp = spv::OpFOrdGreaterThanEqual;
2356 else if (isUnsigned)
2357 binOp = spv::OpUGreaterThanEqual;
2358 else
2359 binOp = spv::OpSGreaterThanEqual;
2360 break;
2361 case glslang::EOpEqual:
2362 case glslang::EOpVectorEqual:
2363 if (isFloat)
2364 binOp = spv::OpFOrdEqual;
2365 else
2366 binOp = spv::OpIEqual;
2367 break;
2368 case glslang::EOpNotEqual:
2369 case glslang::EOpVectorNotEqual:
2370 if (isFloat)
2371 binOp = spv::OpFOrdNotEqual;
2372 else
2373 binOp = spv::OpINotEqual;
2374 break;
2375 default:
2376 break;
2377 }
2378
2379 if (binOp != spv::OpNop) {
2380 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2381 builder.setPrecision(id, precision);
2382
2383 return id;
2384 }
2385
2386 return 0;
2387}
2388
John Kessenich04bb8a02015-12-12 12:28:14 -07002389//
2390// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2391// These can be any of:
2392//
2393// matrix * scalar
2394// scalar * matrix
2395// matrix * matrix linear algebraic
2396// matrix * vector
2397// vector * matrix
2398// matrix * matrix componentwise
2399// matrix op matrix op in {+, -, /}
2400// matrix op scalar op in {+, -, /}
2401// scalar op matrix op in {+, -, /}
2402//
2403spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2404{
2405 bool firstClass = true;
2406
2407 // First, handle first-class matrix operations (* and matrix/scalar)
2408 switch (op) {
2409 case spv::OpFDiv:
2410 if (builder.isMatrix(left) && builder.isScalar(right)) {
2411 // turn matrix / scalar into a multiply...
2412 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2413 op = spv::OpMatrixTimesScalar;
2414 } else
2415 firstClass = false;
2416 break;
2417 case spv::OpMatrixTimesScalar:
2418 if (builder.isMatrix(right))
2419 std::swap(left, right);
2420 assert(builder.isScalar(right));
2421 break;
2422 case spv::OpVectorTimesMatrix:
2423 assert(builder.isVector(left));
2424 assert(builder.isMatrix(right));
2425 break;
2426 case spv::OpMatrixTimesVector:
2427 assert(builder.isMatrix(left));
2428 assert(builder.isVector(right));
2429 break;
2430 case spv::OpMatrixTimesMatrix:
2431 assert(builder.isMatrix(left));
2432 assert(builder.isMatrix(right));
2433 break;
2434 default:
2435 firstClass = false;
2436 break;
2437 }
2438
2439 if (firstClass) {
2440 spv::Id id = builder.createBinOp(op, typeId, left, right);
2441 builder.setPrecision(id, precision);
2442
2443 return id;
2444 }
2445
2446 // Handle component-wise +, -, *, and / for all combinations of type.
2447 // The result type of all of them is the same type as the (a) matrix operand.
2448 // The algorithm is to:
2449 // - break the matrix(es) into vectors
2450 // - smear any scalar to a vector
2451 // - do vector operations
2452 // - make a matrix out the vector results
2453 switch (op) {
2454 case spv::OpFAdd:
2455 case spv::OpFSub:
2456 case spv::OpFDiv:
2457 case spv::OpFMul:
2458 {
2459 // one time set up...
2460 bool leftMat = builder.isMatrix(left);
2461 bool rightMat = builder.isMatrix(right);
2462 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2463 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2464 spv::Id scalarType = builder.getScalarTypeId(typeId);
2465 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2466 std::vector<spv::Id> results;
2467 spv::Id smearVec = spv::NoResult;
2468 if (builder.isScalar(left))
2469 smearVec = builder.smearScalar(precision, left, vecType);
2470 else if (builder.isScalar(right))
2471 smearVec = builder.smearScalar(precision, right, vecType);
2472
2473 // do each vector op
2474 for (unsigned int c = 0; c < numCols; ++c) {
2475 std::vector<unsigned int> indexes;
2476 indexes.push_back(c);
2477 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2478 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2479 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2480 builder.setPrecision(results.back(), precision);
2481 }
2482
2483 // put the pieces together
2484 spv::Id id = builder.createCompositeConstruct(typeId, results);
2485 builder.setPrecision(id, precision);
2486 return id;
2487 }
2488 default:
2489 assert(0);
2490 return spv::NoResult;
2491 }
2492}
2493
Rex Xu04db3f52015-09-16 11:44:02 +08002494spv::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 -06002495{
2496 spv::Op unaryOp = spv::OpNop;
2497 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002498 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002499 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002500
2501 switch (op) {
2502 case glslang::EOpNegative:
2503 if (isFloat)
2504 unaryOp = spv::OpFNegate;
2505 else
2506 unaryOp = spv::OpSNegate;
2507 break;
2508
2509 case glslang::EOpLogicalNot:
2510 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002511 unaryOp = spv::OpLogicalNot;
2512 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002513 case glslang::EOpBitwiseNot:
2514 unaryOp = spv::OpNot;
2515 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002516
John Kessenich140f3df2015-06-26 16:58:36 -06002517 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002518 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002519 break;
2520 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002521 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002522 break;
2523 case glslang::EOpTranspose:
2524 unaryOp = spv::OpTranspose;
2525 break;
2526
2527 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002528 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002529 break;
2530 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002531 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002532 break;
2533 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002534 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002535 break;
2536 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002537 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002538 break;
2539 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002540 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002541 break;
2542 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002543 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002544 break;
2545 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002546 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002547 break;
2548 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002549 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002550 break;
2551
2552 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002553 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002554 break;
2555 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002556 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002557 break;
2558 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002559 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002560 break;
2561 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002562 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002563 break;
2564 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002565 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002566 break;
2567 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002568 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002569 break;
2570
2571 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002572 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002573 break;
2574 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002575 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002576 break;
2577
2578 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002579 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002580 break;
2581 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002582 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002583 break;
2584 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002585 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002586 break;
2587 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002588 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002589 break;
2590 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002591 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002592 break;
2593 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002594 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002595 break;
2596
2597 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002598 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002599 break;
2600 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002601 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002602 break;
2603 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002604 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002605 break;
2606 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002607 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002608 break;
2609 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002610 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002611 break;
2612 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002613 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002614 break;
2615
2616 case glslang::EOpIsNan:
2617 unaryOp = spv::OpIsNan;
2618 break;
2619 case glslang::EOpIsInf:
2620 unaryOp = spv::OpIsInf;
2621 break;
2622
Rex Xucbc426e2015-12-15 16:03:10 +08002623 case glslang::EOpFloatBitsToInt:
2624 case glslang::EOpFloatBitsToUint:
2625 case glslang::EOpIntBitsToFloat:
2626 case glslang::EOpUintBitsToFloat:
2627 unaryOp = spv::OpBitcast;
2628 break;
2629
John Kessenich140f3df2015-06-26 16:58:36 -06002630 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002631 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002632 break;
2633 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002634 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002635 break;
2636 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002637 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002638 break;
2639 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002640 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002641 break;
2642 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002643 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002644 break;
2645 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002646 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002647 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002648 case glslang::EOpPackSnorm4x8:
2649 libCall = spv::GLSLstd450PackSnorm4x8;
2650 break;
2651 case glslang::EOpUnpackSnorm4x8:
2652 libCall = spv::GLSLstd450UnpackSnorm4x8;
2653 break;
2654 case glslang::EOpPackUnorm4x8:
2655 libCall = spv::GLSLstd450PackUnorm4x8;
2656 break;
2657 case glslang::EOpUnpackUnorm4x8:
2658 libCall = spv::GLSLstd450UnpackUnorm4x8;
2659 break;
2660 case glslang::EOpPackDouble2x32:
2661 libCall = spv::GLSLstd450PackDouble2x32;
2662 break;
2663 case glslang::EOpUnpackDouble2x32:
2664 libCall = spv::GLSLstd450UnpackDouble2x32;
2665 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002666
2667 case glslang::EOpDPdx:
2668 unaryOp = spv::OpDPdx;
2669 break;
2670 case glslang::EOpDPdy:
2671 unaryOp = spv::OpDPdy;
2672 break;
2673 case glslang::EOpFwidth:
2674 unaryOp = spv::OpFwidth;
2675 break;
2676 case glslang::EOpDPdxFine:
2677 unaryOp = spv::OpDPdxFine;
2678 break;
2679 case glslang::EOpDPdyFine:
2680 unaryOp = spv::OpDPdyFine;
2681 break;
2682 case glslang::EOpFwidthFine:
2683 unaryOp = spv::OpFwidthFine;
2684 break;
2685 case glslang::EOpDPdxCoarse:
2686 unaryOp = spv::OpDPdxCoarse;
2687 break;
2688 case glslang::EOpDPdyCoarse:
2689 unaryOp = spv::OpDPdyCoarse;
2690 break;
2691 case glslang::EOpFwidthCoarse:
2692 unaryOp = spv::OpFwidthCoarse;
2693 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002694 case glslang::EOpInterpolateAtCentroid:
2695 libCall = spv::GLSLstd450InterpolateAtCentroid;
2696 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002697 case glslang::EOpAny:
2698 unaryOp = spv::OpAny;
2699 break;
2700 case glslang::EOpAll:
2701 unaryOp = spv::OpAll;
2702 break;
2703
2704 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002705 if (isFloat)
2706 libCall = spv::GLSLstd450FAbs;
2707 else
2708 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002709 break;
2710 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002711 if (isFloat)
2712 libCall = spv::GLSLstd450FSign;
2713 else
2714 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002715 break;
2716
John Kessenichfc51d282015-08-19 13:34:18 -06002717 case glslang::EOpAtomicCounterIncrement:
2718 case glslang::EOpAtomicCounterDecrement:
2719 case glslang::EOpAtomicCounter:
2720 {
2721 // Handle all of the atomics in one place, in createAtomicOperation()
2722 std::vector<spv::Id> operands;
2723 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002724 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002725 }
2726
2727 case glslang::EOpImageLoad:
2728 unaryOp = spv::OpImageRead;
2729 break;
2730
2731 case glslang::EOpBitFieldReverse:
2732 unaryOp = spv::OpBitReverse;
2733 break;
2734 case glslang::EOpBitCount:
2735 unaryOp = spv::OpBitCount;
2736 break;
2737 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002738 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002739 break;
2740 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002741 if (isUnsigned)
2742 libCall = spv::GLSLstd450FindUMsb;
2743 else
2744 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002745 break;
2746
John Kessenich140f3df2015-06-26 16:58:36 -06002747 default:
2748 return 0;
2749 }
2750
2751 spv::Id id;
2752 if (libCall >= 0) {
2753 std::vector<spv::Id> args;
2754 args.push_back(operand);
2755 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2756 } else
2757 id = builder.createUnaryOp(unaryOp, typeId, operand);
2758
2759 builder.setPrecision(id, precision);
2760
2761 return id;
2762}
2763
2764spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2765{
2766 spv::Op convOp = spv::OpNop;
2767 spv::Id zero = 0;
2768 spv::Id one = 0;
2769
2770 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2771
2772 switch (op) {
2773 case glslang::EOpConvIntToBool:
2774 case glslang::EOpConvUintToBool:
2775 zero = builder.makeUintConstant(0);
2776 zero = makeSmearedConstant(zero, vectorSize);
2777 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2778
2779 case glslang::EOpConvFloatToBool:
2780 zero = builder.makeFloatConstant(0.0F);
2781 zero = makeSmearedConstant(zero, vectorSize);
2782 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2783
2784 case glslang::EOpConvDoubleToBool:
2785 zero = builder.makeDoubleConstant(0.0);
2786 zero = makeSmearedConstant(zero, vectorSize);
2787 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2788
2789 case glslang::EOpConvBoolToFloat:
2790 convOp = spv::OpSelect;
2791 zero = builder.makeFloatConstant(0.0);
2792 one = builder.makeFloatConstant(1.0);
2793 break;
2794 case glslang::EOpConvBoolToDouble:
2795 convOp = spv::OpSelect;
2796 zero = builder.makeDoubleConstant(0.0);
2797 one = builder.makeDoubleConstant(1.0);
2798 break;
2799 case glslang::EOpConvBoolToInt:
2800 zero = builder.makeIntConstant(0);
2801 one = builder.makeIntConstant(1);
2802 convOp = spv::OpSelect;
2803 break;
2804 case glslang::EOpConvBoolToUint:
2805 zero = builder.makeUintConstant(0);
2806 one = builder.makeUintConstant(1);
2807 convOp = spv::OpSelect;
2808 break;
2809
2810 case glslang::EOpConvIntToFloat:
2811 case glslang::EOpConvIntToDouble:
2812 convOp = spv::OpConvertSToF;
2813 break;
2814
2815 case glslang::EOpConvUintToFloat:
2816 case glslang::EOpConvUintToDouble:
2817 convOp = spv::OpConvertUToF;
2818 break;
2819
2820 case glslang::EOpConvDoubleToFloat:
2821 case glslang::EOpConvFloatToDouble:
2822 convOp = spv::OpFConvert;
2823 break;
2824
2825 case glslang::EOpConvFloatToInt:
2826 case glslang::EOpConvDoubleToInt:
2827 convOp = spv::OpConvertFToS;
2828 break;
2829
2830 case glslang::EOpConvUintToInt:
2831 case glslang::EOpConvIntToUint:
2832 convOp = spv::OpBitcast;
2833 break;
2834
2835 case glslang::EOpConvFloatToUint:
2836 case glslang::EOpConvDoubleToUint:
2837 convOp = spv::OpConvertFToU;
2838 break;
2839 default:
2840 break;
2841 }
2842
2843 spv::Id result = 0;
2844 if (convOp == spv::OpNop)
2845 return result;
2846
2847 if (convOp == spv::OpSelect) {
2848 zero = makeSmearedConstant(zero, vectorSize);
2849 one = makeSmearedConstant(one, vectorSize);
2850 result = builder.createTriOp(convOp, destType, operand, one, zero);
2851 } else
2852 result = builder.createUnaryOp(convOp, destType, operand);
2853
2854 builder.setPrecision(result, precision);
2855
2856 return result;
2857}
2858
2859spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
2860{
2861 if (vectorSize == 0)
2862 return constant;
2863
2864 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
2865 std::vector<spv::Id> components;
2866 for (int c = 0; c < vectorSize; ++c)
2867 components.push_back(constant);
2868 return builder.makeCompositeConstant(vectorTypeId, components);
2869}
2870
John Kessenich426394d2015-07-23 10:22:48 -06002871// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08002872spv::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 -06002873{
2874 spv::Op opCode = spv::OpNop;
2875
2876 switch (op) {
2877 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08002878 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06002879 opCode = spv::OpAtomicIAdd;
2880 break;
2881 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08002882 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08002883 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06002884 break;
2885 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08002886 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08002887 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06002888 break;
2889 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08002890 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06002891 opCode = spv::OpAtomicAnd;
2892 break;
2893 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08002894 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06002895 opCode = spv::OpAtomicOr;
2896 break;
2897 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08002898 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06002899 opCode = spv::OpAtomicXor;
2900 break;
2901 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08002902 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06002903 opCode = spv::OpAtomicExchange;
2904 break;
2905 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08002906 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06002907 opCode = spv::OpAtomicCompareExchange;
2908 break;
2909 case glslang::EOpAtomicCounterIncrement:
2910 opCode = spv::OpAtomicIIncrement;
2911 break;
2912 case glslang::EOpAtomicCounterDecrement:
2913 opCode = spv::OpAtomicIDecrement;
2914 break;
2915 case glslang::EOpAtomicCounter:
2916 opCode = spv::OpAtomicLoad;
2917 break;
2918 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002919 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06002920 break;
2921 }
2922
2923 // Sort out the operands
2924 // - mapping from glslang -> SPV
2925 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06002926 // - compare-exchange swaps the value and comparator
2927 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06002928 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
2929 auto opIt = operands.begin(); // walk the glslang operands
2930 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08002931 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
2932 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
2933 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08002934 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
2935 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08002936 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06002937 spvAtomicOperands.push_back(*(opIt + 1));
2938 spvAtomicOperands.push_back(*opIt);
2939 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08002940 }
John Kessenich426394d2015-07-23 10:22:48 -06002941
John Kessenich3e60a6f2015-09-14 22:45:16 -06002942 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06002943 for (; opIt != operands.end(); ++opIt)
2944 spvAtomicOperands.push_back(*opIt);
2945
2946 return builder.createOp(opCode, typeId, spvAtomicOperands);
2947}
2948
John Kessenich5e4b1242015-08-06 22:53:06 -06002949spv::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 -06002950{
John Kessenich5e4b1242015-08-06 22:53:06 -06002951 bool isUnsigned = typeProxy == glslang::EbtUint;
2952 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2953
John Kessenich140f3df2015-06-26 16:58:36 -06002954 spv::Op opCode = spv::OpNop;
2955 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002956 int consumedOperands = operands.size();
2957 spv::Id typeId0 = 0;
2958 if (consumedOperands > 0)
2959 typeId0 = builder.getTypeId(operands[0]);
2960 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002961
2962 switch (op) {
2963 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002964 if (isFloat)
2965 libCall = spv::GLSLstd450FMin;
2966 else if (isUnsigned)
2967 libCall = spv::GLSLstd450UMin;
2968 else
2969 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002970 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002971 break;
2972 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06002973 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06002974 break;
2975 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06002976 if (isFloat)
2977 libCall = spv::GLSLstd450FMax;
2978 else if (isUnsigned)
2979 libCall = spv::GLSLstd450UMax;
2980 else
2981 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07002982 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06002983 break;
2984 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06002985 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06002986 break;
2987 case glslang::EOpDot:
2988 opCode = spv::OpDot;
2989 break;
2990 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002991 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06002992 break;
2993
2994 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002995 if (isFloat)
2996 libCall = spv::GLSLstd450FClamp;
2997 else if (isUnsigned)
2998 libCall = spv::GLSLstd450UClamp;
2999 else
3000 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003001 builder.promoteScalar(precision, operands.front(), operands[1]);
3002 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003003 break;
3004 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003005 if (isFloat)
3006 libCall = spv::GLSLstd450FMix;
3007 else
3008 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003009 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003010 break;
3011 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003012 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003013 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003014 break;
3015 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003016 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003017 builder.promoteScalar(precision, operands[0], operands[2]);
3018 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003019 break;
3020
3021 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003022 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003023 break;
3024 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003025 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003026 break;
3027 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003028 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003029 break;
3030 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003031 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003032 break;
3033 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003034 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003035 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003036 case glslang::EOpInterpolateAtSample:
3037 libCall = spv::GLSLstd450InterpolateAtSample;
3038 break;
3039 case glslang::EOpInterpolateAtOffset:
3040 libCall = spv::GLSLstd450InterpolateAtOffset;
3041 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003042 case glslang::EOpAddCarry:
3043 opCode = spv::OpIAddCarry;
3044 typeId = builder.makeStructResultType(typeId0, typeId0);
3045 consumedOperands = 2;
3046 break;
3047 case glslang::EOpSubBorrow:
3048 opCode = spv::OpISubBorrow;
3049 typeId = builder.makeStructResultType(typeId0, typeId0);
3050 consumedOperands = 2;
3051 break;
3052 case glslang::EOpUMulExtended:
3053 opCode = spv::OpUMulExtended;
3054 typeId = builder.makeStructResultType(typeId0, typeId0);
3055 consumedOperands = 2;
3056 break;
3057 case glslang::EOpIMulExtended:
3058 opCode = spv::OpSMulExtended;
3059 typeId = builder.makeStructResultType(typeId0, typeId0);
3060 consumedOperands = 2;
3061 break;
3062 case glslang::EOpBitfieldExtract:
3063 if (isUnsigned)
3064 opCode = spv::OpBitFieldUExtract;
3065 else
3066 opCode = spv::OpBitFieldSExtract;
3067 break;
3068 case glslang::EOpBitfieldInsert:
3069 opCode = spv::OpBitFieldInsert;
3070 break;
3071
3072 case glslang::EOpFma:
3073 libCall = spv::GLSLstd450Fma;
3074 break;
3075 case glslang::EOpFrexp:
3076 libCall = spv::GLSLstd450FrexpStruct;
3077 if (builder.getNumComponents(operands[0]) == 1)
3078 frexpIntType = builder.makeIntegerType(32, true);
3079 else
3080 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3081 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3082 consumedOperands = 1;
3083 break;
3084 case glslang::EOpLdexp:
3085 libCall = spv::GLSLstd450Ldexp;
3086 break;
3087
John Kessenich140f3df2015-06-26 16:58:36 -06003088 default:
3089 return 0;
3090 }
3091
3092 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003093 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003094 // Use an extended instruction from the standard library.
3095 // Construct the call arguments, without modifying the original operands vector.
3096 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3097 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
3098 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003099 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003100 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003101 case 0:
3102 // should all be handled by visitAggregate and createNoArgOperation
3103 assert(0);
3104 return 0;
3105 case 1:
3106 // should all be handled by createUnaryOperation
3107 assert(0);
3108 return 0;
3109 case 2:
3110 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3111 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003112 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003113 // anything 3 or over doesn't have l-value operands, so all should be consumed
3114 assert(consumedOperands == operands.size());
3115 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003116 break;
3117 }
3118 }
3119
John Kessenich55e7d112015-11-15 21:33:39 -07003120 // Decode the return types that were structures
3121 switch (op) {
3122 case glslang::EOpAddCarry:
3123 case glslang::EOpSubBorrow:
3124 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3125 id = builder.createCompositeExtract(id, typeId0, 0);
3126 break;
3127 case glslang::EOpUMulExtended:
3128 case glslang::EOpIMulExtended:
3129 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3130 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3131 break;
3132 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003133 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003134 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3135 id = builder.createCompositeExtract(id, typeId0, 0);
3136 break;
3137 default:
3138 break;
3139 }
3140
John Kessenich140f3df2015-06-26 16:58:36 -06003141 builder.setPrecision(id, precision);
3142
3143 return id;
3144}
3145
3146// Intrinsics with no arguments, no return value, and no precision.
3147spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3148{
3149 // TODO: get the barrier operands correct
3150
3151 switch (op) {
3152 case glslang::EOpEmitVertex:
3153 builder.createNoResultOp(spv::OpEmitVertex);
3154 return 0;
3155 case glslang::EOpEndPrimitive:
3156 builder.createNoResultOp(spv::OpEndPrimitive);
3157 return 0;
3158 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003159 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3160 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003161 return 0;
3162 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003163 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003164 return 0;
3165 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003166 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003167 return 0;
3168 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003169 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003170 return 0;
3171 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003172 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003173 return 0;
3174 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003175 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003176 return 0;
3177 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003178 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003179 return 0;
3180 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003181 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003182 return 0;
3183 }
3184}
3185
3186spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3187{
John Kessenich2f273362015-07-18 22:34:27 -06003188 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003189 spv::Id id;
3190 if (symbolValues.end() != iter) {
3191 id = iter->second;
3192 return id;
3193 }
3194
3195 // it was not found, create it
3196 id = createSpvVariable(symbol);
3197 symbolValues[symbol->getId()] = id;
3198
3199 if (! symbol->getType().isStruct()) {
3200 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003201 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003202 if (symbol->getQualifier().hasLocation())
3203 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3204 if (symbol->getQualifier().hasIndex())
3205 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3206 if (symbol->getQualifier().hasComponent())
3207 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3208 if (glslangIntermediate->getXfbMode()) {
3209 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003210 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003211 if (symbol->getQualifier().hasXfbBuffer())
3212 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3213 if (symbol->getQualifier().hasXfbOffset())
3214 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3215 }
3216 }
3217
John Kesseniche0b6cad2015-12-24 10:30:13 -07003218 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003219 if (symbol->getQualifier().hasStream())
3220 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3221 if (symbol->getQualifier().hasSet())
3222 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3223 if (symbol->getQualifier().hasBinding())
3224 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3225 if (glslangIntermediate->getXfbMode()) {
3226 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003227 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003228 if (symbol->getQualifier().hasXfbBuffer())
3229 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3230 }
3231
3232 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003233 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003234 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003235 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003236
John Kessenich140f3df2015-06-26 16:58:36 -06003237 return id;
3238}
3239
John Kessenich55e7d112015-11-15 21:33:39 -07003240// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003241void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3242{
3243 if (dec != spv::BadValue)
3244 builder.addDecoration(id, dec);
3245}
3246
John Kessenich55e7d112015-11-15 21:33:39 -07003247// If 'dec' is valid, add a one-operand decoration to an object
3248void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3249{
3250 if (dec != spv::BadValue)
3251 builder.addDecoration(id, dec, value);
3252}
3253
3254// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003255void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3256{
3257 if (dec != spv::BadValue)
3258 builder.addMemberDecoration(id, (unsigned)member, dec);
3259}
3260
John Kessenich55e7d112015-11-15 21:33:39 -07003261// Make a full tree of instructions to build a SPIR-V specialization constant,
3262// or regularly constant if possible.
3263//
3264// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3265//
3266// Recursively walk the nodes. The nodes form a tree whose leaves are
3267// regular constants, which themselves are trees that createSpvConstant()
3268// recursively walks. So, this function walks the "top" of the tree:
3269// - emit specialization constant-building instructions for specConstant
3270// - when running into a non-spec-constant, switch to createSpvConstant()
3271spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3272{
3273 assert(node.getQualifier().storage == glslang::EvqConst);
3274
3275 // hand off to the non-spec-constant path
3276 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3277 int nextConst = 0;
3278 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3279}
3280
John Kessenich140f3df2015-06-26 16:58:36 -06003281// Use 'consts' as the flattened glslang source of scalar constants to recursively
3282// build the aggregate SPIR-V constant.
3283//
3284// If there are not enough elements present in 'consts', 0 will be substituted;
3285// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3286//
John Kessenich55e7d112015-11-15 21:33:39 -07003287spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003288{
3289 // vector of constants for SPIR-V
3290 std::vector<spv::Id> spvConsts;
3291
3292 // Type is used for struct and array constants
3293 spv::Id typeId = convertGlslangToSpvType(glslangType);
3294
3295 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003296 glslang::TType elementType(glslangType, 0);
3297 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003298 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003299 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003300 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003301 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003302 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003303 } else if (glslangType.getStruct()) {
3304 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3305 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003306 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003307 } else if (glslangType.isVector()) {
3308 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3309 bool zero = nextConst >= consts.size();
3310 switch (glslangType.getBasicType()) {
3311 case glslang::EbtInt:
3312 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3313 break;
3314 case glslang::EbtUint:
3315 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3316 break;
3317 case glslang::EbtFloat:
3318 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3319 break;
3320 case glslang::EbtDouble:
3321 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3322 break;
3323 case glslang::EbtBool:
3324 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3325 break;
3326 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003327 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003328 break;
3329 }
3330 ++nextConst;
3331 }
3332 } else {
3333 // we have a non-aggregate (scalar) constant
3334 bool zero = nextConst >= consts.size();
3335 spv::Id scalar = 0;
3336 switch (glslangType.getBasicType()) {
3337 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003338 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003339 break;
3340 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003341 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003342 break;
3343 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003344 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003345 break;
3346 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003347 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003348 break;
3349 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003350 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003351 break;
3352 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003353 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003354 break;
3355 }
3356 ++nextConst;
3357 return scalar;
3358 }
3359
3360 return builder.makeCompositeConstant(typeId, spvConsts);
3361}
3362
John Kessenich7c1aa102015-10-15 13:29:11 -06003363// Return true if the node is a constant or symbol whose reading has no
3364// non-trivial observable cost or effect.
3365bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3366{
3367 // don't know what this is
3368 if (node == nullptr)
3369 return false;
3370
3371 // a constant is safe
3372 if (node->getAsConstantUnion() != nullptr)
3373 return true;
3374
3375 // not a symbol means non-trivial
3376 if (node->getAsSymbolNode() == nullptr)
3377 return false;
3378
3379 // a symbol, depends on what's being read
3380 switch (node->getType().getQualifier().storage) {
3381 case glslang::EvqTemporary:
3382 case glslang::EvqGlobal:
3383 case glslang::EvqIn:
3384 case glslang::EvqInOut:
3385 case glslang::EvqConst:
3386 case glslang::EvqConstReadOnly:
3387 case glslang::EvqUniform:
3388 return true;
3389 default:
3390 return false;
3391 }
3392}
3393
3394// A node is trivial if it is a single operation with no side effects.
3395// Error on the side of saying non-trivial.
3396// Return true if trivial.
3397bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3398{
3399 if (node == nullptr)
3400 return false;
3401
3402 // symbols and constants are trivial
3403 if (isTrivialLeaf(node))
3404 return true;
3405
3406 // otherwise, it needs to be a simple operation or one or two leaf nodes
3407
3408 // not a simple operation
3409 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3410 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3411 if (binaryNode == nullptr && unaryNode == nullptr)
3412 return false;
3413
3414 // not on leaf nodes
3415 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3416 return false;
3417
3418 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3419 return false;
3420 }
3421
3422 switch (node->getAsOperator()->getOp()) {
3423 case glslang::EOpLogicalNot:
3424 case glslang::EOpConvIntToBool:
3425 case glslang::EOpConvUintToBool:
3426 case glslang::EOpConvFloatToBool:
3427 case glslang::EOpConvDoubleToBool:
3428 case glslang::EOpEqual:
3429 case glslang::EOpNotEqual:
3430 case glslang::EOpLessThan:
3431 case glslang::EOpGreaterThan:
3432 case glslang::EOpLessThanEqual:
3433 case glslang::EOpGreaterThanEqual:
3434 case glslang::EOpIndexDirect:
3435 case glslang::EOpIndexDirectStruct:
3436 case glslang::EOpLogicalXor:
3437 case glslang::EOpAny:
3438 case glslang::EOpAll:
3439 return true;
3440 default:
3441 return false;
3442 }
3443}
3444
3445// Emit short-circuiting code, where 'right' is never evaluated unless
3446// the left side is true (for &&) or false (for ||).
3447spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3448{
3449 spv::Id boolTypeId = builder.makeBoolType();
3450
3451 // emit left operand
3452 builder.clearAccessChain();
3453 left.traverse(this);
3454 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3455
3456 // Operands to accumulate OpPhi operands
3457 std::vector<spv::Id> phiOperands;
3458 // accumulate left operand's phi information
3459 phiOperands.push_back(leftId);
3460 phiOperands.push_back(builder.getBuildPoint()->getId());
3461
3462 // Make the two kinds of operation symmetric with a "!"
3463 // || => emit "if (! left) result = right"
3464 // && => emit "if ( left) result = right"
3465 //
3466 // TODO: this runtime "not" for || could be avoided by adding functionality
3467 // to 'builder' to have an "else" without an "then"
3468 if (op == glslang::EOpLogicalOr)
3469 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3470
3471 // make an "if" based on the left value
3472 spv::Builder::If ifBuilder(leftId, builder);
3473
3474 // emit right operand as the "then" part of the "if"
3475 builder.clearAccessChain();
3476 right.traverse(this);
3477 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3478
3479 // accumulate left operand's phi information
3480 phiOperands.push_back(rightId);
3481 phiOperands.push_back(builder.getBuildPoint()->getId());
3482
3483 // finish the "if"
3484 ifBuilder.makeEndIf();
3485
3486 // phi together the two results
3487 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3488}
3489
John Kessenich140f3df2015-06-26 16:58:36 -06003490}; // end anonymous namespace
3491
3492namespace glslang {
3493
John Kessenich68d78fd2015-07-12 19:28:10 -06003494void GetSpirvVersion(std::string& version)
3495{
John Kessenich9e55f632015-07-15 10:03:39 -06003496 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003497 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003498 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003499 version = buf;
3500}
3501
John Kessenich140f3df2015-06-26 16:58:36 -06003502// Write SPIR-V out to a binary file
3503void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3504{
3505 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003506 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003507 for (int i = 0; i < (int)spirv.size(); ++i) {
3508 unsigned int word = spirv[i];
3509 out.write((const char*)&word, 4);
3510 }
3511 out.close();
3512}
3513
3514//
3515// Set up the glslang traversal
3516//
3517void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3518{
3519 TIntermNode* root = intermediate.getTreeRoot();
3520
3521 if (root == 0)
3522 return;
3523
3524 glslang::GetThreadPoolAllocator().push();
3525
3526 TGlslangToSpvTraverser it(&intermediate);
3527
3528 root->traverse(&it);
3529
3530 it.dumpSpv(spirv);
3531
3532 glslang::GetThreadPoolAllocator().pop();
3533}
3534
3535}; // end namespace glslang