blob: 01f3f903e327a13a45e88566ecaeea902562a52f [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 Kessenich7a53f762016-01-20 11:19:27 -0700113 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
115 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800116 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 -0600117 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 -0600118 spv::Id createNoArgOperation(glslang::TOperator op);
119 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
120 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700121 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600122 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700123 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
124 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600125 bool isTrivialLeaf(const glslang::TIntermTyped* node);
126 bool isTrivial(const glslang::TIntermTyped* node);
127 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600128
129 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700130 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600131 int sequenceDepth;
132
133 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
134 spv::Builder builder;
135 bool inMain;
136 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700137 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 -0700138 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600139 const glslang::TIntermediate* glslangIntermediate;
140 spv::Id stdBuiltins;
141
John Kessenich2f273362015-07-18 22:34:27 -0600142 std::unordered_map<int, spv::Id> symbolValues;
143 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
144 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700145 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600146 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 -0600147 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600148};
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;
John Kessenich7b9fa252016-01-21 18:56:57 -0700440
441 child.layoutLocation = parent.layoutLocation;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700442}
443
444bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
445{
John Kessenich7b9fa252016-01-21 18:56:57 -0700446 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700447 // - struct members can inherit from a struct declaration
448 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
449 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700450 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700451}
452
John Kessenich140f3df2015-06-26 16:58:36 -0600453//
454// Implement the TGlslangToSpvTraverser class.
455//
456
457TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
458 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700459 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600460 inMain(false), mainTerminated(false), linkageOnly(false),
461 glslangIntermediate(glslangIntermediate)
462{
463 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
464
465 builder.clearAccessChain();
466 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
467 stdBuiltins = builder.import("GLSL.std.450");
468 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
469 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700470 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600471
472 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600473 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
474 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600475 builder.addSourceExtension(it->c_str());
476
477 // Add the top-level modes for this shader.
478
479 if (glslangIntermediate->getXfbMode())
480 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
481
482 unsigned int mode;
483 switch (glslangIntermediate->getStage()) {
484 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600485 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600486 break;
487
488 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600489 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600490 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
491 break;
492
493 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600494 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600495 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700496 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
497 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
498 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600499 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600500 }
501 if (mode != spv::BadValue)
502 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
503
John Kesseniche6903322015-10-13 16:29:02 -0600504 switch (glslangIntermediate->getVertexSpacing()) {
505 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
506 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
507 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
508 default: mode = spv::BadValue; break;
509 }
510 if (mode != spv::BadValue)
511 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
512
513 switch (glslangIntermediate->getVertexOrder()) {
514 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
515 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
516 default: mode = spv::BadValue; break;
517 }
518 if (mode != spv::BadValue)
519 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
520
521 if (glslangIntermediate->getPointMode())
522 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600523 break;
524
525 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600526 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600527 switch (glslangIntermediate->getInputPrimitive()) {
528 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
529 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
530 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700531 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600532 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
533 default: mode = spv::BadValue; break;
534 }
535 if (mode != spv::BadValue)
536 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600537
John Kessenich140f3df2015-06-26 16:58:36 -0600538 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
539
540 switch (glslangIntermediate->getOutputPrimitive()) {
541 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
542 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
543 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
544 default: mode = spv::BadValue; break;
545 }
546 if (mode != spv::BadValue)
547 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
548 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
549 break;
550
551 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600552 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600553 if (glslangIntermediate->getPixelCenterInteger())
554 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600555
John Kessenich140f3df2015-06-26 16:58:36 -0600556 if (glslangIntermediate->getOriginUpperLeft())
557 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600558 else
559 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600560
561 if (glslangIntermediate->getEarlyFragmentTests())
562 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
563
564 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600565 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
566 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
567 default: mode = spv::BadValue; break;
568 }
569 if (mode != spv::BadValue)
570 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
571
572 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
573 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600574 break;
575
576 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600577 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600578 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
579 glslangIntermediate->getLocalSize(1),
580 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600581 break;
582
583 default:
584 break;
585 }
586
587}
588
John Kessenich7ba63412015-12-20 17:37:07 -0700589// Finish everything and dump
590void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
591{
592 // finish off the entry-point SPV instruction by adding the Input/Output <id>
593 for (auto it : iOSet)
594 entryPoint->addIdOperand(it);
595
596 builder.dump(out);
597}
598
John Kessenich140f3df2015-06-26 16:58:36 -0600599TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
600{
601 if (! mainTerminated) {
602 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
603 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600604 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600605 }
606}
607
608//
609// Implement the traversal functions.
610//
611// Return true from interior nodes to have the external traversal
612// continue on to children. Return false if children were
613// already processed.
614//
615
616//
617// Symbols can turn into
618// - uniform/input reads
619// - output writes
620// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
621// - something simple that degenerates into the last bullet
622//
623void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
624{
625 // getSymbolId() will set up all the IO decorations on the first call.
626 // Formal function parameters were mapped during makeFunctions().
627 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700628
629 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
630 if (builder.isPointer(id)) {
631 spv::StorageClass sc = builder.getStorageClass(id);
632 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
633 iOSet.insert(id);
634 }
635
636 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600637 if (! linkageOnly) {
638 // Prepare to generate code for the access
639
640 // L-value chains will be computed left to right. We're on the symbol now,
641 // which is the left-most part of the access chain, so now is "clear" time,
642 // followed by setting the base.
643 builder.clearAccessChain();
644
645 // For now, we consider all user variables as being in memory, so they are pointers,
646 // except for "const in" arguments to a function, which are an intermediate object.
647 // See comments in handleUserFunctionCall().
648 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
649 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
650 builder.setAccessChainRValue(id);
651 else
652 builder.setAccessChainLValue(id);
653 }
654}
655
656bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
657{
658 // First, handle special cases
659 switch (node->getOp()) {
660 case glslang::EOpAssign:
661 case glslang::EOpAddAssign:
662 case glslang::EOpSubAssign:
663 case glslang::EOpMulAssign:
664 case glslang::EOpVectorTimesMatrixAssign:
665 case glslang::EOpVectorTimesScalarAssign:
666 case glslang::EOpMatrixTimesScalarAssign:
667 case glslang::EOpMatrixTimesMatrixAssign:
668 case glslang::EOpDivAssign:
669 case glslang::EOpModAssign:
670 case glslang::EOpAndAssign:
671 case glslang::EOpInclusiveOrAssign:
672 case glslang::EOpExclusiveOrAssign:
673 case glslang::EOpLeftShiftAssign:
674 case glslang::EOpRightShiftAssign:
675 // A bin-op assign "a += b" means the same thing as "a = a + b"
676 // where a is evaluated before b. For a simple assignment, GLSL
677 // says to evaluate the left before the right. So, always, left
678 // node then right node.
679 {
680 // get the left l-value, save it away
681 builder.clearAccessChain();
682 node->getLeft()->traverse(this);
683 spv::Builder::AccessChain lValue = builder.getAccessChain();
684
685 // evaluate the right
686 builder.clearAccessChain();
687 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600688 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600689
690 if (node->getOp() != glslang::EOpAssign) {
691 // the left is also an r-value
692 builder.setAccessChain(lValue);
John Kessenichfa668da2015-09-13 14:46:30 -0600693 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600694
695 // do the operation
696 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
697 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
698 node->getType().getBasicType());
699
700 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700701 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600702 }
703
704 // store the result
705 builder.setAccessChain(lValue);
706 builder.accessChainStore(rValue);
707
708 // assignments are expressions having an rValue after they are evaluated...
709 builder.clearAccessChain();
710 builder.setAccessChainRValue(rValue);
711 }
712 return false;
713 case glslang::EOpIndexDirect:
714 case glslang::EOpIndexDirectStruct:
715 {
716 // Get the left part of the access chain.
717 node->getLeft()->traverse(this);
718
719 // Add the next element in the chain
720
John Kessenich55e7d112015-11-15 21:33:39 -0700721 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600722 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
723 // This may be, e.g., an anonymous block-member selection, which generally need
724 // index remapping due to hidden members in anonymous blocks.
725 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700726 assert(remapper.size() > 0);
727 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600728 }
729
730 if (! node->getLeft()->getType().isArray() &&
731 node->getLeft()->getType().isVector() &&
732 node->getOp() == glslang::EOpIndexDirect) {
733 // This is essentially a hard-coded vector swizzle of size 1,
734 // so short circuit the access-chain stuff with a swizzle.
735 std::vector<unsigned> swizzle;
736 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600737 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600738 } else {
739 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600740 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600741 }
742 }
743 return false;
744 case glslang::EOpIndexIndirect:
745 {
746 // Structure or array or vector indirection.
747 // Will use native SPIR-V access-chain for struct and array indirection;
748 // matrices are arrays of vectors, so will also work for a matrix.
749 // Will use the access chain's 'component' for variable index into a vector.
750
751 // This adapter is building access chains left to right.
752 // Set up the access chain to the left.
753 node->getLeft()->traverse(this);
754
755 // save it so that computing the right side doesn't trash it
756 spv::Builder::AccessChain partial = builder.getAccessChain();
757
758 // compute the next index in the chain
759 builder.clearAccessChain();
760 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600761 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600762
763 // restore the saved access chain
764 builder.setAccessChain(partial);
765
766 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600767 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600768 else
John Kessenichfa668da2015-09-13 14:46:30 -0600769 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600770 }
771 return false;
772 case glslang::EOpVectorSwizzle:
773 {
774 node->getLeft()->traverse(this);
775 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
776 std::vector<unsigned> swizzle;
777 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
778 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600779 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600780 }
781 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600782 case glslang::EOpLogicalOr:
783 case glslang::EOpLogicalAnd:
784 {
785
786 // These may require short circuiting, but can sometimes be done as straight
787 // binary operations. The right operand must be short circuited if it has
788 // side effects, and should probably be if it is complex.
789 if (isTrivial(node->getRight()->getAsTyped()))
790 break; // handle below as a normal binary operation
791 // otherwise, we need to do dynamic short circuiting on the right operand
792 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
793 builder.clearAccessChain();
794 builder.setAccessChainRValue(result);
795 }
796 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600797 default:
798 break;
799 }
800
801 // Assume generic binary op...
802
803 // Get the operands
804 builder.clearAccessChain();
805 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600806 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600807
808 builder.clearAccessChain();
809 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600810 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600811
812 spv::Id result;
813 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
814
815 result = createBinaryOperation(node->getOp(), precision,
816 convertGlslangToSpvType(node->getType()), left, right,
817 node->getLeft()->getType().getBasicType());
818
John Kessenich50e57562015-12-21 21:21:11 -0700819 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600820 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700821 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700822 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600823 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600824 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600825 return false;
826 }
John Kessenich140f3df2015-06-26 16:58:36 -0600827}
828
829bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
830{
John Kessenichfc51d282015-08-19 13:34:18 -0600831 spv::Id result = spv::NoResult;
832
833 // try texturing first
834 result = createImageTextureFunctionCall(node);
835 if (result != spv::NoResult) {
836 builder.clearAccessChain();
837 builder.setAccessChainRValue(result);
838
839 return false; // done with this node
840 }
841
842 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600843
844 if (node->getOp() == glslang::EOpArrayLength) {
845 // Quite special; won't want to evaluate the operand.
846
847 // Normal .length() would have been constant folded by the front-end.
848 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600849 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600850 assert(node->getOperand()->getType().isRuntimeSizedArray());
851 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
852 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600853 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
854 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600855
856 builder.clearAccessChain();
857 builder.setAccessChainRValue(length);
858
859 return false;
860 }
861
John Kessenichfc51d282015-08-19 13:34:18 -0600862 // Start by evaluating the operand
863
John Kessenich140f3df2015-06-26 16:58:36 -0600864 builder.clearAccessChain();
865 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800866
Rex Xufc618912015-09-09 16:42:49 +0800867 spv::Id operand = spv::NoResult;
868
869 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
870 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800871 node->getOp() == glslang::EOpAtomicCounter ||
872 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800873 operand = builder.accessChainGetLValue(); // Special case l-value operands
874 else
Rex Xu30f92582015-09-14 10:38:56 +0800875 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600876
877 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
878
879 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600880 if (! result)
881 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600882
883 // if not, then possibly an operation
884 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700885 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600886
887 if (result) {
888 builder.clearAccessChain();
889 builder.setAccessChainRValue(result);
890
891 return false; // done with this node
892 }
893
894 // it must be a special case, check...
895 switch (node->getOp()) {
896 case glslang::EOpPostIncrement:
897 case glslang::EOpPostDecrement:
898 case glslang::EOpPreIncrement:
899 case glslang::EOpPreDecrement:
900 {
901 // we need the integer value "1" or the floating point "1.0" to add/subtract
902 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
903 builder.makeFloatConstant(1.0F) :
904 builder.makeIntConstant(1);
905 glslang::TOperator op;
906 if (node->getOp() == glslang::EOpPreIncrement ||
907 node->getOp() == glslang::EOpPostIncrement)
908 op = glslang::EOpAdd;
909 else
910 op = glslang::EOpSub;
911
912 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
913 convertGlslangToSpvType(node->getType()), operand, one,
914 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700915 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600916
917 // The result of operation is always stored, but conditionally the
918 // consumed result. The consumed result is always an r-value.
919 builder.accessChainStore(result);
920 builder.clearAccessChain();
921 if (node->getOp() == glslang::EOpPreIncrement ||
922 node->getOp() == glslang::EOpPreDecrement)
923 builder.setAccessChainRValue(result);
924 else
925 builder.setAccessChainRValue(operand);
926 }
927
928 return false;
929
930 case glslang::EOpEmitStreamVertex:
931 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
932 return false;
933 case glslang::EOpEndStreamPrimitive:
934 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
935 return false;
936
937 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700938 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -0700939 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -0600940 }
John Kessenich140f3df2015-06-26 16:58:36 -0600941}
942
943bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
944{
John Kessenichfc51d282015-08-19 13:34:18 -0600945 spv::Id result = spv::NoResult;
946
947 // try texturing
948 result = createImageTextureFunctionCall(node);
949 if (result != spv::NoResult) {
950 builder.clearAccessChain();
951 builder.setAccessChainRValue(result);
952
953 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600954 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800955 // "imageStore" is a special case, which has no result
956 return false;
957 }
John Kessenichfc51d282015-08-19 13:34:18 -0600958
John Kessenich140f3df2015-06-26 16:58:36 -0600959 glslang::TOperator binOp = glslang::EOpNull;
960 bool reduceComparison = true;
961 bool isMatrix = false;
962 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600963 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600964
965 assert(node->getOp());
966
967 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
968
969 switch (node->getOp()) {
970 case glslang::EOpSequence:
971 {
972 if (preVisit)
973 ++sequenceDepth;
974 else
975 --sequenceDepth;
976
977 if (sequenceDepth == 1) {
978 // If this is the parent node of all the functions, we want to see them
979 // early, so all call points have actual SPIR-V functions to reference.
980 // In all cases, still let the traverser visit the children for us.
981 makeFunctions(node->getAsAggregate()->getSequence());
982
983 // Also, we want all globals initializers to go into the entry of main(), before
984 // anything else gets there, so visit out of order, doing them all now.
985 makeGlobalInitializers(node->getAsAggregate()->getSequence());
986
987 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
988 // so do them manually.
989 visitFunctions(node->getAsAggregate()->getSequence());
990
991 return false;
992 }
993
994 return true;
995 }
996 case glslang::EOpLinkerObjects:
997 {
998 if (visit == glslang::EvPreVisit)
999 linkageOnly = true;
1000 else
1001 linkageOnly = false;
1002
1003 return true;
1004 }
1005 case glslang::EOpComma:
1006 {
1007 // processing from left to right naturally leaves the right-most
1008 // lying around in the access chain
1009 glslang::TIntermSequence& glslangOperands = node->getSequence();
1010 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1011 glslangOperands[i]->traverse(this);
1012
1013 return false;
1014 }
1015 case glslang::EOpFunction:
1016 if (visit == glslang::EvPreVisit) {
1017 if (isShaderEntrypoint(node)) {
1018 inMain = true;
1019 builder.setBuildPoint(shaderEntry->getLastBlock());
1020 } else {
1021 handleFunctionEntry(node);
1022 }
1023 } else {
1024 if (inMain)
1025 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001026 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001027 inMain = false;
1028 }
1029
1030 return true;
1031 case glslang::EOpParameters:
1032 // Parameters will have been consumed by EOpFunction processing, but not
1033 // the body, so we still visited the function node's children, making this
1034 // child redundant.
1035 return false;
1036 case glslang::EOpFunctionCall:
1037 {
1038 if (node->isUserDefined())
1039 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001040 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001041 builder.clearAccessChain();
1042 builder.setAccessChainRValue(result);
1043
1044 return false;
1045 }
1046 case glslang::EOpConstructMat2x2:
1047 case glslang::EOpConstructMat2x3:
1048 case glslang::EOpConstructMat2x4:
1049 case glslang::EOpConstructMat3x2:
1050 case glslang::EOpConstructMat3x3:
1051 case glslang::EOpConstructMat3x4:
1052 case glslang::EOpConstructMat4x2:
1053 case glslang::EOpConstructMat4x3:
1054 case glslang::EOpConstructMat4x4:
1055 case glslang::EOpConstructDMat2x2:
1056 case glslang::EOpConstructDMat2x3:
1057 case glslang::EOpConstructDMat2x4:
1058 case glslang::EOpConstructDMat3x2:
1059 case glslang::EOpConstructDMat3x3:
1060 case glslang::EOpConstructDMat3x4:
1061 case glslang::EOpConstructDMat4x2:
1062 case glslang::EOpConstructDMat4x3:
1063 case glslang::EOpConstructDMat4x4:
1064 isMatrix = true;
1065 // fall through
1066 case glslang::EOpConstructFloat:
1067 case glslang::EOpConstructVec2:
1068 case glslang::EOpConstructVec3:
1069 case glslang::EOpConstructVec4:
1070 case glslang::EOpConstructDouble:
1071 case glslang::EOpConstructDVec2:
1072 case glslang::EOpConstructDVec3:
1073 case glslang::EOpConstructDVec4:
1074 case glslang::EOpConstructBool:
1075 case glslang::EOpConstructBVec2:
1076 case glslang::EOpConstructBVec3:
1077 case glslang::EOpConstructBVec4:
1078 case glslang::EOpConstructInt:
1079 case glslang::EOpConstructIVec2:
1080 case glslang::EOpConstructIVec3:
1081 case glslang::EOpConstructIVec4:
1082 case glslang::EOpConstructUint:
1083 case glslang::EOpConstructUVec2:
1084 case glslang::EOpConstructUVec3:
1085 case glslang::EOpConstructUVec4:
1086 case glslang::EOpConstructStruct:
1087 {
1088 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001089 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001090 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1091 spv::Id constructed;
1092 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1093 std::vector<spv::Id> constituents;
1094 for (int c = 0; c < (int)arguments.size(); ++c)
1095 constituents.push_back(arguments[c]);
1096 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001097 } else if (isMatrix)
1098 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1099 else
1100 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001101
1102 builder.clearAccessChain();
1103 builder.setAccessChainRValue(constructed);
1104
1105 return false;
1106 }
1107
1108 // These six are component-wise compares with component-wise results.
1109 // Forward on to createBinaryOperation(), requesting a vector result.
1110 case glslang::EOpLessThan:
1111 case glslang::EOpGreaterThan:
1112 case glslang::EOpLessThanEqual:
1113 case glslang::EOpGreaterThanEqual:
1114 case glslang::EOpVectorEqual:
1115 case glslang::EOpVectorNotEqual:
1116 {
1117 // Map the operation to a binary
1118 binOp = node->getOp();
1119 reduceComparison = false;
1120 switch (node->getOp()) {
1121 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1122 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1123 default: binOp = node->getOp(); break;
1124 }
1125
1126 break;
1127 }
1128 case glslang::EOpMul:
1129 // compontent-wise matrix multiply
1130 binOp = glslang::EOpMul;
1131 break;
1132 case glslang::EOpOuterProduct:
1133 // two vectors multiplied to make a matrix
1134 binOp = glslang::EOpOuterProduct;
1135 break;
1136 case glslang::EOpDot:
1137 {
1138 // for scalar dot product, use multiply
1139 glslang::TIntermSequence& glslangOperands = node->getSequence();
1140 if (! glslangOperands[0]->getAsTyped()->isVector())
1141 binOp = glslang::EOpMul;
1142 break;
1143 }
1144 case glslang::EOpMod:
1145 // when an aggregate, this is the floating-point mod built-in function,
1146 // which can be emitted by the one in createBinaryOperation()
1147 binOp = glslang::EOpMod;
1148 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001149 case glslang::EOpEmitVertex:
1150 case glslang::EOpEndPrimitive:
1151 case glslang::EOpBarrier:
1152 case glslang::EOpMemoryBarrier:
1153 case glslang::EOpMemoryBarrierAtomicCounter:
1154 case glslang::EOpMemoryBarrierBuffer:
1155 case glslang::EOpMemoryBarrierImage:
1156 case glslang::EOpMemoryBarrierShared:
1157 case glslang::EOpGroupMemoryBarrier:
1158 noReturnValue = true;
1159 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1160 break;
1161
John Kessenich426394d2015-07-23 10:22:48 -06001162 case glslang::EOpAtomicAdd:
1163 case glslang::EOpAtomicMin:
1164 case glslang::EOpAtomicMax:
1165 case glslang::EOpAtomicAnd:
1166 case glslang::EOpAtomicOr:
1167 case glslang::EOpAtomicXor:
1168 case glslang::EOpAtomicExchange:
1169 case glslang::EOpAtomicCompSwap:
1170 atomic = true;
1171 break;
1172
John Kessenich140f3df2015-06-26 16:58:36 -06001173 default:
1174 break;
1175 }
1176
1177 //
1178 // See if it maps to a regular operation.
1179 //
John Kessenich140f3df2015-06-26 16:58:36 -06001180 if (binOp != glslang::EOpNull) {
1181 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1182 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1183 assert(left && right);
1184
1185 builder.clearAccessChain();
1186 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001187 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001188
1189 builder.clearAccessChain();
1190 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001191 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001192
1193 result = createBinaryOperation(binOp, precision,
1194 convertGlslangToSpvType(node->getType()), leftId, rightId,
1195 left->getType().getBasicType(), reduceComparison);
1196
1197 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001198 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001199 builder.clearAccessChain();
1200 builder.setAccessChainRValue(result);
1201
1202 return false;
1203 }
1204
John Kessenich426394d2015-07-23 10:22:48 -06001205 //
1206 // Create the list of operands.
1207 //
John Kessenich140f3df2015-06-26 16:58:36 -06001208 glslang::TIntermSequence& glslangOperands = node->getSequence();
1209 std::vector<spv::Id> operands;
1210 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1211 builder.clearAccessChain();
1212 glslangOperands[arg]->traverse(this);
1213
1214 // special case l-value operands; there are just a few
1215 bool lvalue = false;
1216 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001217 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001218 case glslang::EOpModf:
1219 if (arg == 1)
1220 lvalue = true;
1221 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001222 case glslang::EOpInterpolateAtSample:
1223 case glslang::EOpInterpolateAtOffset:
1224 if (arg == 0)
1225 lvalue = true;
1226 break;
Rex Xud4782c12015-09-06 16:30:11 +08001227 case glslang::EOpAtomicAdd:
1228 case glslang::EOpAtomicMin:
1229 case glslang::EOpAtomicMax:
1230 case glslang::EOpAtomicAnd:
1231 case glslang::EOpAtomicOr:
1232 case glslang::EOpAtomicXor:
1233 case glslang::EOpAtomicExchange:
1234 case glslang::EOpAtomicCompSwap:
1235 if (arg == 0)
1236 lvalue = true;
1237 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001238 case glslang::EOpAddCarry:
1239 case glslang::EOpSubBorrow:
1240 if (arg == 2)
1241 lvalue = true;
1242 break;
1243 case glslang::EOpUMulExtended:
1244 case glslang::EOpIMulExtended:
1245 if (arg >= 2)
1246 lvalue = true;
1247 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001248 default:
1249 break;
1250 }
1251 if (lvalue)
1252 operands.push_back(builder.accessChainGetLValue());
1253 else
John Kessenichfa668da2015-09-13 14:46:30 -06001254 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001255 }
John Kessenich426394d2015-07-23 10:22:48 -06001256
1257 if (atomic) {
1258 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001259 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001260 } else {
1261 // Pass through to generic operations.
1262 switch (glslangOperands.size()) {
1263 case 0:
1264 result = createNoArgOperation(node->getOp());
1265 break;
1266 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001267 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001268 break;
1269 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001270 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001271 break;
1272 }
John Kessenich140f3df2015-06-26 16:58:36 -06001273 }
1274
1275 if (noReturnValue)
1276 return false;
1277
1278 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001279 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001280 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001281 } else {
1282 builder.clearAccessChain();
1283 builder.setAccessChainRValue(result);
1284 return false;
1285 }
1286}
1287
1288bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1289{
1290 // This path handles both if-then-else and ?:
1291 // The if-then-else has a node type of void, while
1292 // ?: has a non-void node type
1293 spv::Id result = 0;
1294 if (node->getBasicType() != glslang::EbtVoid) {
1295 // don't handle this as just on-the-fly temporaries, because there will be two names
1296 // and better to leave SSA to later passes
1297 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1298 }
1299
1300 // emit the condition before doing anything with selection
1301 node->getCondition()->traverse(this);
1302
1303 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001304 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001305
1306 if (node->getTrueBlock()) {
1307 // emit the "then" statement
1308 node->getTrueBlock()->traverse(this);
1309 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001310 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001311 }
1312
1313 if (node->getFalseBlock()) {
1314 ifBuilder.makeBeginElse();
1315 // emit the "else" statement
1316 node->getFalseBlock()->traverse(this);
1317 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001318 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001319 }
1320
1321 ifBuilder.makeEndIf();
1322
1323 if (result) {
1324 // GLSL only has r-values as the result of a :?, but
1325 // if we have an l-value, that can be more efficient if it will
1326 // become the base of a complex r-value expression, because the
1327 // next layer copies r-values into memory to use the access-chain mechanism
1328 builder.clearAccessChain();
1329 builder.setAccessChainLValue(result);
1330 }
1331
1332 return false;
1333}
1334
1335bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1336{
1337 // emit and get the condition before doing anything with switch
1338 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001339 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001340
1341 // browse the children to sort out code segments
1342 int defaultSegment = -1;
1343 std::vector<TIntermNode*> codeSegments;
1344 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1345 std::vector<int> caseValues;
1346 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1347 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1348 TIntermNode* child = *c;
1349 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001350 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001351 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001352 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001353 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1354 } else
1355 codeSegments.push_back(child);
1356 }
1357
1358 // handle the case where the last code segment is missing, due to no code
1359 // statements between the last case and the end of the switch statement
1360 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1361 (int)codeSegments.size() == defaultSegment)
1362 codeSegments.push_back(nullptr);
1363
1364 // make the switch statement
1365 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001366 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001367
1368 // emit all the code in the segments
1369 breakForLoop.push(false);
1370 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1371 builder.nextSwitchSegment(segmentBlocks, s);
1372 if (codeSegments[s])
1373 codeSegments[s]->traverse(this);
1374 else
1375 builder.addSwitchBreak();
1376 }
1377 breakForLoop.pop();
1378
1379 builder.endSwitch(segmentBlocks);
1380
1381 return false;
1382}
1383
1384void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1385{
1386 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001387 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001388
1389 builder.clearAccessChain();
1390 builder.setAccessChainRValue(constant);
1391}
1392
1393bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1394{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001395 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001396 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001397 // Spec requires back edges to target header blocks, and every header block
1398 // must dominate its merge block. Make a header block first to ensure these
1399 // conditions are met. By definition, it will contain OpLoopMerge, followed
1400 // by a block-ending branch. But we don't want to put any other body/test
1401 // instructions in it, since the body/test may have arbitrary instructions,
1402 // including merges of its own.
1403 builder.setBuildPoint(&blocks.head);
1404 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001405 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001406 spv::Block& test = builder.makeNewBlock();
1407 builder.createBranch(&test);
1408
1409 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001410 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001411 spv::Id condition =
1412 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001413 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1414
1415 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001416 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001417 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001418 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001419 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001420 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001421
1422 builder.setBuildPoint(&blocks.continue_target);
1423 if (node->getTerminal())
1424 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001425 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001426 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001427 builder.createBranch(&blocks.body);
1428
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001429 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001430 builder.setBuildPoint(&blocks.body);
1431 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001432 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001433 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001434 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001435
1436 builder.setBuildPoint(&blocks.continue_target);
1437 if (node->getTerminal())
1438 node->getTerminal()->traverse(this);
1439 if (node->getTest()) {
1440 node->getTest()->traverse(this);
1441 spv::Id condition =
1442 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001443 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001444 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001445 // TODO: unless there was a break/return/discard instruction
1446 // somewhere in the body, this is an infinite loop, so we should
1447 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001448 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001449 }
John Kessenich140f3df2015-06-26 16:58:36 -06001450 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001451 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001452 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001453 return false;
1454}
1455
1456bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1457{
1458 if (node->getExpression())
1459 node->getExpression()->traverse(this);
1460
1461 switch (node->getFlowOp()) {
1462 case glslang::EOpKill:
1463 builder.makeDiscard();
1464 break;
1465 case glslang::EOpBreak:
1466 if (breakForLoop.top())
1467 builder.createLoopExit();
1468 else
1469 builder.addSwitchBreak();
1470 break;
1471 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001472 builder.createLoopContinue();
1473 break;
1474 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001475 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001476 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001477 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001478 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001479
1480 builder.clearAccessChain();
1481 break;
1482
1483 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001484 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001485 break;
1486 }
1487
1488 return false;
1489}
1490
1491spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1492{
1493 // First, steer off constants, which are not SPIR-V variables, but
1494 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001495 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001496 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001497 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001498 }
1499
1500 // Now, handle actual variables
1501 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1502 spv::Id spvType = convertGlslangToSpvType(node->getType());
1503
1504 const char* name = node->getName().c_str();
1505 if (glslang::IsAnonymous(name))
1506 name = "";
1507
1508 return builder.createVariable(storageClass, spvType, name);
1509}
1510
1511// Return type Id of the sampled type.
1512spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1513{
1514 switch (sampler.type) {
1515 case glslang::EbtFloat: return builder.makeFloatType(32);
1516 case glslang::EbtInt: return builder.makeIntType(32);
1517 case glslang::EbtUint: return builder.makeUintType(32);
1518 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001519 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001520 return builder.makeFloatType(32);
1521 }
1522}
1523
John Kessenich3ac051e2015-12-20 11:29:16 -07001524// Convert from a glslang type to an SPV type, by calling into a
1525// recursive version of this function. This establishes the inherited
1526// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001527spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1528{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001529 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001530}
1531
1532// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001533// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001534spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001535{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001536 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001537
1538 switch (type.getBasicType()) {
1539 case glslang::EbtVoid:
1540 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001541 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001542 break;
1543 case glslang::EbtFloat:
1544 spvType = builder.makeFloatType(32);
1545 break;
1546 case glslang::EbtDouble:
1547 spvType = builder.makeFloatType(64);
1548 break;
1549 case glslang::EbtBool:
1550 spvType = builder.makeBoolType();
1551 break;
1552 case glslang::EbtInt:
1553 spvType = builder.makeIntType(32);
1554 break;
1555 case glslang::EbtUint:
1556 spvType = builder.makeUintType(32);
1557 break;
John Kessenich426394d2015-07-23 10:22:48 -06001558 case glslang::EbtAtomicUint:
1559 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1560 spvType = builder.makeUintType(32);
1561 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001562 case glslang::EbtSampler:
1563 {
1564 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001565 // an image is present, make its type
1566 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1567 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001568 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001569 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001570 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001571 }
John Kessenich140f3df2015-06-26 16:58:36 -06001572 break;
1573 case glslang::EbtStruct:
1574 case glslang::EbtBlock:
1575 {
1576 // If we've seen this struct type, return it
1577 const glslang::TTypeList* glslangStruct = type.getStruct();
1578 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001579
1580 // Try to share structs for different layouts, but not yet for other
1581 // kinds of qualification (primarily not yet including interpolant qualification).
1582 if (! HasNonLayoutQualifiers(qualifier))
1583 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1584 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001585 break;
1586
1587 // else, we haven't seen it...
1588
1589 // Create a vector of struct types for SPIR-V to consume
1590 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1591 if (type.getBasicType() == glslang::EbtBlock)
1592 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001593 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001594 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1595 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1596 if (glslangType.hiddenMember()) {
1597 ++memberDelta;
1598 if (type.getBasicType() == glslang::EbtBlock)
1599 memberRemapper[glslangStruct][i] = -1;
1600 } else {
1601 if (type.getBasicType() == glslang::EbtBlock)
1602 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001603 // modify just this child's view of the qualifier
1604 glslang::TQualifier subQualifier = glslangType.getQualifier();
1605 InheritQualifiers(subQualifier, qualifier);
John Kessenich7b9fa252016-01-21 18:56:57 -07001606 if (qualifier.hasLocation()) {
1607 subQualifier.layoutLocation += locationOffset;
1608 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1609 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001610 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001611 }
1612 }
1613
1614 // Make the SPIR-V type
1615 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001616 if (! HasNonLayoutQualifiers(qualifier))
1617 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001618
1619 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001620 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001621 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001622 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1623 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1624 int member = i;
1625 if (type.getBasicType() == glslang::EbtBlock)
1626 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001627
John Kesseniche0b6cad2015-12-24 10:30:13 -07001628 // modify just this child's view of the qualifier
1629 glslang::TQualifier subQualifier = glslangType.getQualifier();
1630 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001631
John Kessenich140f3df2015-06-26 16:58:36 -06001632 // using -1 above to indicate a hidden member
1633 if (member >= 0) {
1634 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001635 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001636 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001637 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1638 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich7b9fa252016-01-21 18:56:57 -07001639 if (qualifier.hasLocation()) {
1640 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, qualifier.layoutLocation + locationOffset);
1641 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1642 }
John Kessenich140f3df2015-06-26 16:58:36 -06001643 if (glslangType.getQualifier().hasComponent())
1644 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1645 if (glslangType.getQualifier().hasXfbOffset())
1646 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001647 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001648 // figure out what to do with offset, which is accumulating
1649 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001650 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001651 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001652 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001653 offset = nextOffset;
1654 }
John Kessenich140f3df2015-06-26 16:58:36 -06001655
John Kessenichf85e8062015-12-19 13:57:10 -07001656 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001657 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001658
John Kessenich140f3df2015-06-26 16:58:36 -06001659 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001660 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1661 if (builtIn != spv::BadValue)
1662 builder.addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001663 }
1664 }
1665
1666 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001667 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001668 addDecoration(spvType, TranslateBlockDecoration(type));
1669 if (type.getQualifier().hasStream())
1670 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
1671 if (glslangIntermediate->getXfbMode()) {
1672 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001673 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001674 if (type.getQualifier().hasXfbBuffer())
1675 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1676 }
1677 }
1678 break;
1679 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001680 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001681 break;
1682 }
1683
1684 if (type.isMatrix())
1685 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1686 else {
1687 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1688 if (type.getVectorSize() > 1)
1689 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1690 }
1691
1692 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001693 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1694
John Kessenichc9a80832015-09-12 12:17:44 -06001695 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001696 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001697 // We need to decorate array strides for types needing explicit layout, except blocks.
1698 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001699 // Use a dummy glslang type for querying internal strides of
1700 // arrays of arrays, but using just a one-dimensional array.
1701 glslang::TType simpleArrayType(type, 0); // deference type of the array
1702 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1703 simpleArrayType.getArraySizes().dereference();
1704
1705 // Will compute the higher-order strides here, rather than making a whole
1706 // pile of types and doing repetitive recursion on their contents.
1707 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1708 }
John Kessenichf8842e52016-01-04 19:22:56 -07001709
1710 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001711 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1712 int size = type.getArraySizes()->getDimSize(dim);
1713 assert(size > 0);
1714 spvType = builder.makeArrayType(spvType, size, stride);
1715 if (stride > 0)
1716 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1717 stride *= size;
1718 }
1719 } else {
1720 // single-dimensional array, and don't yet have stride
1721
John Kessenichf8842e52016-01-04 19:22:56 -07001722 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001723 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1724 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001725 }
John Kessenich31ed4832015-09-09 17:51:38 -06001726
John Kessenichc9a80832015-09-12 12:17:44 -06001727 // Do the outer dimension, which might not be known for a runtime-sized array
1728 if (type.isRuntimeSizedArray()) {
1729 spvType = builder.makeRuntimeArray(spvType);
1730 } else {
1731 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001732 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001733 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001734 if (stride > 0)
1735 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001736 }
1737
1738 return spvType;
1739}
1740
John Kessenichf85e8062015-12-19 13:57:10 -07001741// Decide whether or not this type should be
1742// decorated with offsets and strides, and if so
1743// whether std140 or std430 rules should be applied.
1744glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001745{
John Kessenichf85e8062015-12-19 13:57:10 -07001746 // has to be a block
1747 if (type.getBasicType() != glslang::EbtBlock)
1748 return glslang::ElpNone;
1749
1750 // has to be a uniform or buffer block
1751 if (type.getQualifier().storage != glslang::EvqUniform &&
1752 type.getQualifier().storage != glslang::EvqBuffer)
1753 return glslang::ElpNone;
1754
1755 // return the layout to use
1756 switch (type.getQualifier().layoutPacking) {
1757 case glslang::ElpStd140:
1758 case glslang::ElpStd430:
1759 return type.getQualifier().layoutPacking;
1760 default:
1761 return glslang::ElpNone;
1762 }
John Kessenich31ed4832015-09-09 17:51:38 -06001763}
1764
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001765// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001766int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001767{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001768 int size;
John Kessenich49987892015-12-29 17:11:44 -07001769 int stride;
1770 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001771
1772 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001773}
1774
John Kessenich49987892015-12-29 17:11:44 -07001775// 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 -07001776// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001777int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001778{
John Kessenich49987892015-12-29 17:11:44 -07001779 glslang::TType elementType;
1780 elementType.shallowCopy(matrixType);
1781 elementType.clearArraySizes();
1782
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001783 int size;
John Kessenich49987892015-12-29 17:11:44 -07001784 int stride;
1785 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1786
1787 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001788}
1789
John Kessenich5e4b1242015-08-06 22:53:06 -06001790// Given a member type of a struct, realign the current offset for it, and compute
1791// the next (not yet aligned) offset for the next member, which will get aligned
1792// on the next call.
1793// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1794// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1795// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001796void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001797 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001798{
1799 // this will get a positive value when deemed necessary
1800 nextOffset = -1;
1801
John Kessenich5e4b1242015-08-06 22:53:06 -06001802 // override anything in currentOffset with user-set offset
1803 if (memberType.getQualifier().hasOffset())
1804 currentOffset = memberType.getQualifier().layoutOffset;
1805
1806 // It could be that current linker usage in glslang updated all the layoutOffset,
1807 // in which case the following code does not matter. But, that's not quite right
1808 // once cross-compilation unit GLSL validation is done, as the original user
1809 // settings are needed in layoutOffset, and then the following will come into play.
1810
John Kessenichf85e8062015-12-19 13:57:10 -07001811 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001812 if (! memberType.getQualifier().hasOffset())
1813 currentOffset = -1;
1814
1815 return;
1816 }
1817
John Kessenichf85e8062015-12-19 13:57:10 -07001818 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001819 if (currentOffset < 0)
1820 currentOffset = 0;
1821
1822 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1823 // but possibly not yet correctly aligned.
1824
1825 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001826 int dummyStride;
1827 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001828 glslang::RoundToPow2(currentOffset, memberAlignment);
1829 nextOffset = currentOffset + memberSize;
1830}
1831
John Kessenich140f3df2015-06-26 16:58:36 -06001832bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1833{
1834 return node->getName() == "main(";
1835}
1836
1837// Make all the functions, skeletally, without actually visiting their bodies.
1838void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1839{
1840 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1841 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1842 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1843 continue;
1844
1845 // We're on a user function. Set up the basic interface for the function now,
1846 // so that it's available to call.
1847 // Translating the body will happen later.
1848 //
1849 // Typically (except for a "const in" parameter), an address will be passed to the
1850 // function. What it is an address of varies:
1851 //
1852 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1853 // so that write needs to be to a copy, hence the address of a copy works.
1854 //
1855 // - "const in" parameters can just be the r-value, as no writes need occur.
1856 //
1857 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1858 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1859
1860 std::vector<spv::Id> paramTypes;
1861 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1862
1863 for (int p = 0; p < (int)parameters.size(); ++p) {
1864 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1865 spv::Id typeId = convertGlslangToSpvType(paramType);
1866 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1867 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1868 else
1869 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1870 paramTypes.push_back(typeId);
1871 }
1872
1873 spv::Block* functionBlock;
1874 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1875 paramTypes, &functionBlock);
1876
1877 // Track function to emit/call later
1878 functionMap[glslFunction->getName().c_str()] = function;
1879
1880 // Set the parameter id's
1881 for (int p = 0; p < (int)parameters.size(); ++p) {
1882 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1883 // give a name too
1884 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1885 }
1886 }
1887}
1888
1889// Process all the initializers, while skipping the functions and link objects
1890void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1891{
1892 builder.setBuildPoint(shaderEntry->getLastBlock());
1893 for (int i = 0; i < (int)initializers.size(); ++i) {
1894 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1895 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1896
1897 // We're on a top-level node that's not a function. Treat as an initializer, whose
1898 // code goes into the beginning of main.
1899 initializer->traverse(this);
1900 }
1901 }
1902}
1903
1904// Process all the functions, while skipping initializers.
1905void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1906{
1907 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1908 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1909 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1910 node->traverse(this);
1911 }
1912}
1913
1914void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1915{
1916 // SPIR-V functions should already be in the functionMap from the prepass
1917 // that called makeFunctions().
1918 spv::Function* function = functionMap[node->getName().c_str()];
1919 spv::Block* functionBlock = function->getEntryBlock();
1920 builder.setBuildPoint(functionBlock);
1921}
1922
Rex Xu04db3f52015-09-16 11:44:02 +08001923void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001924{
Rex Xufc618912015-09-09 16:42:49 +08001925 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08001926
1927 glslang::TSampler sampler = {};
1928 bool cubeCompare = false;
1929 if (node.isTexture()) {
1930 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
1931 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1932 }
1933
John Kessenich140f3df2015-06-26 16:58:36 -06001934 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1935 builder.clearAccessChain();
1936 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001937
1938 // Special case l-value operands
1939 bool lvalue = false;
1940 switch (node.getOp()) {
1941 case glslang::EOpImageAtomicAdd:
1942 case glslang::EOpImageAtomicMin:
1943 case glslang::EOpImageAtomicMax:
1944 case glslang::EOpImageAtomicAnd:
1945 case glslang::EOpImageAtomicOr:
1946 case glslang::EOpImageAtomicXor:
1947 case glslang::EOpImageAtomicExchange:
1948 case glslang::EOpImageAtomicCompSwap:
1949 if (i == 0)
1950 lvalue = true;
1951 break;
Rex Xu48edadf2015-12-31 16:11:41 +08001952 case glslang::EOpSparseTexture:
1953 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
1954 lvalue = true;
1955 break;
1956 case glslang::EOpSparseTextureClamp:
1957 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
1958 lvalue = true;
1959 break;
1960 case glslang::EOpSparseTextureLod:
1961 case glslang::EOpSparseTextureOffset:
1962 if (i == 3)
1963 lvalue = true;
1964 break;
1965 case glslang::EOpSparseTextureFetch:
1966 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
1967 lvalue = true;
1968 break;
1969 case glslang::EOpSparseTextureFetchOffset:
1970 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
1971 lvalue = true;
1972 break;
1973 case glslang::EOpSparseTextureLodOffset:
1974 case glslang::EOpSparseTextureGrad:
1975 case glslang::EOpSparseTextureOffsetClamp:
1976 if (i == 4)
1977 lvalue = true;
1978 break;
1979 case glslang::EOpSparseTextureGradOffset:
1980 case glslang::EOpSparseTextureGradClamp:
1981 if (i == 5)
1982 lvalue = true;
1983 break;
1984 case glslang::EOpSparseTextureGradOffsetClamp:
1985 if (i == 6)
1986 lvalue = true;
1987 break;
1988 case glslang::EOpSparseTextureGather:
1989 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
1990 lvalue = true;
1991 break;
1992 case glslang::EOpSparseTextureGatherOffset:
1993 case glslang::EOpSparseTextureGatherOffsets:
1994 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
1995 lvalue = true;
1996 break;
Rex Xufc618912015-09-09 16:42:49 +08001997 default:
1998 break;
1999 }
2000
Rex Xu6b86d492015-09-16 17:48:22 +08002001 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002002 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002003 else
Rex Xu30f92582015-09-14 10:38:56 +08002004 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06002005 }
2006}
2007
John Kessenichfc51d282015-08-19 13:34:18 -06002008void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002009{
John Kessenichfc51d282015-08-19 13:34:18 -06002010 builder.clearAccessChain();
2011 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002012 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06002013}
John Kessenich140f3df2015-06-26 16:58:36 -06002014
John Kessenichfc51d282015-08-19 13:34:18 -06002015spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2016{
Rex Xufc618912015-09-09 16:42:49 +08002017 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002018 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002019 }
2020
John Kessenichfc51d282015-08-19 13:34:18 -06002021 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002022 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2023 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2024 std::vector<spv::Id> arguments;
2025 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002026 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002027 else
2028 translateArguments(*node->getAsUnaryNode(), arguments);
2029 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2030
2031 spv::Builder::TextureParameters params = { };
2032 params.sampler = arguments[0];
2033
Rex Xu04db3f52015-09-16 11:44:02 +08002034 glslang::TCrackedTextureOp cracked;
2035 node->crackTexture(sampler, cracked);
2036
John Kessenichfc51d282015-08-19 13:34:18 -06002037 // Check for queries
2038 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002039 // a sampled image needs to have the image extracted first
2040 if (builder.isSampledImage(params.sampler))
2041 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002042 switch (node->getOp()) {
2043 case glslang::EOpImageQuerySize:
2044 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002045 if (arguments.size() > 1) {
2046 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002047 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002048 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002049 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002050 case glslang::EOpImageQuerySamples:
2051 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002052 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002053 case glslang::EOpTextureQueryLod:
2054 params.coords = arguments[1];
2055 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2056 case glslang::EOpTextureQueryLevels:
2057 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002058 case glslang::EOpSparseTexelsResident:
2059 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002060 default:
2061 assert(0);
2062 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002063 }
John Kessenich140f3df2015-06-26 16:58:36 -06002064 }
2065
Rex Xufc618912015-09-09 16:42:49 +08002066 // Check for image functions other than queries
2067 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002068 std::vector<spv::Id> operands;
2069 auto opIt = arguments.begin();
2070 operands.push_back(*(opIt++));
2071 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002072 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002073 if (sampler.ms) {
2074 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002075 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002076 }
John Kessenich56bab042015-09-16 10:54:31 -06002077 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2078 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002079 if (sampler.ms) {
2080 operands.push_back(*(opIt + 1));
2081 operands.push_back(spv::ImageOperandsSampleMask);
2082 operands.push_back(*opIt);
2083 } else
2084 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002085 builder.createNoResultOp(spv::OpImageWrite, operands);
2086 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002087 } else if (node->isSparseImage()) {
2088 spv::MissingFunctionality("sparse image functions");
2089 return spv::NoResult;
2090 }
2091 else {
Rex Xu6b86d492015-09-16 17:48:22 +08002092 // Process image atomic operations
2093
2094 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2095 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenich56bab042015-09-16 10:54:31 -06002096 operands.push_back(sampler.ms ? *(opIt++) : 0); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002097
Rex Xufc618912015-09-09 16:42:49 +08002098 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002099 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002100
2101 std::vector<spv::Id> operands;
2102 operands.push_back(pointer);
2103 for (; opIt != arguments.end(); ++opIt)
2104 operands.push_back(*opIt);
2105
Rex Xu04db3f52015-09-16 11:44:02 +08002106 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002107 }
2108 }
2109
2110 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002111 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002112 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2113
John Kessenichfc51d282015-08-19 13:34:18 -06002114 // check for bias argument
2115 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002116 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002117 int nonBiasArgCount = 2;
2118 if (cracked.offset)
2119 ++nonBiasArgCount;
2120 if (cracked.grad)
2121 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002122 if (cracked.lodClamp)
2123 ++nonBiasArgCount;
2124 if (sparse)
2125 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002126
2127 if ((int)arguments.size() > nonBiasArgCount)
2128 bias = true;
2129 }
2130
John Kessenichfc51d282015-08-19 13:34:18 -06002131 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002132
John Kessenichfc51d282015-08-19 13:34:18 -06002133 params.coords = arguments[1];
2134 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002135
2136 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002137 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002138 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002139 ++extraArgs;
2140 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002141 params.Dref = arguments[2];
2142 ++extraArgs;
2143 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002144 std::vector<spv::Id> indexes;
2145 int comp;
2146 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002147 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002148 else
2149 comp = builder.getNumComponents(params.coords) - 1;
2150 indexes.push_back(comp);
2151 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2152 }
2153 if (cracked.lod) {
2154 params.lod = arguments[2];
2155 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002156 } else if (sampler.ms) {
2157 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002158 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002159 }
2160 if (cracked.grad) {
2161 params.gradX = arguments[2 + extraArgs];
2162 params.gradY = arguments[3 + extraArgs];
2163 extraArgs += 2;
2164 }
John Kessenich55e7d112015-11-15 21:33:39 -07002165 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002166 params.offset = arguments[2 + extraArgs];
2167 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002168 } else if (cracked.offsets) {
2169 params.offsets = arguments[2 + extraArgs];
2170 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002171 }
Rex Xu48edadf2015-12-31 16:11:41 +08002172 if (cracked.lodClamp) {
2173 params.lodClamp = arguments[2 + extraArgs];
2174 ++extraArgs;
2175 }
2176 if (sparse) {
2177 params.texelOut = arguments[2 + extraArgs];
2178 ++extraArgs;
2179 }
John Kessenichfc51d282015-08-19 13:34:18 -06002180 if (bias) {
2181 params.bias = arguments[2 + extraArgs];
2182 ++extraArgs;
2183 }
John Kessenich55e7d112015-11-15 21:33:39 -07002184 if (cracked.gather && ! sampler.shadow) {
2185 // default component is 0, if missing, otherwise an argument
2186 if (2 + extraArgs < (int)arguments.size()) {
2187 params.comp = arguments[2 + extraArgs];
2188 ++extraArgs;
2189 } else {
2190 params.comp = builder.makeIntConstant(0);
2191 }
2192 }
John Kessenichfc51d282015-08-19 13:34:18 -06002193
Rex Xu48edadf2015-12-31 16:11:41 +08002194 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002195}
2196
2197spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2198{
2199 // Grab the function's pointer from the previously created function
2200 spv::Function* function = functionMap[node->getName().c_str()];
2201 if (! function)
2202 return 0;
2203
2204 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2205 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2206
2207 // See comments in makeFunctions() for details about the semantics for parameter passing.
2208 //
2209 // These imply we need a four step process:
2210 // 1. Evaluate the arguments
2211 // 2. Allocate and make copies of in, out, and inout arguments
2212 // 3. Make the call
2213 // 4. Copy back the results
2214
2215 // 1. Evaluate the arguments
2216 std::vector<spv::Builder::AccessChain> lValues;
2217 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002218 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002219 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2220 // build l-value
2221 builder.clearAccessChain();
2222 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002223 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002224 // keep outputs as l-values, evaluate input-only as r-values
2225 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2226 // save l-value
2227 lValues.push_back(builder.getAccessChain());
2228 } else {
2229 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002230 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002231 }
2232 }
2233
2234 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2235 // copy the original into that space.
2236 //
2237 // Also, build up the list of actual arguments to pass in for the call
2238 int lValueCount = 0;
2239 int rValueCount = 0;
2240 std::vector<spv::Id> spvArgs;
2241 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2242 spv::Id arg;
2243 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2244 // need space to hold the copy
2245 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2246 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2247 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2248 // need to copy the input into output space
2249 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002250 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002251 builder.createStore(copy, arg);
2252 }
2253 ++lValueCount;
2254 } else {
2255 arg = rValues[rValueCount];
2256 ++rValueCount;
2257 }
2258 spvArgs.push_back(arg);
2259 }
2260
2261 // 3. Make the call.
2262 spv::Id result = builder.createFunctionCall(function, spvArgs);
2263
2264 // 4. Copy back out an "out" arguments.
2265 lValueCount = 0;
2266 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2267 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2268 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2269 spv::Id copy = builder.createLoad(spvArgs[a]);
2270 builder.setAccessChain(lValues[lValueCount]);
2271 builder.accessChainStore(copy);
2272 }
2273 ++lValueCount;
2274 }
2275 }
2276
2277 return result;
2278}
2279
2280// Translate AST operation to SPV operation, already having SPV-based operands/types.
2281spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2282 spv::Id typeId, spv::Id left, spv::Id right,
2283 glslang::TBasicType typeProxy, bool reduceComparison)
2284{
2285 bool isUnsigned = typeProxy == glslang::EbtUint;
2286 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2287
2288 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002289 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002290 bool comparison = false;
2291
2292 switch (op) {
2293 case glslang::EOpAdd:
2294 case glslang::EOpAddAssign:
2295 if (isFloat)
2296 binOp = spv::OpFAdd;
2297 else
2298 binOp = spv::OpIAdd;
2299 break;
2300 case glslang::EOpSub:
2301 case glslang::EOpSubAssign:
2302 if (isFloat)
2303 binOp = spv::OpFSub;
2304 else
2305 binOp = spv::OpISub;
2306 break;
2307 case glslang::EOpMul:
2308 case glslang::EOpMulAssign:
2309 if (isFloat)
2310 binOp = spv::OpFMul;
2311 else
2312 binOp = spv::OpIMul;
2313 break;
2314 case glslang::EOpVectorTimesScalar:
2315 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002316 if (isFloat) {
2317 if (builder.isVector(right))
2318 std::swap(left, right);
2319 assert(builder.isScalar(right));
2320 needMatchingVectors = false;
2321 binOp = spv::OpVectorTimesScalar;
2322 } else
2323 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002324 break;
2325 case glslang::EOpVectorTimesMatrix:
2326 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002327 binOp = spv::OpVectorTimesMatrix;
2328 break;
2329 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002330 binOp = spv::OpMatrixTimesVector;
2331 break;
2332 case glslang::EOpMatrixTimesScalar:
2333 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002334 binOp = spv::OpMatrixTimesScalar;
2335 break;
2336 case glslang::EOpMatrixTimesMatrix:
2337 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002338 binOp = spv::OpMatrixTimesMatrix;
2339 break;
2340 case glslang::EOpOuterProduct:
2341 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002342 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002343 break;
2344
2345 case glslang::EOpDiv:
2346 case glslang::EOpDivAssign:
2347 if (isFloat)
2348 binOp = spv::OpFDiv;
2349 else if (isUnsigned)
2350 binOp = spv::OpUDiv;
2351 else
2352 binOp = spv::OpSDiv;
2353 break;
2354 case glslang::EOpMod:
2355 case glslang::EOpModAssign:
2356 if (isFloat)
2357 binOp = spv::OpFMod;
2358 else if (isUnsigned)
2359 binOp = spv::OpUMod;
2360 else
2361 binOp = spv::OpSMod;
2362 break;
2363 case glslang::EOpRightShift:
2364 case glslang::EOpRightShiftAssign:
2365 if (isUnsigned)
2366 binOp = spv::OpShiftRightLogical;
2367 else
2368 binOp = spv::OpShiftRightArithmetic;
2369 break;
2370 case glslang::EOpLeftShift:
2371 case glslang::EOpLeftShiftAssign:
2372 binOp = spv::OpShiftLeftLogical;
2373 break;
2374 case glslang::EOpAnd:
2375 case glslang::EOpAndAssign:
2376 binOp = spv::OpBitwiseAnd;
2377 break;
2378 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002379 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002380 binOp = spv::OpLogicalAnd;
2381 break;
2382 case glslang::EOpInclusiveOr:
2383 case glslang::EOpInclusiveOrAssign:
2384 binOp = spv::OpBitwiseOr;
2385 break;
2386 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002387 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002388 binOp = spv::OpLogicalOr;
2389 break;
2390 case glslang::EOpExclusiveOr:
2391 case glslang::EOpExclusiveOrAssign:
2392 binOp = spv::OpBitwiseXor;
2393 break;
2394 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002395 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002396 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002397 break;
2398
2399 case glslang::EOpLessThan:
2400 case glslang::EOpGreaterThan:
2401 case glslang::EOpLessThanEqual:
2402 case glslang::EOpGreaterThanEqual:
2403 case glslang::EOpEqual:
2404 case glslang::EOpNotEqual:
2405 case glslang::EOpVectorEqual:
2406 case glslang::EOpVectorNotEqual:
2407 comparison = true;
2408 break;
2409 default:
2410 break;
2411 }
2412
John Kessenich7c1aa102015-10-15 13:29:11 -06002413 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002414 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002415 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002416 if (builder.isMatrix(left) || builder.isMatrix(right))
2417 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002418
2419 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002420 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002421 builder.promoteScalar(precision, left, right);
2422
2423 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2424 builder.setPrecision(id, precision);
2425
2426 return id;
2427 }
2428
2429 if (! comparison)
2430 return 0;
2431
John Kessenich7c1aa102015-10-15 13:29:11 -06002432 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002433
2434 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2435 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2436
John Kessenich22118352015-12-21 20:54:09 -07002437 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002438 }
2439
2440 switch (op) {
2441 case glslang::EOpLessThan:
2442 if (isFloat)
2443 binOp = spv::OpFOrdLessThan;
2444 else if (isUnsigned)
2445 binOp = spv::OpULessThan;
2446 else
2447 binOp = spv::OpSLessThan;
2448 break;
2449 case glslang::EOpGreaterThan:
2450 if (isFloat)
2451 binOp = spv::OpFOrdGreaterThan;
2452 else if (isUnsigned)
2453 binOp = spv::OpUGreaterThan;
2454 else
2455 binOp = spv::OpSGreaterThan;
2456 break;
2457 case glslang::EOpLessThanEqual:
2458 if (isFloat)
2459 binOp = spv::OpFOrdLessThanEqual;
2460 else if (isUnsigned)
2461 binOp = spv::OpULessThanEqual;
2462 else
2463 binOp = spv::OpSLessThanEqual;
2464 break;
2465 case glslang::EOpGreaterThanEqual:
2466 if (isFloat)
2467 binOp = spv::OpFOrdGreaterThanEqual;
2468 else if (isUnsigned)
2469 binOp = spv::OpUGreaterThanEqual;
2470 else
2471 binOp = spv::OpSGreaterThanEqual;
2472 break;
2473 case glslang::EOpEqual:
2474 case glslang::EOpVectorEqual:
2475 if (isFloat)
2476 binOp = spv::OpFOrdEqual;
2477 else
2478 binOp = spv::OpIEqual;
2479 break;
2480 case glslang::EOpNotEqual:
2481 case glslang::EOpVectorNotEqual:
2482 if (isFloat)
2483 binOp = spv::OpFOrdNotEqual;
2484 else
2485 binOp = spv::OpINotEqual;
2486 break;
2487 default:
2488 break;
2489 }
2490
2491 if (binOp != spv::OpNop) {
2492 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2493 builder.setPrecision(id, precision);
2494
2495 return id;
2496 }
2497
2498 return 0;
2499}
2500
John Kessenich04bb8a02015-12-12 12:28:14 -07002501//
2502// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2503// These can be any of:
2504//
2505// matrix * scalar
2506// scalar * matrix
2507// matrix * matrix linear algebraic
2508// matrix * vector
2509// vector * matrix
2510// matrix * matrix componentwise
2511// matrix op matrix op in {+, -, /}
2512// matrix op scalar op in {+, -, /}
2513// scalar op matrix op in {+, -, /}
2514//
2515spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2516{
2517 bool firstClass = true;
2518
2519 // First, handle first-class matrix operations (* and matrix/scalar)
2520 switch (op) {
2521 case spv::OpFDiv:
2522 if (builder.isMatrix(left) && builder.isScalar(right)) {
2523 // turn matrix / scalar into a multiply...
2524 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2525 op = spv::OpMatrixTimesScalar;
2526 } else
2527 firstClass = false;
2528 break;
2529 case spv::OpMatrixTimesScalar:
2530 if (builder.isMatrix(right))
2531 std::swap(left, right);
2532 assert(builder.isScalar(right));
2533 break;
2534 case spv::OpVectorTimesMatrix:
2535 assert(builder.isVector(left));
2536 assert(builder.isMatrix(right));
2537 break;
2538 case spv::OpMatrixTimesVector:
2539 assert(builder.isMatrix(left));
2540 assert(builder.isVector(right));
2541 break;
2542 case spv::OpMatrixTimesMatrix:
2543 assert(builder.isMatrix(left));
2544 assert(builder.isMatrix(right));
2545 break;
2546 default:
2547 firstClass = false;
2548 break;
2549 }
2550
2551 if (firstClass) {
2552 spv::Id id = builder.createBinOp(op, typeId, left, right);
2553 builder.setPrecision(id, precision);
2554
2555 return id;
2556 }
2557
2558 // Handle component-wise +, -, *, and / for all combinations of type.
2559 // The result type of all of them is the same type as the (a) matrix operand.
2560 // The algorithm is to:
2561 // - break the matrix(es) into vectors
2562 // - smear any scalar to a vector
2563 // - do vector operations
2564 // - make a matrix out the vector results
2565 switch (op) {
2566 case spv::OpFAdd:
2567 case spv::OpFSub:
2568 case spv::OpFDiv:
2569 case spv::OpFMul:
2570 {
2571 // one time set up...
2572 bool leftMat = builder.isMatrix(left);
2573 bool rightMat = builder.isMatrix(right);
2574 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2575 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2576 spv::Id scalarType = builder.getScalarTypeId(typeId);
2577 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2578 std::vector<spv::Id> results;
2579 spv::Id smearVec = spv::NoResult;
2580 if (builder.isScalar(left))
2581 smearVec = builder.smearScalar(precision, left, vecType);
2582 else if (builder.isScalar(right))
2583 smearVec = builder.smearScalar(precision, right, vecType);
2584
2585 // do each vector op
2586 for (unsigned int c = 0; c < numCols; ++c) {
2587 std::vector<unsigned int> indexes;
2588 indexes.push_back(c);
2589 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2590 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2591 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2592 builder.setPrecision(results.back(), precision);
2593 }
2594
2595 // put the pieces together
2596 spv::Id id = builder.createCompositeConstruct(typeId, results);
2597 builder.setPrecision(id, precision);
2598 return id;
2599 }
2600 default:
2601 assert(0);
2602 return spv::NoResult;
2603 }
2604}
2605
Rex Xu04db3f52015-09-16 11:44:02 +08002606spv::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 -06002607{
2608 spv::Op unaryOp = spv::OpNop;
2609 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002610 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002611 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002612
2613 switch (op) {
2614 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002615 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002616 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002617 if (builder.isMatrixType(typeId))
2618 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2619 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002620 unaryOp = spv::OpSNegate;
2621 break;
2622
2623 case glslang::EOpLogicalNot:
2624 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002625 unaryOp = spv::OpLogicalNot;
2626 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002627 case glslang::EOpBitwiseNot:
2628 unaryOp = spv::OpNot;
2629 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002630
John Kessenich140f3df2015-06-26 16:58:36 -06002631 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002632 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002633 break;
2634 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002635 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002636 break;
2637 case glslang::EOpTranspose:
2638 unaryOp = spv::OpTranspose;
2639 break;
2640
2641 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002642 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002643 break;
2644 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002645 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002646 break;
2647 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002648 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002649 break;
2650 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002651 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002652 break;
2653 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002654 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002655 break;
2656 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002657 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002658 break;
2659 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002660 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002661 break;
2662 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002663 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002664 break;
2665
2666 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002667 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002668 break;
2669 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002670 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002671 break;
2672 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002673 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002674 break;
2675 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002676 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002677 break;
2678 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002679 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002680 break;
2681 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002682 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002683 break;
2684
2685 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002686 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002687 break;
2688 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002689 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002690 break;
2691
2692 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002693 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002694 break;
2695 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002696 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002697 break;
2698 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002699 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002700 break;
2701 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002702 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002703 break;
2704 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002705 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002706 break;
2707 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002709 break;
2710
2711 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002712 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002713 break;
2714 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002715 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002716 break;
2717 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002718 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002719 break;
2720 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002721 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002722 break;
2723 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002724 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002725 break;
2726 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002727 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002728 break;
2729
2730 case glslang::EOpIsNan:
2731 unaryOp = spv::OpIsNan;
2732 break;
2733 case glslang::EOpIsInf:
2734 unaryOp = spv::OpIsInf;
2735 break;
2736
Rex Xucbc426e2015-12-15 16:03:10 +08002737 case glslang::EOpFloatBitsToInt:
2738 case glslang::EOpFloatBitsToUint:
2739 case glslang::EOpIntBitsToFloat:
2740 case glslang::EOpUintBitsToFloat:
2741 unaryOp = spv::OpBitcast;
2742 break;
2743
John Kessenich140f3df2015-06-26 16:58:36 -06002744 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002745 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002746 break;
2747 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002748 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002749 break;
2750 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002751 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002752 break;
2753 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002754 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002755 break;
2756 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002757 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002758 break;
2759 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002760 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002761 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002762 case glslang::EOpPackSnorm4x8:
2763 libCall = spv::GLSLstd450PackSnorm4x8;
2764 break;
2765 case glslang::EOpUnpackSnorm4x8:
2766 libCall = spv::GLSLstd450UnpackSnorm4x8;
2767 break;
2768 case glslang::EOpPackUnorm4x8:
2769 libCall = spv::GLSLstd450PackUnorm4x8;
2770 break;
2771 case glslang::EOpUnpackUnorm4x8:
2772 libCall = spv::GLSLstd450UnpackUnorm4x8;
2773 break;
2774 case glslang::EOpPackDouble2x32:
2775 libCall = spv::GLSLstd450PackDouble2x32;
2776 break;
2777 case glslang::EOpUnpackDouble2x32:
2778 libCall = spv::GLSLstd450UnpackDouble2x32;
2779 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002780
2781 case glslang::EOpDPdx:
2782 unaryOp = spv::OpDPdx;
2783 break;
2784 case glslang::EOpDPdy:
2785 unaryOp = spv::OpDPdy;
2786 break;
2787 case glslang::EOpFwidth:
2788 unaryOp = spv::OpFwidth;
2789 break;
2790 case glslang::EOpDPdxFine:
2791 unaryOp = spv::OpDPdxFine;
2792 break;
2793 case glslang::EOpDPdyFine:
2794 unaryOp = spv::OpDPdyFine;
2795 break;
2796 case glslang::EOpFwidthFine:
2797 unaryOp = spv::OpFwidthFine;
2798 break;
2799 case glslang::EOpDPdxCoarse:
2800 unaryOp = spv::OpDPdxCoarse;
2801 break;
2802 case glslang::EOpDPdyCoarse:
2803 unaryOp = spv::OpDPdyCoarse;
2804 break;
2805 case glslang::EOpFwidthCoarse:
2806 unaryOp = spv::OpFwidthCoarse;
2807 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002808 case glslang::EOpInterpolateAtCentroid:
2809 libCall = spv::GLSLstd450InterpolateAtCentroid;
2810 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002811 case glslang::EOpAny:
2812 unaryOp = spv::OpAny;
2813 break;
2814 case glslang::EOpAll:
2815 unaryOp = spv::OpAll;
2816 break;
2817
2818 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002819 if (isFloat)
2820 libCall = spv::GLSLstd450FAbs;
2821 else
2822 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002823 break;
2824 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002825 if (isFloat)
2826 libCall = spv::GLSLstd450FSign;
2827 else
2828 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002829 break;
2830
John Kessenichfc51d282015-08-19 13:34:18 -06002831 case glslang::EOpAtomicCounterIncrement:
2832 case glslang::EOpAtomicCounterDecrement:
2833 case glslang::EOpAtomicCounter:
2834 {
2835 // Handle all of the atomics in one place, in createAtomicOperation()
2836 std::vector<spv::Id> operands;
2837 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002838 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002839 }
2840
2841 case glslang::EOpImageLoad:
2842 unaryOp = spv::OpImageRead;
2843 break;
2844
2845 case glslang::EOpBitFieldReverse:
2846 unaryOp = spv::OpBitReverse;
2847 break;
2848 case glslang::EOpBitCount:
2849 unaryOp = spv::OpBitCount;
2850 break;
2851 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002852 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002853 break;
2854 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002855 if (isUnsigned)
2856 libCall = spv::GLSLstd450FindUMsb;
2857 else
2858 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002859 break;
2860
John Kessenich140f3df2015-06-26 16:58:36 -06002861 default:
2862 return 0;
2863 }
2864
2865 spv::Id id;
2866 if (libCall >= 0) {
2867 std::vector<spv::Id> args;
2868 args.push_back(operand);
2869 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2870 } else
2871 id = builder.createUnaryOp(unaryOp, typeId, operand);
2872
2873 builder.setPrecision(id, precision);
2874
2875 return id;
2876}
2877
John Kessenich7a53f762016-01-20 11:19:27 -07002878// Create a unary operation on a matrix
2879spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
2880{
2881 // Handle unary operations vector by vector.
2882 // The result type is the same type as the original type.
2883 // The algorithm is to:
2884 // - break the matrix into vectors
2885 // - apply the operation to each vector
2886 // - make a matrix out the vector results
2887
2888 // get the types sorted out
2889 int numCols = builder.getNumColumns(operand);
2890 int numRows = builder.getNumRows(operand);
2891 spv::Id scalarType = builder.getScalarTypeId(typeId);
2892 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2893 std::vector<spv::Id> results;
2894
2895 // do each vector op
2896 for (int c = 0; c < numCols; ++c) {
2897 std::vector<unsigned int> indexes;
2898 indexes.push_back(c);
2899 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
2900 results.push_back(builder.createUnaryOp(op, vecType, vec));
2901 builder.setPrecision(results.back(), precision);
2902 }
2903
2904 // put the pieces together
2905 spv::Id id = builder.createCompositeConstruct(typeId, results);
2906 builder.setPrecision(id, precision);
2907
2908 return id;
2909}
2910
John Kessenich140f3df2015-06-26 16:58:36 -06002911spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2912{
2913 spv::Op convOp = spv::OpNop;
2914 spv::Id zero = 0;
2915 spv::Id one = 0;
2916
2917 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2918
2919 switch (op) {
2920 case glslang::EOpConvIntToBool:
2921 case glslang::EOpConvUintToBool:
2922 zero = builder.makeUintConstant(0);
2923 zero = makeSmearedConstant(zero, vectorSize);
2924 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2925
2926 case glslang::EOpConvFloatToBool:
2927 zero = builder.makeFloatConstant(0.0F);
2928 zero = makeSmearedConstant(zero, vectorSize);
2929 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2930
2931 case glslang::EOpConvDoubleToBool:
2932 zero = builder.makeDoubleConstant(0.0);
2933 zero = makeSmearedConstant(zero, vectorSize);
2934 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2935
2936 case glslang::EOpConvBoolToFloat:
2937 convOp = spv::OpSelect;
2938 zero = builder.makeFloatConstant(0.0);
2939 one = builder.makeFloatConstant(1.0);
2940 break;
2941 case glslang::EOpConvBoolToDouble:
2942 convOp = spv::OpSelect;
2943 zero = builder.makeDoubleConstant(0.0);
2944 one = builder.makeDoubleConstant(1.0);
2945 break;
2946 case glslang::EOpConvBoolToInt:
2947 zero = builder.makeIntConstant(0);
2948 one = builder.makeIntConstant(1);
2949 convOp = spv::OpSelect;
2950 break;
2951 case glslang::EOpConvBoolToUint:
2952 zero = builder.makeUintConstant(0);
2953 one = builder.makeUintConstant(1);
2954 convOp = spv::OpSelect;
2955 break;
2956
2957 case glslang::EOpConvIntToFloat:
2958 case glslang::EOpConvIntToDouble:
2959 convOp = spv::OpConvertSToF;
2960 break;
2961
2962 case glslang::EOpConvUintToFloat:
2963 case glslang::EOpConvUintToDouble:
2964 convOp = spv::OpConvertUToF;
2965 break;
2966
2967 case glslang::EOpConvDoubleToFloat:
2968 case glslang::EOpConvFloatToDouble:
2969 convOp = spv::OpFConvert;
2970 break;
2971
2972 case glslang::EOpConvFloatToInt:
2973 case glslang::EOpConvDoubleToInt:
2974 convOp = spv::OpConvertFToS;
2975 break;
2976
2977 case glslang::EOpConvUintToInt:
2978 case glslang::EOpConvIntToUint:
2979 convOp = spv::OpBitcast;
2980 break;
2981
2982 case glslang::EOpConvFloatToUint:
2983 case glslang::EOpConvDoubleToUint:
2984 convOp = spv::OpConvertFToU;
2985 break;
2986 default:
2987 break;
2988 }
2989
2990 spv::Id result = 0;
2991 if (convOp == spv::OpNop)
2992 return result;
2993
2994 if (convOp == spv::OpSelect) {
2995 zero = makeSmearedConstant(zero, vectorSize);
2996 one = makeSmearedConstant(one, vectorSize);
2997 result = builder.createTriOp(convOp, destType, operand, one, zero);
2998 } else
2999 result = builder.createUnaryOp(convOp, destType, operand);
3000
3001 builder.setPrecision(result, precision);
3002
3003 return result;
3004}
3005
3006spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3007{
3008 if (vectorSize == 0)
3009 return constant;
3010
3011 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3012 std::vector<spv::Id> components;
3013 for (int c = 0; c < vectorSize; ++c)
3014 components.push_back(constant);
3015 return builder.makeCompositeConstant(vectorTypeId, components);
3016}
3017
John Kessenich426394d2015-07-23 10:22:48 -06003018// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08003019spv::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 -06003020{
3021 spv::Op opCode = spv::OpNop;
3022
3023 switch (op) {
3024 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003025 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003026 opCode = spv::OpAtomicIAdd;
3027 break;
3028 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003029 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003030 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003031 break;
3032 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003033 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003034 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003035 break;
3036 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003037 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003038 opCode = spv::OpAtomicAnd;
3039 break;
3040 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003041 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003042 opCode = spv::OpAtomicOr;
3043 break;
3044 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003045 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003046 opCode = spv::OpAtomicXor;
3047 break;
3048 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003049 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003050 opCode = spv::OpAtomicExchange;
3051 break;
3052 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003053 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003054 opCode = spv::OpAtomicCompareExchange;
3055 break;
3056 case glslang::EOpAtomicCounterIncrement:
3057 opCode = spv::OpAtomicIIncrement;
3058 break;
3059 case glslang::EOpAtomicCounterDecrement:
3060 opCode = spv::OpAtomicIDecrement;
3061 break;
3062 case glslang::EOpAtomicCounter:
3063 opCode = spv::OpAtomicLoad;
3064 break;
3065 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003066 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003067 break;
3068 }
3069
3070 // Sort out the operands
3071 // - mapping from glslang -> SPV
3072 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003073 // - compare-exchange swaps the value and comparator
3074 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003075 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3076 auto opIt = operands.begin(); // walk the glslang operands
3077 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003078 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3079 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3080 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003081 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3082 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003083 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003084 spvAtomicOperands.push_back(*(opIt + 1));
3085 spvAtomicOperands.push_back(*opIt);
3086 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003087 }
John Kessenich426394d2015-07-23 10:22:48 -06003088
John Kessenich3e60a6f2015-09-14 22:45:16 -06003089 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003090 for (; opIt != operands.end(); ++opIt)
3091 spvAtomicOperands.push_back(*opIt);
3092
3093 return builder.createOp(opCode, typeId, spvAtomicOperands);
3094}
3095
John Kessenich5e4b1242015-08-06 22:53:06 -06003096spv::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 -06003097{
John Kessenich5e4b1242015-08-06 22:53:06 -06003098 bool isUnsigned = typeProxy == glslang::EbtUint;
3099 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3100
John Kessenich140f3df2015-06-26 16:58:36 -06003101 spv::Op opCode = spv::OpNop;
3102 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003103 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003104 spv::Id typeId0 = 0;
3105 if (consumedOperands > 0)
3106 typeId0 = builder.getTypeId(operands[0]);
3107 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003108
3109 switch (op) {
3110 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003111 if (isFloat)
3112 libCall = spv::GLSLstd450FMin;
3113 else if (isUnsigned)
3114 libCall = spv::GLSLstd450UMin;
3115 else
3116 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003117 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003118 break;
3119 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003120 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 break;
3122 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 if (isFloat)
3124 libCall = spv::GLSLstd450FMax;
3125 else if (isUnsigned)
3126 libCall = spv::GLSLstd450UMax;
3127 else
3128 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003129 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003130 break;
3131 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003133 break;
3134 case glslang::EOpDot:
3135 opCode = spv::OpDot;
3136 break;
3137 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003138 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003139 break;
3140
3141 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003142 if (isFloat)
3143 libCall = spv::GLSLstd450FClamp;
3144 else if (isUnsigned)
3145 libCall = spv::GLSLstd450UClamp;
3146 else
3147 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003148 builder.promoteScalar(precision, operands.front(), operands[1]);
3149 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003150 break;
3151 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003152 if (isFloat)
3153 libCall = spv::GLSLstd450FMix;
3154 else
3155 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003156 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003157 break;
3158 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003159 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003160 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003161 break;
3162 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003163 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003164 builder.promoteScalar(precision, operands[0], operands[2]);
3165 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167
3168 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003169 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003170 break;
3171 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003172 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003173 break;
3174 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003175 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003176 break;
3177 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003178 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003179 break;
3180 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003181 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003182 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003183 case glslang::EOpInterpolateAtSample:
3184 libCall = spv::GLSLstd450InterpolateAtSample;
3185 break;
3186 case glslang::EOpInterpolateAtOffset:
3187 libCall = spv::GLSLstd450InterpolateAtOffset;
3188 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003189 case glslang::EOpAddCarry:
3190 opCode = spv::OpIAddCarry;
3191 typeId = builder.makeStructResultType(typeId0, typeId0);
3192 consumedOperands = 2;
3193 break;
3194 case glslang::EOpSubBorrow:
3195 opCode = spv::OpISubBorrow;
3196 typeId = builder.makeStructResultType(typeId0, typeId0);
3197 consumedOperands = 2;
3198 break;
3199 case glslang::EOpUMulExtended:
3200 opCode = spv::OpUMulExtended;
3201 typeId = builder.makeStructResultType(typeId0, typeId0);
3202 consumedOperands = 2;
3203 break;
3204 case glslang::EOpIMulExtended:
3205 opCode = spv::OpSMulExtended;
3206 typeId = builder.makeStructResultType(typeId0, typeId0);
3207 consumedOperands = 2;
3208 break;
3209 case glslang::EOpBitfieldExtract:
3210 if (isUnsigned)
3211 opCode = spv::OpBitFieldUExtract;
3212 else
3213 opCode = spv::OpBitFieldSExtract;
3214 break;
3215 case glslang::EOpBitfieldInsert:
3216 opCode = spv::OpBitFieldInsert;
3217 break;
3218
3219 case glslang::EOpFma:
3220 libCall = spv::GLSLstd450Fma;
3221 break;
3222 case glslang::EOpFrexp:
3223 libCall = spv::GLSLstd450FrexpStruct;
3224 if (builder.getNumComponents(operands[0]) == 1)
3225 frexpIntType = builder.makeIntegerType(32, true);
3226 else
3227 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3228 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3229 consumedOperands = 1;
3230 break;
3231 case glslang::EOpLdexp:
3232 libCall = spv::GLSLstd450Ldexp;
3233 break;
3234
John Kessenich140f3df2015-06-26 16:58:36 -06003235 default:
3236 return 0;
3237 }
3238
3239 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003240 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003241 // Use an extended instruction from the standard library.
3242 // Construct the call arguments, without modifying the original operands vector.
3243 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3244 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
3245 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003246 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003247 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003248 case 0:
3249 // should all be handled by visitAggregate and createNoArgOperation
3250 assert(0);
3251 return 0;
3252 case 1:
3253 // should all be handled by createUnaryOperation
3254 assert(0);
3255 return 0;
3256 case 2:
3257 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3258 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003259 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003260 // anything 3 or over doesn't have l-value operands, so all should be consumed
3261 assert(consumedOperands == operands.size());
3262 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003263 break;
3264 }
3265 }
3266
John Kessenich55e7d112015-11-15 21:33:39 -07003267 // Decode the return types that were structures
3268 switch (op) {
3269 case glslang::EOpAddCarry:
3270 case glslang::EOpSubBorrow:
3271 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3272 id = builder.createCompositeExtract(id, typeId0, 0);
3273 break;
3274 case glslang::EOpUMulExtended:
3275 case glslang::EOpIMulExtended:
3276 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3277 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3278 break;
3279 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003280 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003281 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3282 id = builder.createCompositeExtract(id, typeId0, 0);
3283 break;
3284 default:
3285 break;
3286 }
3287
John Kessenich140f3df2015-06-26 16:58:36 -06003288 builder.setPrecision(id, precision);
3289
3290 return id;
3291}
3292
3293// Intrinsics with no arguments, no return value, and no precision.
3294spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3295{
3296 // TODO: get the barrier operands correct
3297
3298 switch (op) {
3299 case glslang::EOpEmitVertex:
3300 builder.createNoResultOp(spv::OpEmitVertex);
3301 return 0;
3302 case glslang::EOpEndPrimitive:
3303 builder.createNoResultOp(spv::OpEndPrimitive);
3304 return 0;
3305 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003306 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3307 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003308 return 0;
3309 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003310 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003311 return 0;
3312 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003313 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003314 return 0;
3315 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003316 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003317 return 0;
3318 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003319 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003320 return 0;
3321 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003322 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003323 return 0;
3324 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003325 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003326 return 0;
3327 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003328 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003329 return 0;
3330 }
3331}
3332
3333spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3334{
John Kessenich2f273362015-07-18 22:34:27 -06003335 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003336 spv::Id id;
3337 if (symbolValues.end() != iter) {
3338 id = iter->second;
3339 return id;
3340 }
3341
3342 // it was not found, create it
3343 id = createSpvVariable(symbol);
3344 symbolValues[symbol->getId()] = id;
3345
3346 if (! symbol->getType().isStruct()) {
3347 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003348 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003349 if (symbol->getQualifier().hasLocation())
3350 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3351 if (symbol->getQualifier().hasIndex())
3352 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3353 if (symbol->getQualifier().hasComponent())
3354 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3355 if (glslangIntermediate->getXfbMode()) {
3356 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003357 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003358 if (symbol->getQualifier().hasXfbBuffer())
3359 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3360 if (symbol->getQualifier().hasXfbOffset())
3361 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3362 }
3363 }
3364
John Kesseniche0b6cad2015-12-24 10:30:13 -07003365 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003366 if (symbol->getQualifier().hasStream())
3367 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
3368 if (symbol->getQualifier().hasSet())
3369 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3370 if (symbol->getQualifier().hasBinding())
3371 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3372 if (glslangIntermediate->getXfbMode()) {
3373 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003374 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003375 if (symbol->getQualifier().hasXfbBuffer())
3376 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3377 }
3378
3379 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003380 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003381 if (builtIn != spv::BadValue)
John Kessenich30669532015-08-06 22:02:24 -06003382 builder.addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003383
John Kessenich140f3df2015-06-26 16:58:36 -06003384 return id;
3385}
3386
John Kessenich55e7d112015-11-15 21:33:39 -07003387// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003388void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3389{
3390 if (dec != spv::BadValue)
3391 builder.addDecoration(id, dec);
3392}
3393
John Kessenich55e7d112015-11-15 21:33:39 -07003394// If 'dec' is valid, add a one-operand decoration to an object
3395void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3396{
3397 if (dec != spv::BadValue)
3398 builder.addDecoration(id, dec, value);
3399}
3400
3401// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003402void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3403{
3404 if (dec != spv::BadValue)
3405 builder.addMemberDecoration(id, (unsigned)member, dec);
3406}
3407
John Kessenich55e7d112015-11-15 21:33:39 -07003408// Make a full tree of instructions to build a SPIR-V specialization constant,
3409// or regularly constant if possible.
3410//
3411// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3412//
3413// Recursively walk the nodes. The nodes form a tree whose leaves are
3414// regular constants, which themselves are trees that createSpvConstant()
3415// recursively walks. So, this function walks the "top" of the tree:
3416// - emit specialization constant-building instructions for specConstant
3417// - when running into a non-spec-constant, switch to createSpvConstant()
3418spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3419{
3420 assert(node.getQualifier().storage == glslang::EvqConst);
3421
3422 // hand off to the non-spec-constant path
3423 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3424 int nextConst = 0;
3425 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3426}
3427
John Kessenich140f3df2015-06-26 16:58:36 -06003428// Use 'consts' as the flattened glslang source of scalar constants to recursively
3429// build the aggregate SPIR-V constant.
3430//
3431// If there are not enough elements present in 'consts', 0 will be substituted;
3432// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3433//
John Kessenich55e7d112015-11-15 21:33:39 -07003434spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003435{
3436 // vector of constants for SPIR-V
3437 std::vector<spv::Id> spvConsts;
3438
3439 // Type is used for struct and array constants
3440 spv::Id typeId = convertGlslangToSpvType(glslangType);
3441
3442 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003443 glslang::TType elementType(glslangType, 0);
3444 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003445 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003446 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003447 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003448 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003449 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003450 } else if (glslangType.getStruct()) {
3451 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3452 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003453 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003454 } else if (glslangType.isVector()) {
3455 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3456 bool zero = nextConst >= consts.size();
3457 switch (glslangType.getBasicType()) {
3458 case glslang::EbtInt:
3459 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3460 break;
3461 case glslang::EbtUint:
3462 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3463 break;
3464 case glslang::EbtFloat:
3465 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3466 break;
3467 case glslang::EbtDouble:
3468 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3469 break;
3470 case glslang::EbtBool:
3471 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3472 break;
3473 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003474 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003475 break;
3476 }
3477 ++nextConst;
3478 }
3479 } else {
3480 // we have a non-aggregate (scalar) constant
3481 bool zero = nextConst >= consts.size();
3482 spv::Id scalar = 0;
3483 switch (glslangType.getBasicType()) {
3484 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003485 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003486 break;
3487 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003488 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003489 break;
3490 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003491 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003492 break;
3493 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003494 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003495 break;
3496 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003497 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003498 break;
3499 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003500 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003501 break;
3502 }
3503 ++nextConst;
3504 return scalar;
3505 }
3506
3507 return builder.makeCompositeConstant(typeId, spvConsts);
3508}
3509
John Kessenich7c1aa102015-10-15 13:29:11 -06003510// Return true if the node is a constant or symbol whose reading has no
3511// non-trivial observable cost or effect.
3512bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3513{
3514 // don't know what this is
3515 if (node == nullptr)
3516 return false;
3517
3518 // a constant is safe
3519 if (node->getAsConstantUnion() != nullptr)
3520 return true;
3521
3522 // not a symbol means non-trivial
3523 if (node->getAsSymbolNode() == nullptr)
3524 return false;
3525
3526 // a symbol, depends on what's being read
3527 switch (node->getType().getQualifier().storage) {
3528 case glslang::EvqTemporary:
3529 case glslang::EvqGlobal:
3530 case glslang::EvqIn:
3531 case glslang::EvqInOut:
3532 case glslang::EvqConst:
3533 case glslang::EvqConstReadOnly:
3534 case glslang::EvqUniform:
3535 return true;
3536 default:
3537 return false;
3538 }
3539}
3540
3541// A node is trivial if it is a single operation with no side effects.
3542// Error on the side of saying non-trivial.
3543// Return true if trivial.
3544bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3545{
3546 if (node == nullptr)
3547 return false;
3548
3549 // symbols and constants are trivial
3550 if (isTrivialLeaf(node))
3551 return true;
3552
3553 // otherwise, it needs to be a simple operation or one or two leaf nodes
3554
3555 // not a simple operation
3556 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3557 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3558 if (binaryNode == nullptr && unaryNode == nullptr)
3559 return false;
3560
3561 // not on leaf nodes
3562 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3563 return false;
3564
3565 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3566 return false;
3567 }
3568
3569 switch (node->getAsOperator()->getOp()) {
3570 case glslang::EOpLogicalNot:
3571 case glslang::EOpConvIntToBool:
3572 case glslang::EOpConvUintToBool:
3573 case glslang::EOpConvFloatToBool:
3574 case glslang::EOpConvDoubleToBool:
3575 case glslang::EOpEqual:
3576 case glslang::EOpNotEqual:
3577 case glslang::EOpLessThan:
3578 case glslang::EOpGreaterThan:
3579 case glslang::EOpLessThanEqual:
3580 case glslang::EOpGreaterThanEqual:
3581 case glslang::EOpIndexDirect:
3582 case glslang::EOpIndexDirectStruct:
3583 case glslang::EOpLogicalXor:
3584 case glslang::EOpAny:
3585 case glslang::EOpAll:
3586 return true;
3587 default:
3588 return false;
3589 }
3590}
3591
3592// Emit short-circuiting code, where 'right' is never evaluated unless
3593// the left side is true (for &&) or false (for ||).
3594spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3595{
3596 spv::Id boolTypeId = builder.makeBoolType();
3597
3598 // emit left operand
3599 builder.clearAccessChain();
3600 left.traverse(this);
3601 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3602
3603 // Operands to accumulate OpPhi operands
3604 std::vector<spv::Id> phiOperands;
3605 // accumulate left operand's phi information
3606 phiOperands.push_back(leftId);
3607 phiOperands.push_back(builder.getBuildPoint()->getId());
3608
3609 // Make the two kinds of operation symmetric with a "!"
3610 // || => emit "if (! left) result = right"
3611 // && => emit "if ( left) result = right"
3612 //
3613 // TODO: this runtime "not" for || could be avoided by adding functionality
3614 // to 'builder' to have an "else" without an "then"
3615 if (op == glslang::EOpLogicalOr)
3616 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3617
3618 // make an "if" based on the left value
3619 spv::Builder::If ifBuilder(leftId, builder);
3620
3621 // emit right operand as the "then" part of the "if"
3622 builder.clearAccessChain();
3623 right.traverse(this);
3624 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3625
3626 // accumulate left operand's phi information
3627 phiOperands.push_back(rightId);
3628 phiOperands.push_back(builder.getBuildPoint()->getId());
3629
3630 // finish the "if"
3631 ifBuilder.makeEndIf();
3632
3633 // phi together the two results
3634 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3635}
3636
John Kessenich140f3df2015-06-26 16:58:36 -06003637}; // end anonymous namespace
3638
3639namespace glslang {
3640
John Kessenich68d78fd2015-07-12 19:28:10 -06003641void GetSpirvVersion(std::string& version)
3642{
John Kessenich9e55f632015-07-15 10:03:39 -06003643 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003644 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003645 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003646 version = buf;
3647}
3648
John Kessenich140f3df2015-06-26 16:58:36 -06003649// Write SPIR-V out to a binary file
3650void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3651{
3652 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003653 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003654 for (int i = 0; i < (int)spirv.size(); ++i) {
3655 unsigned int word = spirv[i];
3656 out.write((const char*)&word, 4);
3657 }
3658 out.close();
3659}
3660
3661//
3662// Set up the glslang traversal
3663//
3664void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3665{
3666 TIntermNode* root = intermediate.getTreeRoot();
3667
3668 if (root == 0)
3669 return;
3670
3671 glslang::GetThreadPoolAllocator().push();
3672
3673 TGlslangToSpvTraverser it(&intermediate);
3674
3675 root->traverse(&it);
3676
3677 it.dumpSpv(spirv);
3678
3679 glslang::GetThreadPoolAllocator().pop();
3680}
3681
3682}; // end namespace glslang