blob: 94e37e8f2145bbc3cd66008dd49c1f2d96679db0 [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:
John Kessenich92187592016-02-01 13:45:25 -070091 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich140f3df2015-06-26 16:58:36 -060092 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
93 spv::Id getSampledType(const glslang::TSampler&);
94 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070095 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich32cfd492016-02-02 12:37:46 -070096 spv::Id accessChainLoad(const glslang::TType& type);
John Kessenichf85e8062015-12-19 13:57:10 -070097 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -070098 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
99 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
100 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 -0600101
102 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
103 void makeFunctions(const glslang::TIntermSequence&);
104 void makeGlobalInitializers(const glslang::TIntermSequence&);
105 void visitFunctions(const glslang::TIntermSequence&);
106 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800107 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600108 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
109 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600110 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
111
112 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 -0700113 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800114 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 -0700115 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600116 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
117 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800118 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 -0600119 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 -0600120 spv::Id createNoArgOperation(glslang::TOperator op);
121 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
122 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700123 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600124 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700125 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700126 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
127 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600128 bool isTrivialLeaf(const glslang::TIntermTyped* node);
129 bool isTrivial(const glslang::TIntermTyped* node);
130 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600131
132 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700133 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600134 int sequenceDepth;
135
136 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
137 spv::Builder builder;
138 bool inMain;
139 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700140 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 -0700141 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600142 const glslang::TIntermediate* glslangIntermediate;
143 spv::Id stdBuiltins;
144
John Kessenich2f273362015-07-18 22:34:27 -0600145 std::unordered_map<int, spv::Id> symbolValues;
146 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
147 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700148 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600149 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 -0600150 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600151};
152
153//
154// Helper functions for translating glslang representations to SPIR-V enumerants.
155//
156
157// Translate glslang profile to SPIR-V source language.
158spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
159{
160 switch (profile) {
161 case ENoProfile:
162 case ECoreProfile:
163 case ECompatibilityProfile:
164 return spv::SourceLanguageGLSL;
165 case EEsProfile:
166 return spv::SourceLanguageESSL;
167 default:
168 return spv::SourceLanguageUnknown;
169 }
170}
171
172// Translate glslang language (stage) to SPIR-V execution model.
173spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
174{
175 switch (stage) {
176 case EShLangVertex: return spv::ExecutionModelVertex;
177 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
178 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
179 case EShLangGeometry: return spv::ExecutionModelGeometry;
180 case EShLangFragment: return spv::ExecutionModelFragment;
181 case EShLangCompute: return spv::ExecutionModelGLCompute;
182 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700183 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600184 return spv::ExecutionModelFragment;
185 }
186}
187
188// Translate glslang type to SPIR-V storage class.
189spv::StorageClass TranslateStorageClass(const glslang::TType& type)
190{
191 if (type.getQualifier().isPipeInput())
192 return spv::StorageClassInput;
193 else if (type.getQualifier().isPipeOutput())
194 return spv::StorageClassOutput;
195 else if (type.getQualifier().isUniformOrBuffer()) {
196 if (type.getBasicType() == glslang::EbtBlock)
197 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800198 else if (type.getBasicType() == glslang::EbtAtomicUint)
199 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600200 else
201 return spv::StorageClassUniformConstant;
202 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
203 } else {
204 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700205 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
206 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600207 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
208 case glslang::EvqTemporary: return spv::StorageClassFunction;
209 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700210 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600211 return spv::StorageClassFunction;
212 }
213 }
214}
215
216// Translate glslang sampler type to SPIR-V dimensionality.
217spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
218{
219 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700220 case glslang::Esd1D: return spv::Dim1D;
221 case glslang::Esd2D: return spv::Dim2D;
222 case glslang::Esd3D: return spv::Dim3D;
223 case glslang::EsdCube: return spv::DimCube;
224 case glslang::EsdRect: return spv::DimRect;
225 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600226 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700227 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600228 return spv::Dim2D;
229 }
230}
231
232// Translate glslang type to SPIR-V precision decorations.
233spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
234{
235 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700236 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600237 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600238 default:
239 return spv::NoPrecision;
240 }
241}
242
243// Translate glslang type to SPIR-V block decorations.
244spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
245{
246 if (type.getBasicType() == glslang::EbtBlock) {
247 switch (type.getQualifier().storage) {
248 case glslang::EvqUniform: return spv::DecorationBlock;
249 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
250 case glslang::EvqVaryingIn: return spv::DecorationBlock;
251 case glslang::EvqVaryingOut: return spv::DecorationBlock;
252 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700253 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600254 break;
255 }
256 }
257
258 return (spv::Decoration)spv::BadValue;
259}
260
261// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700262spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600263{
264 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700265 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600266 case glslang::ElmRowMajor:
267 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700268 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600269 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700270 default:
271 // opaque layouts don't need a majorness
272 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600273 }
274 } else {
275 switch (type.getBasicType()) {
276 default:
277 return (spv::Decoration)spv::BadValue;
278 break;
279 case glslang::EbtBlock:
280 switch (type.getQualifier().storage) {
281 case glslang::EvqUniform:
282 case glslang::EvqBuffer:
283 switch (type.getQualifier().layoutPacking) {
284 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600285 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
286 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600287 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600288 }
289 case glslang::EvqVaryingIn:
290 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700291 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return (spv::Decoration)spv::BadValue;
293 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700294 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600295 return (spv::Decoration)spv::BadValue;
296 }
297 }
298 }
299}
300
301// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700302// Returns spv::Decoration(spv::BadValue) when no decoration
303// should be applied.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700304spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600305{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700306 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700307 // Smooth decoration doesn't exist in SPIR-V 1.0
308 return (spv::Decoration)spv::BadValue;
309 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700310 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700311 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700312 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600313 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700314 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700316 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600317 return spv::DecorationCentroid;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700318 else if (qualifier.sample)
John Kessenich140f3df2015-06-26 16:58:36 -0600319 return spv::DecorationSample;
320 else
321 return (spv::Decoration)spv::BadValue;
322}
323
John Kessenich92187592016-02-01 13:45:25 -0700324// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700325spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600326{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700327 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600328 return spv::DecorationInvariant;
329 else
330 return (spv::Decoration)spv::BadValue;
331}
332
333// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700334spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600335{
336 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700337 case glslang::EbvPointSize:
338 switch (glslangIntermediate->getStage()) {
339 case EShLangGeometry:
340 builder.addCapability(spv::CapabilityGeometryPointSize);
341 break;
342 case EShLangTessControl:
343 case EShLangTessEvaluation:
344 builder.addCapability(spv::CapabilityTessellationPointSize);
345 break;
346 }
347 return spv::BuiltInPointSize;
348
349 case glslang::EbvClipDistance:
350 builder.addCapability(spv::CapabilityClipDistance);
351 return spv::BuiltInClipDistance;
352
353 case glslang::EbvCullDistance:
354 builder.addCapability(spv::CapabilityCullDistance);
355 return spv::BuiltInCullDistance;
356
357 case glslang::EbvViewportIndex:
358 // TODO: builder.addCapability(spv::CapabilityMultiViewport);
359 return spv::BuiltInViewportIndex;
360
John Kessenich140f3df2015-06-26 16:58:36 -0600361 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600362 case glslang::EbvVertexId: return spv::BuiltInVertexId;
363 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600364 case glslang::EbvBaseVertex:
365 case glslang::EbvBaseInstance:
366 case glslang::EbvDrawId:
367 // TODO: Add SPIR-V builtin ID.
368 spv::MissingFunctionality("Draw parameters");
369 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600370 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
371 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
372 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600373 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
374 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
375 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
376 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
377 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
378 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
379 case glslang::EbvFace: return spv::BuiltInFrontFacing;
380 case glslang::EbvSampleId: return spv::BuiltInSampleId;
381 case glslang::EbvSamplePosition: return spv::BuiltInSamplePosition;
382 case glslang::EbvSampleMask: return spv::BuiltInSampleMask;
John Kessenich140f3df2015-06-26 16:58:36 -0600383 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
384 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
385 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
386 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
387 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
388 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
389 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
390 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
391 default: return (spv::BuiltIn)spv::BadValue;
392 }
393}
394
Rex Xufc618912015-09-09 16:42:49 +0800395// Translate glslang image layout format to SPIR-V image format.
396spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
397{
398 assert(type.getBasicType() == glslang::EbtSampler);
399
400 switch (type.getQualifier().layoutFormat) {
401 case glslang::ElfNone: return spv::ImageFormatUnknown;
402 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
403 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
404 case glslang::ElfR32f: return spv::ImageFormatR32f;
405 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
406 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
407 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
408 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
409 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
410 case glslang::ElfR16f: return spv::ImageFormatR16f;
411 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
412 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
413 case glslang::ElfRg16: return spv::ImageFormatRg16;
414 case glslang::ElfRg8: return spv::ImageFormatRg8;
415 case glslang::ElfR16: return spv::ImageFormatR16;
416 case glslang::ElfR8: return spv::ImageFormatR8;
417 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
418 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
419 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
420 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
421 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
422 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
423 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
424 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
425 case glslang::ElfR32i: return spv::ImageFormatR32i;
426 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
427 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
428 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
429 case glslang::ElfR16i: return spv::ImageFormatR16i;
430 case glslang::ElfR8i: return spv::ImageFormatR8i;
431 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
432 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
433 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
434 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
435 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
436 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
437 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
438 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
439 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
440 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
441 default: return (spv::ImageFormat)spv::BadValue;
442 }
443}
444
John Kesseniche0b6cad2015-12-24 10:30:13 -0700445void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
446{
447 if (child.layoutMatrix == glslang::ElmNone)
448 child.layoutMatrix = parent.layoutMatrix;
449
450 if (parent.invariant)
451 child.invariant = true;
452 if (parent.nopersp)
453 child.nopersp = true;
454 if (parent.flat)
455 child.flat = true;
456 if (parent.centroid)
457 child.centroid = true;
458 if (parent.patch)
459 child.patch = true;
460 if (parent.sample)
461 child.sample = true;
John Kessenich7b9fa252016-01-21 18:56:57 -0700462
463 child.layoutLocation = parent.layoutLocation;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700464}
465
466bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
467{
John Kessenich7b9fa252016-01-21 18:56:57 -0700468 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700469 // - struct members can inherit from a struct declaration
470 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
471 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700472 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700473}
474
John Kessenich140f3df2015-06-26 16:58:36 -0600475//
476// Implement the TGlslangToSpvTraverser class.
477//
478
479TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
480 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700481 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600482 inMain(false), mainTerminated(false), linkageOnly(false),
483 glslangIntermediate(glslangIntermediate)
484{
485 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
486
487 builder.clearAccessChain();
488 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
489 stdBuiltins = builder.import("GLSL.std.450");
490 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
491 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700492 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600493
494 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600495 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
496 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600497 builder.addSourceExtension(it->c_str());
498
499 // Add the top-level modes for this shader.
500
John Kessenich92187592016-02-01 13:45:25 -0700501 if (glslangIntermediate->getXfbMode()) {
502 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600503 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700504 }
John Kessenich140f3df2015-06-26 16:58:36 -0600505
506 unsigned int mode;
507 switch (glslangIntermediate->getStage()) {
508 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600509 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600510 break;
511
512 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600513 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600514 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
515 break;
516
517 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600518 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600519 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700520 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
521 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
522 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600523 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600524 }
525 if (mode != spv::BadValue)
526 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
527
John Kesseniche6903322015-10-13 16:29:02 -0600528 switch (glslangIntermediate->getVertexSpacing()) {
529 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
530 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
531 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
532 default: mode = spv::BadValue; break;
533 }
534 if (mode != spv::BadValue)
535 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
536
537 switch (glslangIntermediate->getVertexOrder()) {
538 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
539 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
540 default: mode = spv::BadValue; break;
541 }
542 if (mode != spv::BadValue)
543 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
544
545 if (glslangIntermediate->getPointMode())
546 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600547 break;
548
549 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600550 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600551 switch (glslangIntermediate->getInputPrimitive()) {
552 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
553 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
554 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700555 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600556 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
557 default: mode = spv::BadValue; break;
558 }
559 if (mode != spv::BadValue)
560 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600561
John Kessenich140f3df2015-06-26 16:58:36 -0600562 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
563
564 switch (glslangIntermediate->getOutputPrimitive()) {
565 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
566 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
567 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
568 default: mode = spv::BadValue; break;
569 }
570 if (mode != spv::BadValue)
571 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
572 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
573 break;
574
575 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600576 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600577 if (glslangIntermediate->getPixelCenterInteger())
578 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600579
John Kessenich140f3df2015-06-26 16:58:36 -0600580 if (glslangIntermediate->getOriginUpperLeft())
581 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600582 else
583 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600584
585 if (glslangIntermediate->getEarlyFragmentTests())
586 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
587
588 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600589 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
590 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
591 default: mode = spv::BadValue; break;
592 }
593 if (mode != spv::BadValue)
594 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
595
596 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
597 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600598 break;
599
600 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600601 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600602 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
603 glslangIntermediate->getLocalSize(1),
604 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600605 break;
606
607 default:
608 break;
609 }
610
611}
612
John Kessenich7ba63412015-12-20 17:37:07 -0700613// Finish everything and dump
614void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
615{
616 // finish off the entry-point SPV instruction by adding the Input/Output <id>
617 for (auto it : iOSet)
618 entryPoint->addIdOperand(it);
619
620 builder.dump(out);
621}
622
John Kessenich140f3df2015-06-26 16:58:36 -0600623TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
624{
625 if (! mainTerminated) {
626 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
627 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600628 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600629 }
630}
631
632//
633// Implement the traversal functions.
634//
635// Return true from interior nodes to have the external traversal
636// continue on to children. Return false if children were
637// already processed.
638//
639
640//
641// Symbols can turn into
642// - uniform/input reads
643// - output writes
644// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
645// - something simple that degenerates into the last bullet
646//
647void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
648{
649 // getSymbolId() will set up all the IO decorations on the first call.
650 // Formal function parameters were mapped during makeFunctions().
651 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700652
653 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
654 if (builder.isPointer(id)) {
655 spv::StorageClass sc = builder.getStorageClass(id);
656 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
657 iOSet.insert(id);
658 }
659
660 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600661 if (! linkageOnly) {
662 // Prepare to generate code for the access
663
664 // L-value chains will be computed left to right. We're on the symbol now,
665 // which is the left-most part of the access chain, so now is "clear" time,
666 // followed by setting the base.
667 builder.clearAccessChain();
668
669 // For now, we consider all user variables as being in memory, so they are pointers,
670 // except for "const in" arguments to a function, which are an intermediate object.
671 // See comments in handleUserFunctionCall().
672 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
673 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
674 builder.setAccessChainRValue(id);
675 else
676 builder.setAccessChainLValue(id);
677 }
678}
679
680bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
681{
682 // First, handle special cases
683 switch (node->getOp()) {
684 case glslang::EOpAssign:
685 case glslang::EOpAddAssign:
686 case glslang::EOpSubAssign:
687 case glslang::EOpMulAssign:
688 case glslang::EOpVectorTimesMatrixAssign:
689 case glslang::EOpVectorTimesScalarAssign:
690 case glslang::EOpMatrixTimesScalarAssign:
691 case glslang::EOpMatrixTimesMatrixAssign:
692 case glslang::EOpDivAssign:
693 case glslang::EOpModAssign:
694 case glslang::EOpAndAssign:
695 case glslang::EOpInclusiveOrAssign:
696 case glslang::EOpExclusiveOrAssign:
697 case glslang::EOpLeftShiftAssign:
698 case glslang::EOpRightShiftAssign:
699 // A bin-op assign "a += b" means the same thing as "a = a + b"
700 // where a is evaluated before b. For a simple assignment, GLSL
701 // says to evaluate the left before the right. So, always, left
702 // node then right node.
703 {
704 // get the left l-value, save it away
705 builder.clearAccessChain();
706 node->getLeft()->traverse(this);
707 spv::Builder::AccessChain lValue = builder.getAccessChain();
708
709 // evaluate the right
710 builder.clearAccessChain();
711 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700712 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600713
714 if (node->getOp() != glslang::EOpAssign) {
715 // the left is also an r-value
716 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700717 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600718
719 // do the operation
720 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
721 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
722 node->getType().getBasicType());
723
724 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700725 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600726 }
727
728 // store the result
729 builder.setAccessChain(lValue);
730 builder.accessChainStore(rValue);
731
732 // assignments are expressions having an rValue after they are evaluated...
733 builder.clearAccessChain();
734 builder.setAccessChainRValue(rValue);
735 }
736 return false;
737 case glslang::EOpIndexDirect:
738 case glslang::EOpIndexDirectStruct:
739 {
740 // Get the left part of the access chain.
741 node->getLeft()->traverse(this);
742
743 // Add the next element in the chain
744
John Kessenich55e7d112015-11-15 21:33:39 -0700745 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600746 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
747 // This may be, e.g., an anonymous block-member selection, which generally need
748 // index remapping due to hidden members in anonymous blocks.
749 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700750 assert(remapper.size() > 0);
751 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600752 }
753
754 if (! node->getLeft()->getType().isArray() &&
755 node->getLeft()->getType().isVector() &&
756 node->getOp() == glslang::EOpIndexDirect) {
757 // This is essentially a hard-coded vector swizzle of size 1,
758 // so short circuit the access-chain stuff with a swizzle.
759 std::vector<unsigned> swizzle;
760 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600761 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600762 } else {
763 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600764 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600765 }
766 }
767 return false;
768 case glslang::EOpIndexIndirect:
769 {
770 // Structure or array or vector indirection.
771 // Will use native SPIR-V access-chain for struct and array indirection;
772 // matrices are arrays of vectors, so will also work for a matrix.
773 // Will use the access chain's 'component' for variable index into a vector.
774
775 // This adapter is building access chains left to right.
776 // Set up the access chain to the left.
777 node->getLeft()->traverse(this);
778
779 // save it so that computing the right side doesn't trash it
780 spv::Builder::AccessChain partial = builder.getAccessChain();
781
782 // compute the next index in the chain
783 builder.clearAccessChain();
784 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700785 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600786
787 // restore the saved access chain
788 builder.setAccessChain(partial);
789
790 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600791 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600792 else
John Kessenichfa668da2015-09-13 14:46:30 -0600793 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600794 }
795 return false;
796 case glslang::EOpVectorSwizzle:
797 {
798 node->getLeft()->traverse(this);
799 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
800 std::vector<unsigned> swizzle;
801 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
802 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600803 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600804 }
805 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600806 case glslang::EOpLogicalOr:
807 case glslang::EOpLogicalAnd:
808 {
809
810 // These may require short circuiting, but can sometimes be done as straight
811 // binary operations. The right operand must be short circuited if it has
812 // side effects, and should probably be if it is complex.
813 if (isTrivial(node->getRight()->getAsTyped()))
814 break; // handle below as a normal binary operation
815 // otherwise, we need to do dynamic short circuiting on the right operand
816 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
817 builder.clearAccessChain();
818 builder.setAccessChainRValue(result);
819 }
820 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600821 default:
822 break;
823 }
824
825 // Assume generic binary op...
826
John Kessenich32cfd492016-02-02 12:37:46 -0700827 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600828 builder.clearAccessChain();
829 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700830 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600831
John Kessenich32cfd492016-02-02 12:37:46 -0700832 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600833 builder.clearAccessChain();
834 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700835 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600836
John Kessenich32cfd492016-02-02 12:37:46 -0700837 // get result
838 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
839 convertGlslangToSpvType(node->getType()), left, right,
840 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600841
John Kessenich50e57562015-12-21 21:21:11 -0700842 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600843 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700844 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700845 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600846 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600847 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600848 return false;
849 }
John Kessenich140f3df2015-06-26 16:58:36 -0600850}
851
852bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
853{
John Kessenichfc51d282015-08-19 13:34:18 -0600854 spv::Id result = spv::NoResult;
855
856 // try texturing first
857 result = createImageTextureFunctionCall(node);
858 if (result != spv::NoResult) {
859 builder.clearAccessChain();
860 builder.setAccessChainRValue(result);
861
862 return false; // done with this node
863 }
864
865 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600866
867 if (node->getOp() == glslang::EOpArrayLength) {
868 // Quite special; won't want to evaluate the operand.
869
870 // Normal .length() would have been constant folded by the front-end.
871 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600872 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600873 assert(node->getOperand()->getType().isRuntimeSizedArray());
874 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
875 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600876 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
877 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600878
879 builder.clearAccessChain();
880 builder.setAccessChainRValue(length);
881
882 return false;
883 }
884
John Kessenichfc51d282015-08-19 13:34:18 -0600885 // Start by evaluating the operand
886
John Kessenich140f3df2015-06-26 16:58:36 -0600887 builder.clearAccessChain();
888 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800889
Rex Xufc618912015-09-09 16:42:49 +0800890 spv::Id operand = spv::NoResult;
891
892 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
893 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800894 node->getOp() == glslang::EOpAtomicCounter ||
895 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800896 operand = builder.accessChainGetLValue(); // Special case l-value operands
897 else
John Kessenich32cfd492016-02-02 12:37:46 -0700898 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600899
900 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
901
902 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600903 if (! result)
904 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600905
906 // if not, then possibly an operation
907 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700908 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600909
910 if (result) {
911 builder.clearAccessChain();
912 builder.setAccessChainRValue(result);
913
914 return false; // done with this node
915 }
916
917 // it must be a special case, check...
918 switch (node->getOp()) {
919 case glslang::EOpPostIncrement:
920 case glslang::EOpPostDecrement:
921 case glslang::EOpPreIncrement:
922 case glslang::EOpPreDecrement:
923 {
924 // we need the integer value "1" or the floating point "1.0" to add/subtract
925 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
926 builder.makeFloatConstant(1.0F) :
927 builder.makeIntConstant(1);
928 glslang::TOperator op;
929 if (node->getOp() == glslang::EOpPreIncrement ||
930 node->getOp() == glslang::EOpPostIncrement)
931 op = glslang::EOpAdd;
932 else
933 op = glslang::EOpSub;
934
935 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
936 convertGlslangToSpvType(node->getType()), operand, one,
937 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700938 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600939
940 // The result of operation is always stored, but conditionally the
941 // consumed result. The consumed result is always an r-value.
942 builder.accessChainStore(result);
943 builder.clearAccessChain();
944 if (node->getOp() == glslang::EOpPreIncrement ||
945 node->getOp() == glslang::EOpPreDecrement)
946 builder.setAccessChainRValue(result);
947 else
948 builder.setAccessChainRValue(operand);
949 }
950
951 return false;
952
953 case glslang::EOpEmitStreamVertex:
954 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
955 return false;
956 case glslang::EOpEndStreamPrimitive:
957 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
958 return false;
959
960 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700961 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -0700962 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -0600963 }
John Kessenich140f3df2015-06-26 16:58:36 -0600964}
965
966bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
967{
John Kessenichfc51d282015-08-19 13:34:18 -0600968 spv::Id result = spv::NoResult;
969
970 // try texturing
971 result = createImageTextureFunctionCall(node);
972 if (result != spv::NoResult) {
973 builder.clearAccessChain();
974 builder.setAccessChainRValue(result);
975
976 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600977 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800978 // "imageStore" is a special case, which has no result
979 return false;
980 }
John Kessenichfc51d282015-08-19 13:34:18 -0600981
John Kessenich140f3df2015-06-26 16:58:36 -0600982 glslang::TOperator binOp = glslang::EOpNull;
983 bool reduceComparison = true;
984 bool isMatrix = false;
985 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600986 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600987
988 assert(node->getOp());
989
990 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
991
992 switch (node->getOp()) {
993 case glslang::EOpSequence:
994 {
995 if (preVisit)
996 ++sequenceDepth;
997 else
998 --sequenceDepth;
999
1000 if (sequenceDepth == 1) {
1001 // If this is the parent node of all the functions, we want to see them
1002 // early, so all call points have actual SPIR-V functions to reference.
1003 // In all cases, still let the traverser visit the children for us.
1004 makeFunctions(node->getAsAggregate()->getSequence());
1005
1006 // Also, we want all globals initializers to go into the entry of main(), before
1007 // anything else gets there, so visit out of order, doing them all now.
1008 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1009
1010 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1011 // so do them manually.
1012 visitFunctions(node->getAsAggregate()->getSequence());
1013
1014 return false;
1015 }
1016
1017 return true;
1018 }
1019 case glslang::EOpLinkerObjects:
1020 {
1021 if (visit == glslang::EvPreVisit)
1022 linkageOnly = true;
1023 else
1024 linkageOnly = false;
1025
1026 return true;
1027 }
1028 case glslang::EOpComma:
1029 {
1030 // processing from left to right naturally leaves the right-most
1031 // lying around in the access chain
1032 glslang::TIntermSequence& glslangOperands = node->getSequence();
1033 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1034 glslangOperands[i]->traverse(this);
1035
1036 return false;
1037 }
1038 case glslang::EOpFunction:
1039 if (visit == glslang::EvPreVisit) {
1040 if (isShaderEntrypoint(node)) {
1041 inMain = true;
1042 builder.setBuildPoint(shaderEntry->getLastBlock());
1043 } else {
1044 handleFunctionEntry(node);
1045 }
1046 } else {
1047 if (inMain)
1048 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001049 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001050 inMain = false;
1051 }
1052
1053 return true;
1054 case glslang::EOpParameters:
1055 // Parameters will have been consumed by EOpFunction processing, but not
1056 // the body, so we still visited the function node's children, making this
1057 // child redundant.
1058 return false;
1059 case glslang::EOpFunctionCall:
1060 {
1061 if (node->isUserDefined())
1062 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001063 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001064 builder.clearAccessChain();
1065 builder.setAccessChainRValue(result);
1066
1067 return false;
1068 }
1069 case glslang::EOpConstructMat2x2:
1070 case glslang::EOpConstructMat2x3:
1071 case glslang::EOpConstructMat2x4:
1072 case glslang::EOpConstructMat3x2:
1073 case glslang::EOpConstructMat3x3:
1074 case glslang::EOpConstructMat3x4:
1075 case glslang::EOpConstructMat4x2:
1076 case glslang::EOpConstructMat4x3:
1077 case glslang::EOpConstructMat4x4:
1078 case glslang::EOpConstructDMat2x2:
1079 case glslang::EOpConstructDMat2x3:
1080 case glslang::EOpConstructDMat2x4:
1081 case glslang::EOpConstructDMat3x2:
1082 case glslang::EOpConstructDMat3x3:
1083 case glslang::EOpConstructDMat3x4:
1084 case glslang::EOpConstructDMat4x2:
1085 case glslang::EOpConstructDMat4x3:
1086 case glslang::EOpConstructDMat4x4:
1087 isMatrix = true;
1088 // fall through
1089 case glslang::EOpConstructFloat:
1090 case glslang::EOpConstructVec2:
1091 case glslang::EOpConstructVec3:
1092 case glslang::EOpConstructVec4:
1093 case glslang::EOpConstructDouble:
1094 case glslang::EOpConstructDVec2:
1095 case glslang::EOpConstructDVec3:
1096 case glslang::EOpConstructDVec4:
1097 case glslang::EOpConstructBool:
1098 case glslang::EOpConstructBVec2:
1099 case glslang::EOpConstructBVec3:
1100 case glslang::EOpConstructBVec4:
1101 case glslang::EOpConstructInt:
1102 case glslang::EOpConstructIVec2:
1103 case glslang::EOpConstructIVec3:
1104 case glslang::EOpConstructIVec4:
1105 case glslang::EOpConstructUint:
1106 case glslang::EOpConstructUVec2:
1107 case glslang::EOpConstructUVec3:
1108 case glslang::EOpConstructUVec4:
1109 case glslang::EOpConstructStruct:
1110 {
1111 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001112 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001113 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1114 spv::Id constructed;
1115 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1116 std::vector<spv::Id> constituents;
1117 for (int c = 0; c < (int)arguments.size(); ++c)
1118 constituents.push_back(arguments[c]);
1119 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001120 } else if (isMatrix)
1121 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1122 else
1123 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001124
1125 builder.clearAccessChain();
1126 builder.setAccessChainRValue(constructed);
1127
1128 return false;
1129 }
1130
1131 // These six are component-wise compares with component-wise results.
1132 // Forward on to createBinaryOperation(), requesting a vector result.
1133 case glslang::EOpLessThan:
1134 case glslang::EOpGreaterThan:
1135 case glslang::EOpLessThanEqual:
1136 case glslang::EOpGreaterThanEqual:
1137 case glslang::EOpVectorEqual:
1138 case glslang::EOpVectorNotEqual:
1139 {
1140 // Map the operation to a binary
1141 binOp = node->getOp();
1142 reduceComparison = false;
1143 switch (node->getOp()) {
1144 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1145 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1146 default: binOp = node->getOp(); break;
1147 }
1148
1149 break;
1150 }
1151 case glslang::EOpMul:
1152 // compontent-wise matrix multiply
1153 binOp = glslang::EOpMul;
1154 break;
1155 case glslang::EOpOuterProduct:
1156 // two vectors multiplied to make a matrix
1157 binOp = glslang::EOpOuterProduct;
1158 break;
1159 case glslang::EOpDot:
1160 {
1161 // for scalar dot product, use multiply
1162 glslang::TIntermSequence& glslangOperands = node->getSequence();
1163 if (! glslangOperands[0]->getAsTyped()->isVector())
1164 binOp = glslang::EOpMul;
1165 break;
1166 }
1167 case glslang::EOpMod:
1168 // when an aggregate, this is the floating-point mod built-in function,
1169 // which can be emitted by the one in createBinaryOperation()
1170 binOp = glslang::EOpMod;
1171 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001172 case glslang::EOpEmitVertex:
1173 case glslang::EOpEndPrimitive:
1174 case glslang::EOpBarrier:
1175 case glslang::EOpMemoryBarrier:
1176 case glslang::EOpMemoryBarrierAtomicCounter:
1177 case glslang::EOpMemoryBarrierBuffer:
1178 case glslang::EOpMemoryBarrierImage:
1179 case glslang::EOpMemoryBarrierShared:
1180 case glslang::EOpGroupMemoryBarrier:
1181 noReturnValue = true;
1182 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1183 break;
1184
John Kessenich426394d2015-07-23 10:22:48 -06001185 case glslang::EOpAtomicAdd:
1186 case glslang::EOpAtomicMin:
1187 case glslang::EOpAtomicMax:
1188 case glslang::EOpAtomicAnd:
1189 case glslang::EOpAtomicOr:
1190 case glslang::EOpAtomicXor:
1191 case glslang::EOpAtomicExchange:
1192 case glslang::EOpAtomicCompSwap:
1193 atomic = true;
1194 break;
1195
John Kessenich140f3df2015-06-26 16:58:36 -06001196 default:
1197 break;
1198 }
1199
1200 //
1201 // See if it maps to a regular operation.
1202 //
John Kessenich140f3df2015-06-26 16:58:36 -06001203 if (binOp != glslang::EOpNull) {
1204 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1205 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1206 assert(left && right);
1207
1208 builder.clearAccessChain();
1209 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001210 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001211
1212 builder.clearAccessChain();
1213 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001214 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001215
1216 result = createBinaryOperation(binOp, precision,
1217 convertGlslangToSpvType(node->getType()), leftId, rightId,
1218 left->getType().getBasicType(), reduceComparison);
1219
1220 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001221 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001222 builder.clearAccessChain();
1223 builder.setAccessChainRValue(result);
1224
1225 return false;
1226 }
1227
John Kessenich426394d2015-07-23 10:22:48 -06001228 //
1229 // Create the list of operands.
1230 //
John Kessenich140f3df2015-06-26 16:58:36 -06001231 glslang::TIntermSequence& glslangOperands = node->getSequence();
1232 std::vector<spv::Id> operands;
1233 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1234 builder.clearAccessChain();
1235 glslangOperands[arg]->traverse(this);
1236
1237 // special case l-value operands; there are just a few
1238 bool lvalue = false;
1239 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001240 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001241 case glslang::EOpModf:
1242 if (arg == 1)
1243 lvalue = true;
1244 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001245 case glslang::EOpInterpolateAtSample:
1246 case glslang::EOpInterpolateAtOffset:
1247 if (arg == 0)
1248 lvalue = true;
1249 break;
Rex Xud4782c12015-09-06 16:30:11 +08001250 case glslang::EOpAtomicAdd:
1251 case glslang::EOpAtomicMin:
1252 case glslang::EOpAtomicMax:
1253 case glslang::EOpAtomicAnd:
1254 case glslang::EOpAtomicOr:
1255 case glslang::EOpAtomicXor:
1256 case glslang::EOpAtomicExchange:
1257 case glslang::EOpAtomicCompSwap:
1258 if (arg == 0)
1259 lvalue = true;
1260 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001261 case glslang::EOpAddCarry:
1262 case glslang::EOpSubBorrow:
1263 if (arg == 2)
1264 lvalue = true;
1265 break;
1266 case glslang::EOpUMulExtended:
1267 case glslang::EOpIMulExtended:
1268 if (arg >= 2)
1269 lvalue = true;
1270 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001271 default:
1272 break;
1273 }
1274 if (lvalue)
1275 operands.push_back(builder.accessChainGetLValue());
1276 else
John Kessenich32cfd492016-02-02 12:37:46 -07001277 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001278 }
John Kessenich426394d2015-07-23 10:22:48 -06001279
1280 if (atomic) {
1281 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001282 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001283 } else {
1284 // Pass through to generic operations.
1285 switch (glslangOperands.size()) {
1286 case 0:
1287 result = createNoArgOperation(node->getOp());
1288 break;
1289 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001290 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001291 break;
1292 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001293 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001294 break;
1295 }
John Kessenich140f3df2015-06-26 16:58:36 -06001296 }
1297
1298 if (noReturnValue)
1299 return false;
1300
1301 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001302 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001303 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001304 } else {
1305 builder.clearAccessChain();
1306 builder.setAccessChainRValue(result);
1307 return false;
1308 }
1309}
1310
1311bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1312{
1313 // This path handles both if-then-else and ?:
1314 // The if-then-else has a node type of void, while
1315 // ?: has a non-void node type
1316 spv::Id result = 0;
1317 if (node->getBasicType() != glslang::EbtVoid) {
1318 // don't handle this as just on-the-fly temporaries, because there will be two names
1319 // and better to leave SSA to later passes
1320 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1321 }
1322
1323 // emit the condition before doing anything with selection
1324 node->getCondition()->traverse(this);
1325
1326 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001327 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001328
1329 if (node->getTrueBlock()) {
1330 // emit the "then" statement
1331 node->getTrueBlock()->traverse(this);
1332 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001333 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001334 }
1335
1336 if (node->getFalseBlock()) {
1337 ifBuilder.makeBeginElse();
1338 // emit the "else" statement
1339 node->getFalseBlock()->traverse(this);
1340 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001341 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001342 }
1343
1344 ifBuilder.makeEndIf();
1345
1346 if (result) {
1347 // GLSL only has r-values as the result of a :?, but
1348 // if we have an l-value, that can be more efficient if it will
1349 // become the base of a complex r-value expression, because the
1350 // next layer copies r-values into memory to use the access-chain mechanism
1351 builder.clearAccessChain();
1352 builder.setAccessChainLValue(result);
1353 }
1354
1355 return false;
1356}
1357
1358bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1359{
1360 // emit and get the condition before doing anything with switch
1361 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001362 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001363
1364 // browse the children to sort out code segments
1365 int defaultSegment = -1;
1366 std::vector<TIntermNode*> codeSegments;
1367 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1368 std::vector<int> caseValues;
1369 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1370 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1371 TIntermNode* child = *c;
1372 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001373 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001374 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001375 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001376 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1377 } else
1378 codeSegments.push_back(child);
1379 }
1380
1381 // handle the case where the last code segment is missing, due to no code
1382 // statements between the last case and the end of the switch statement
1383 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1384 (int)codeSegments.size() == defaultSegment)
1385 codeSegments.push_back(nullptr);
1386
1387 // make the switch statement
1388 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001389 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001390
1391 // emit all the code in the segments
1392 breakForLoop.push(false);
1393 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1394 builder.nextSwitchSegment(segmentBlocks, s);
1395 if (codeSegments[s])
1396 codeSegments[s]->traverse(this);
1397 else
1398 builder.addSwitchBreak();
1399 }
1400 breakForLoop.pop();
1401
1402 builder.endSwitch(segmentBlocks);
1403
1404 return false;
1405}
1406
1407void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1408{
1409 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001410 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001411
1412 builder.clearAccessChain();
1413 builder.setAccessChainRValue(constant);
1414}
1415
1416bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1417{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001418 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001419 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001420 // Spec requires back edges to target header blocks, and every header block
1421 // must dominate its merge block. Make a header block first to ensure these
1422 // conditions are met. By definition, it will contain OpLoopMerge, followed
1423 // by a block-ending branch. But we don't want to put any other body/test
1424 // instructions in it, since the body/test may have arbitrary instructions,
1425 // including merges of its own.
1426 builder.setBuildPoint(&blocks.head);
1427 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001428 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001429 spv::Block& test = builder.makeNewBlock();
1430 builder.createBranch(&test);
1431
1432 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001433 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001434 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001435 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001436 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1437
1438 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001439 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001440 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001441 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001442 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001443 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001444
1445 builder.setBuildPoint(&blocks.continue_target);
1446 if (node->getTerminal())
1447 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001448 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001449 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001450 builder.createBranch(&blocks.body);
1451
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001452 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001453 builder.setBuildPoint(&blocks.body);
1454 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001455 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001456 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001457 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001458
1459 builder.setBuildPoint(&blocks.continue_target);
1460 if (node->getTerminal())
1461 node->getTerminal()->traverse(this);
1462 if (node->getTest()) {
1463 node->getTest()->traverse(this);
1464 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001465 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001466 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001467 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001468 // TODO: unless there was a break/return/discard instruction
1469 // somewhere in the body, this is an infinite loop, so we should
1470 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001471 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001472 }
John Kessenich140f3df2015-06-26 16:58:36 -06001473 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001474 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001475 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001476 return false;
1477}
1478
1479bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1480{
1481 if (node->getExpression())
1482 node->getExpression()->traverse(this);
1483
1484 switch (node->getFlowOp()) {
1485 case glslang::EOpKill:
1486 builder.makeDiscard();
1487 break;
1488 case glslang::EOpBreak:
1489 if (breakForLoop.top())
1490 builder.createLoopExit();
1491 else
1492 builder.addSwitchBreak();
1493 break;
1494 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001495 builder.createLoopContinue();
1496 break;
1497 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001498 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001499 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001500 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001501 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001502
1503 builder.clearAccessChain();
1504 break;
1505
1506 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001507 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001508 break;
1509 }
1510
1511 return false;
1512}
1513
1514spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1515{
1516 // First, steer off constants, which are not SPIR-V variables, but
1517 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001518 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001519 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001520 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001521 }
1522
1523 // Now, handle actual variables
1524 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1525 spv::Id spvType = convertGlslangToSpvType(node->getType());
1526
1527 const char* name = node->getName().c_str();
1528 if (glslang::IsAnonymous(name))
1529 name = "";
1530
1531 return builder.createVariable(storageClass, spvType, name);
1532}
1533
1534// Return type Id of the sampled type.
1535spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1536{
1537 switch (sampler.type) {
1538 case glslang::EbtFloat: return builder.makeFloatType(32);
1539 case glslang::EbtInt: return builder.makeIntType(32);
1540 case glslang::EbtUint: return builder.makeUintType(32);
1541 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001542 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001543 return builder.makeFloatType(32);
1544 }
1545}
1546
John Kessenich3ac051e2015-12-20 11:29:16 -07001547// Convert from a glslang type to an SPV type, by calling into a
1548// recursive version of this function. This establishes the inherited
1549// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001550spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1551{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001552 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001553}
1554
1555// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001556// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001557spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001558{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001559 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001560
1561 switch (type.getBasicType()) {
1562 case glslang::EbtVoid:
1563 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001564 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001565 break;
1566 case glslang::EbtFloat:
1567 spvType = builder.makeFloatType(32);
1568 break;
1569 case glslang::EbtDouble:
1570 spvType = builder.makeFloatType(64);
1571 break;
1572 case glslang::EbtBool:
1573 spvType = builder.makeBoolType();
1574 break;
1575 case glslang::EbtInt:
1576 spvType = builder.makeIntType(32);
1577 break;
1578 case glslang::EbtUint:
1579 spvType = builder.makeUintType(32);
1580 break;
John Kessenich426394d2015-07-23 10:22:48 -06001581 case glslang::EbtAtomicUint:
1582 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1583 spvType = builder.makeUintType(32);
1584 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001585 case glslang::EbtSampler:
1586 {
1587 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001588 // an image is present, make its type
1589 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1590 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001591 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001592 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001593 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001594 }
John Kessenich140f3df2015-06-26 16:58:36 -06001595 break;
1596 case glslang::EbtStruct:
1597 case glslang::EbtBlock:
1598 {
1599 // If we've seen this struct type, return it
1600 const glslang::TTypeList* glslangStruct = type.getStruct();
1601 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001602
1603 // Try to share structs for different layouts, but not yet for other
1604 // kinds of qualification (primarily not yet including interpolant qualification).
1605 if (! HasNonLayoutQualifiers(qualifier))
1606 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1607 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001608 break;
1609
1610 // else, we haven't seen it...
1611
1612 // Create a vector of struct types for SPIR-V to consume
1613 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1614 if (type.getBasicType() == glslang::EbtBlock)
1615 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001616 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001617 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1618 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1619 if (glslangType.hiddenMember()) {
1620 ++memberDelta;
1621 if (type.getBasicType() == glslang::EbtBlock)
1622 memberRemapper[glslangStruct][i] = -1;
1623 } else {
1624 if (type.getBasicType() == glslang::EbtBlock)
1625 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001626 // modify just this child's view of the qualifier
1627 glslang::TQualifier subQualifier = glslangType.getQualifier();
1628 InheritQualifiers(subQualifier, qualifier);
John Kessenich7b9fa252016-01-21 18:56:57 -07001629 if (qualifier.hasLocation()) {
1630 subQualifier.layoutLocation += locationOffset;
1631 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1632 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001633 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001634 }
1635 }
1636
1637 // Make the SPIR-V type
1638 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001639 if (! HasNonLayoutQualifiers(qualifier))
1640 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001641
1642 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001643 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001644 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001645 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1646 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1647 int member = i;
1648 if (type.getBasicType() == glslang::EbtBlock)
1649 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001650
John Kesseniche0b6cad2015-12-24 10:30:13 -07001651 // modify just this child's view of the qualifier
1652 glslang::TQualifier subQualifier = glslangType.getQualifier();
1653 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001654
John Kessenich140f3df2015-06-26 16:58:36 -06001655 // using -1 above to indicate a hidden member
1656 if (member >= 0) {
1657 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001658 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001659 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001660 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1661 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich7b9fa252016-01-21 18:56:57 -07001662 if (qualifier.hasLocation()) {
1663 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, qualifier.layoutLocation + locationOffset);
1664 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1665 }
John Kessenich140f3df2015-06-26 16:58:36 -06001666 if (glslangType.getQualifier().hasComponent())
1667 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1668 if (glslangType.getQualifier().hasXfbOffset())
1669 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001670 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001671 // figure out what to do with offset, which is accumulating
1672 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001673 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001674 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001675 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001676 offset = nextOffset;
1677 }
John Kessenich140f3df2015-06-26 16:58:36 -06001678
John Kessenichf85e8062015-12-19 13:57:10 -07001679 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001680 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001681
John Kessenich140f3df2015-06-26 16:58:36 -06001682 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001683 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1684 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001685 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001686 }
1687 }
1688
1689 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001690 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001691 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001692 if (type.getQualifier().hasStream()) {
1693 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001694 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001695 }
John Kessenich140f3df2015-06-26 16:58:36 -06001696 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001697 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001698 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001699 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001700 if (type.getQualifier().hasXfbBuffer())
1701 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1702 }
1703 }
1704 break;
1705 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001706 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001707 break;
1708 }
1709
1710 if (type.isMatrix())
1711 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1712 else {
1713 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1714 if (type.getVectorSize() > 1)
1715 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1716 }
1717
1718 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001719 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1720
John Kessenichc9a80832015-09-12 12:17:44 -06001721 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001722 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001723 // We need to decorate array strides for types needing explicit layout, except blocks.
1724 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001725 // Use a dummy glslang type for querying internal strides of
1726 // arrays of arrays, but using just a one-dimensional array.
1727 glslang::TType simpleArrayType(type, 0); // deference type of the array
1728 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1729 simpleArrayType.getArraySizes().dereference();
1730
1731 // Will compute the higher-order strides here, rather than making a whole
1732 // pile of types and doing repetitive recursion on their contents.
1733 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1734 }
John Kessenichf8842e52016-01-04 19:22:56 -07001735
1736 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001737 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1738 int size = type.getArraySizes()->getDimSize(dim);
1739 assert(size > 0);
1740 spvType = builder.makeArrayType(spvType, size, stride);
1741 if (stride > 0)
1742 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1743 stride *= size;
1744 }
1745 } else {
1746 // single-dimensional array, and don't yet have stride
1747
John Kessenichf8842e52016-01-04 19:22:56 -07001748 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001749 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1750 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001751 }
John Kessenich31ed4832015-09-09 17:51:38 -06001752
John Kessenichc9a80832015-09-12 12:17:44 -06001753 // Do the outer dimension, which might not be known for a runtime-sized array
1754 if (type.isRuntimeSizedArray()) {
1755 spvType = builder.makeRuntimeArray(spvType);
1756 } else {
1757 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001758 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001759 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001760 if (stride > 0)
1761 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001762 }
1763
1764 return spvType;
1765}
1766
John Kessenich32cfd492016-02-02 12:37:46 -07001767spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1768{
1769 return builder.accessChainLoad(TranslatePrecisionDecoration(type), convertGlslangToSpvType(type));
1770}
1771
John Kessenichf85e8062015-12-19 13:57:10 -07001772// Decide whether or not this type should be
1773// decorated with offsets and strides, and if so
1774// whether std140 or std430 rules should be applied.
1775glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001776{
John Kessenichf85e8062015-12-19 13:57:10 -07001777 // has to be a block
1778 if (type.getBasicType() != glslang::EbtBlock)
1779 return glslang::ElpNone;
1780
1781 // has to be a uniform or buffer block
1782 if (type.getQualifier().storage != glslang::EvqUniform &&
1783 type.getQualifier().storage != glslang::EvqBuffer)
1784 return glslang::ElpNone;
1785
1786 // return the layout to use
1787 switch (type.getQualifier().layoutPacking) {
1788 case glslang::ElpStd140:
1789 case glslang::ElpStd430:
1790 return type.getQualifier().layoutPacking;
1791 default:
1792 return glslang::ElpNone;
1793 }
John Kessenich31ed4832015-09-09 17:51:38 -06001794}
1795
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001796// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001797int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001798{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001799 int size;
John Kessenich49987892015-12-29 17:11:44 -07001800 int stride;
1801 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001802
1803 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001804}
1805
John Kessenich49987892015-12-29 17:11:44 -07001806// 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 -07001807// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001808int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001809{
John Kessenich49987892015-12-29 17:11:44 -07001810 glslang::TType elementType;
1811 elementType.shallowCopy(matrixType);
1812 elementType.clearArraySizes();
1813
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001814 int size;
John Kessenich49987892015-12-29 17:11:44 -07001815 int stride;
1816 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1817
1818 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001819}
1820
John Kessenich5e4b1242015-08-06 22:53:06 -06001821// Given a member type of a struct, realign the current offset for it, and compute
1822// the next (not yet aligned) offset for the next member, which will get aligned
1823// on the next call.
1824// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1825// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1826// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001827void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001828 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001829{
1830 // this will get a positive value when deemed necessary
1831 nextOffset = -1;
1832
John Kessenich5e4b1242015-08-06 22:53:06 -06001833 // override anything in currentOffset with user-set offset
1834 if (memberType.getQualifier().hasOffset())
1835 currentOffset = memberType.getQualifier().layoutOffset;
1836
1837 // It could be that current linker usage in glslang updated all the layoutOffset,
1838 // in which case the following code does not matter. But, that's not quite right
1839 // once cross-compilation unit GLSL validation is done, as the original user
1840 // settings are needed in layoutOffset, and then the following will come into play.
1841
John Kessenichf85e8062015-12-19 13:57:10 -07001842 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001843 if (! memberType.getQualifier().hasOffset())
1844 currentOffset = -1;
1845
1846 return;
1847 }
1848
John Kessenichf85e8062015-12-19 13:57:10 -07001849 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001850 if (currentOffset < 0)
1851 currentOffset = 0;
1852
1853 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1854 // but possibly not yet correctly aligned.
1855
1856 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001857 int dummyStride;
1858 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001859 glslang::RoundToPow2(currentOffset, memberAlignment);
1860 nextOffset = currentOffset + memberSize;
1861}
1862
John Kessenich140f3df2015-06-26 16:58:36 -06001863bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1864{
1865 return node->getName() == "main(";
1866}
1867
1868// Make all the functions, skeletally, without actually visiting their bodies.
1869void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1870{
1871 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1872 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1873 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1874 continue;
1875
1876 // We're on a user function. Set up the basic interface for the function now,
1877 // so that it's available to call.
1878 // Translating the body will happen later.
1879 //
1880 // Typically (except for a "const in" parameter), an address will be passed to the
1881 // function. What it is an address of varies:
1882 //
1883 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1884 // so that write needs to be to a copy, hence the address of a copy works.
1885 //
1886 // - "const in" parameters can just be the r-value, as no writes need occur.
1887 //
1888 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1889 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1890
1891 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07001892 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06001893 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1894
1895 for (int p = 0; p < (int)parameters.size(); ++p) {
1896 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1897 spv::Id typeId = convertGlslangToSpvType(paramType);
1898 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1899 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1900 else
1901 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07001902 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06001903 paramTypes.push_back(typeId);
1904 }
1905
1906 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07001907 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
1908 convertGlslangToSpvType(glslFunction->getType()),
1909 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06001910
1911 // Track function to emit/call later
1912 functionMap[glslFunction->getName().c_str()] = function;
1913
1914 // Set the parameter id's
1915 for (int p = 0; p < (int)parameters.size(); ++p) {
1916 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1917 // give a name too
1918 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1919 }
1920 }
1921}
1922
1923// Process all the initializers, while skipping the functions and link objects
1924void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1925{
1926 builder.setBuildPoint(shaderEntry->getLastBlock());
1927 for (int i = 0; i < (int)initializers.size(); ++i) {
1928 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1929 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1930
1931 // We're on a top-level node that's not a function. Treat as an initializer, whose
1932 // code goes into the beginning of main.
1933 initializer->traverse(this);
1934 }
1935 }
1936}
1937
1938// Process all the functions, while skipping initializers.
1939void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1940{
1941 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1942 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1943 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1944 node->traverse(this);
1945 }
1946}
1947
1948void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1949{
1950 // SPIR-V functions should already be in the functionMap from the prepass
1951 // that called makeFunctions().
1952 spv::Function* function = functionMap[node->getName().c_str()];
1953 spv::Block* functionBlock = function->getEntryBlock();
1954 builder.setBuildPoint(functionBlock);
1955}
1956
Rex Xu04db3f52015-09-16 11:44:02 +08001957void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001958{
Rex Xufc618912015-09-09 16:42:49 +08001959 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08001960
1961 glslang::TSampler sampler = {};
1962 bool cubeCompare = false;
1963 if (node.isTexture()) {
1964 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
1965 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1966 }
1967
John Kessenich140f3df2015-06-26 16:58:36 -06001968 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1969 builder.clearAccessChain();
1970 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001971
1972 // Special case l-value operands
1973 bool lvalue = false;
1974 switch (node.getOp()) {
1975 case glslang::EOpImageAtomicAdd:
1976 case glslang::EOpImageAtomicMin:
1977 case glslang::EOpImageAtomicMax:
1978 case glslang::EOpImageAtomicAnd:
1979 case glslang::EOpImageAtomicOr:
1980 case glslang::EOpImageAtomicXor:
1981 case glslang::EOpImageAtomicExchange:
1982 case glslang::EOpImageAtomicCompSwap:
1983 if (i == 0)
1984 lvalue = true;
1985 break;
Rex Xu48edadf2015-12-31 16:11:41 +08001986 case glslang::EOpSparseTexture:
1987 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
1988 lvalue = true;
1989 break;
1990 case glslang::EOpSparseTextureClamp:
1991 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
1992 lvalue = true;
1993 break;
1994 case glslang::EOpSparseTextureLod:
1995 case glslang::EOpSparseTextureOffset:
1996 if (i == 3)
1997 lvalue = true;
1998 break;
1999 case glslang::EOpSparseTextureFetch:
2000 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2001 lvalue = true;
2002 break;
2003 case glslang::EOpSparseTextureFetchOffset:
2004 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2005 lvalue = true;
2006 break;
2007 case glslang::EOpSparseTextureLodOffset:
2008 case glslang::EOpSparseTextureGrad:
2009 case glslang::EOpSparseTextureOffsetClamp:
2010 if (i == 4)
2011 lvalue = true;
2012 break;
2013 case glslang::EOpSparseTextureGradOffset:
2014 case glslang::EOpSparseTextureGradClamp:
2015 if (i == 5)
2016 lvalue = true;
2017 break;
2018 case glslang::EOpSparseTextureGradOffsetClamp:
2019 if (i == 6)
2020 lvalue = true;
2021 break;
2022 case glslang::EOpSparseTextureGather:
2023 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2024 lvalue = true;
2025 break;
2026 case glslang::EOpSparseTextureGatherOffset:
2027 case glslang::EOpSparseTextureGatherOffsets:
2028 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2029 lvalue = true;
2030 break;
Rex Xufc618912015-09-09 16:42:49 +08002031 default:
2032 break;
2033 }
2034
Rex Xu6b86d492015-09-16 17:48:22 +08002035 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002036 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002037 else
John Kessenich32cfd492016-02-02 12:37:46 -07002038 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002039 }
2040}
2041
John Kessenichfc51d282015-08-19 13:34:18 -06002042void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002043{
John Kessenichfc51d282015-08-19 13:34:18 -06002044 builder.clearAccessChain();
2045 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002046 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002047}
John Kessenich140f3df2015-06-26 16:58:36 -06002048
John Kessenichfc51d282015-08-19 13:34:18 -06002049spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2050{
Rex Xufc618912015-09-09 16:42:49 +08002051 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002052 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002053 }
2054
John Kessenichfc51d282015-08-19 13:34:18 -06002055 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002056 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2057 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2058 std::vector<spv::Id> arguments;
2059 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002060 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002061 else
2062 translateArguments(*node->getAsUnaryNode(), arguments);
2063 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2064
2065 spv::Builder::TextureParameters params = { };
2066 params.sampler = arguments[0];
2067
Rex Xu04db3f52015-09-16 11:44:02 +08002068 glslang::TCrackedTextureOp cracked;
2069 node->crackTexture(sampler, cracked);
2070
John Kessenichfc51d282015-08-19 13:34:18 -06002071 // Check for queries
2072 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002073 // a sampled image needs to have the image extracted first
2074 if (builder.isSampledImage(params.sampler))
2075 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002076 switch (node->getOp()) {
2077 case glslang::EOpImageQuerySize:
2078 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002079 if (arguments.size() > 1) {
2080 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002081 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002082 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002083 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002084 case glslang::EOpImageQuerySamples:
2085 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002086 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002087 case glslang::EOpTextureQueryLod:
2088 params.coords = arguments[1];
2089 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2090 case glslang::EOpTextureQueryLevels:
2091 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002092 case glslang::EOpSparseTexelsResident:
2093 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002094 default:
2095 assert(0);
2096 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002097 }
John Kessenich140f3df2015-06-26 16:58:36 -06002098 }
2099
Rex Xufc618912015-09-09 16:42:49 +08002100 // Check for image functions other than queries
2101 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002102 std::vector<spv::Id> operands;
2103 auto opIt = arguments.begin();
2104 operands.push_back(*(opIt++));
2105 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002106 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002107 if (sampler.ms) {
2108 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002109 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002110 }
John Kessenich56bab042015-09-16 10:54:31 -06002111 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2112 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002113 if (sampler.ms) {
2114 operands.push_back(*(opIt + 1));
2115 operands.push_back(spv::ImageOperandsSampleMask);
2116 operands.push_back(*opIt);
2117 } else
2118 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002119 builder.createNoResultOp(spv::OpImageWrite, operands);
2120 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002121 } else if (node->isSparseImage()) {
2122 spv::MissingFunctionality("sparse image functions");
2123 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002124 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002125 // Process image atomic operations
2126
2127 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2128 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002129 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002130
Rex Xufc618912015-09-09 16:42:49 +08002131 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002132 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002133
2134 std::vector<spv::Id> operands;
2135 operands.push_back(pointer);
2136 for (; opIt != arguments.end(); ++opIt)
2137 operands.push_back(*opIt);
2138
Rex Xu04db3f52015-09-16 11:44:02 +08002139 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002140 }
2141 }
2142
2143 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002144 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002145 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2146
John Kessenichfc51d282015-08-19 13:34:18 -06002147 // check for bias argument
2148 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002149 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002150 int nonBiasArgCount = 2;
2151 if (cracked.offset)
2152 ++nonBiasArgCount;
2153 if (cracked.grad)
2154 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002155 if (cracked.lodClamp)
2156 ++nonBiasArgCount;
2157 if (sparse)
2158 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002159
2160 if ((int)arguments.size() > nonBiasArgCount)
2161 bias = true;
2162 }
2163
John Kessenichfc51d282015-08-19 13:34:18 -06002164 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002165
John Kessenichfc51d282015-08-19 13:34:18 -06002166 params.coords = arguments[1];
2167 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002168
2169 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002170 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002171 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002172 ++extraArgs;
2173 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002174 params.Dref = arguments[2];
2175 ++extraArgs;
2176 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002177 std::vector<spv::Id> indexes;
2178 int comp;
2179 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002180 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002181 else
2182 comp = builder.getNumComponents(params.coords) - 1;
2183 indexes.push_back(comp);
2184 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2185 }
2186 if (cracked.lod) {
2187 params.lod = arguments[2];
2188 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002189 } else if (sampler.ms) {
2190 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002191 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002192 }
2193 if (cracked.grad) {
2194 params.gradX = arguments[2 + extraArgs];
2195 params.gradY = arguments[3 + extraArgs];
2196 extraArgs += 2;
2197 }
John Kessenich55e7d112015-11-15 21:33:39 -07002198 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002199 params.offset = arguments[2 + extraArgs];
2200 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002201 } else if (cracked.offsets) {
2202 params.offsets = arguments[2 + extraArgs];
2203 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002204 }
Rex Xu48edadf2015-12-31 16:11:41 +08002205 if (cracked.lodClamp) {
2206 params.lodClamp = arguments[2 + extraArgs];
2207 ++extraArgs;
2208 }
2209 if (sparse) {
2210 params.texelOut = arguments[2 + extraArgs];
2211 ++extraArgs;
2212 }
John Kessenichfc51d282015-08-19 13:34:18 -06002213 if (bias) {
2214 params.bias = arguments[2 + extraArgs];
2215 ++extraArgs;
2216 }
John Kessenich55e7d112015-11-15 21:33:39 -07002217 if (cracked.gather && ! sampler.shadow) {
2218 // default component is 0, if missing, otherwise an argument
2219 if (2 + extraArgs < (int)arguments.size()) {
2220 params.comp = arguments[2 + extraArgs];
2221 ++extraArgs;
2222 } else {
2223 params.comp = builder.makeIntConstant(0);
2224 }
2225 }
John Kessenichfc51d282015-08-19 13:34:18 -06002226
Rex Xu48edadf2015-12-31 16:11:41 +08002227 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002228}
2229
2230spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2231{
2232 // Grab the function's pointer from the previously created function
2233 spv::Function* function = functionMap[node->getName().c_str()];
2234 if (! function)
2235 return 0;
2236
2237 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2238 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2239
2240 // See comments in makeFunctions() for details about the semantics for parameter passing.
2241 //
2242 // These imply we need a four step process:
2243 // 1. Evaluate the arguments
2244 // 2. Allocate and make copies of in, out, and inout arguments
2245 // 3. Make the call
2246 // 4. Copy back the results
2247
2248 // 1. Evaluate the arguments
2249 std::vector<spv::Builder::AccessChain> lValues;
2250 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002251 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002252 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2253 // build l-value
2254 builder.clearAccessChain();
2255 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002256 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002257 // keep outputs as l-values, evaluate input-only as r-values
2258 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2259 // save l-value
2260 lValues.push_back(builder.getAccessChain());
2261 } else {
2262 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002263 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002264 }
2265 }
2266
2267 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2268 // copy the original into that space.
2269 //
2270 // Also, build up the list of actual arguments to pass in for the call
2271 int lValueCount = 0;
2272 int rValueCount = 0;
2273 std::vector<spv::Id> spvArgs;
2274 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2275 spv::Id arg;
2276 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2277 // need space to hold the copy
2278 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2279 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2280 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2281 // need to copy the input into output space
2282 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002283 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002284 builder.createStore(copy, arg);
2285 }
2286 ++lValueCount;
2287 } else {
2288 arg = rValues[rValueCount];
2289 ++rValueCount;
2290 }
2291 spvArgs.push_back(arg);
2292 }
2293
2294 // 3. Make the call.
2295 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002296 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002297
2298 // 4. Copy back out an "out" arguments.
2299 lValueCount = 0;
2300 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2301 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2302 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2303 spv::Id copy = builder.createLoad(spvArgs[a]);
2304 builder.setAccessChain(lValues[lValueCount]);
2305 builder.accessChainStore(copy);
2306 }
2307 ++lValueCount;
2308 }
2309 }
2310
2311 return result;
2312}
2313
2314// Translate AST operation to SPV operation, already having SPV-based operands/types.
2315spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2316 spv::Id typeId, spv::Id left, spv::Id right,
2317 glslang::TBasicType typeProxy, bool reduceComparison)
2318{
2319 bool isUnsigned = typeProxy == glslang::EbtUint;
2320 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2321
2322 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002323 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002324 bool comparison = false;
2325
2326 switch (op) {
2327 case glslang::EOpAdd:
2328 case glslang::EOpAddAssign:
2329 if (isFloat)
2330 binOp = spv::OpFAdd;
2331 else
2332 binOp = spv::OpIAdd;
2333 break;
2334 case glslang::EOpSub:
2335 case glslang::EOpSubAssign:
2336 if (isFloat)
2337 binOp = spv::OpFSub;
2338 else
2339 binOp = spv::OpISub;
2340 break;
2341 case glslang::EOpMul:
2342 case glslang::EOpMulAssign:
2343 if (isFloat)
2344 binOp = spv::OpFMul;
2345 else
2346 binOp = spv::OpIMul;
2347 break;
2348 case glslang::EOpVectorTimesScalar:
2349 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002350 if (isFloat) {
2351 if (builder.isVector(right))
2352 std::swap(left, right);
2353 assert(builder.isScalar(right));
2354 needMatchingVectors = false;
2355 binOp = spv::OpVectorTimesScalar;
2356 } else
2357 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002358 break;
2359 case glslang::EOpVectorTimesMatrix:
2360 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002361 binOp = spv::OpVectorTimesMatrix;
2362 break;
2363 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002364 binOp = spv::OpMatrixTimesVector;
2365 break;
2366 case glslang::EOpMatrixTimesScalar:
2367 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002368 binOp = spv::OpMatrixTimesScalar;
2369 break;
2370 case glslang::EOpMatrixTimesMatrix:
2371 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002372 binOp = spv::OpMatrixTimesMatrix;
2373 break;
2374 case glslang::EOpOuterProduct:
2375 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002376 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002377 break;
2378
2379 case glslang::EOpDiv:
2380 case glslang::EOpDivAssign:
2381 if (isFloat)
2382 binOp = spv::OpFDiv;
2383 else if (isUnsigned)
2384 binOp = spv::OpUDiv;
2385 else
2386 binOp = spv::OpSDiv;
2387 break;
2388 case glslang::EOpMod:
2389 case glslang::EOpModAssign:
2390 if (isFloat)
2391 binOp = spv::OpFMod;
2392 else if (isUnsigned)
2393 binOp = spv::OpUMod;
2394 else
2395 binOp = spv::OpSMod;
2396 break;
2397 case glslang::EOpRightShift:
2398 case glslang::EOpRightShiftAssign:
2399 if (isUnsigned)
2400 binOp = spv::OpShiftRightLogical;
2401 else
2402 binOp = spv::OpShiftRightArithmetic;
2403 break;
2404 case glslang::EOpLeftShift:
2405 case glslang::EOpLeftShiftAssign:
2406 binOp = spv::OpShiftLeftLogical;
2407 break;
2408 case glslang::EOpAnd:
2409 case glslang::EOpAndAssign:
2410 binOp = spv::OpBitwiseAnd;
2411 break;
2412 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002413 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002414 binOp = spv::OpLogicalAnd;
2415 break;
2416 case glslang::EOpInclusiveOr:
2417 case glslang::EOpInclusiveOrAssign:
2418 binOp = spv::OpBitwiseOr;
2419 break;
2420 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002421 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002422 binOp = spv::OpLogicalOr;
2423 break;
2424 case glslang::EOpExclusiveOr:
2425 case glslang::EOpExclusiveOrAssign:
2426 binOp = spv::OpBitwiseXor;
2427 break;
2428 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002429 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002430 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002431 break;
2432
2433 case glslang::EOpLessThan:
2434 case glslang::EOpGreaterThan:
2435 case glslang::EOpLessThanEqual:
2436 case glslang::EOpGreaterThanEqual:
2437 case glslang::EOpEqual:
2438 case glslang::EOpNotEqual:
2439 case glslang::EOpVectorEqual:
2440 case glslang::EOpVectorNotEqual:
2441 comparison = true;
2442 break;
2443 default:
2444 break;
2445 }
2446
John Kessenich7c1aa102015-10-15 13:29:11 -06002447 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002448 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002449 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002450 if (builder.isMatrix(left) || builder.isMatrix(right))
2451 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002452
2453 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002454 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002455 builder.promoteScalar(precision, left, right);
2456
John Kessenich32cfd492016-02-02 12:37:46 -07002457 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002458 }
2459
2460 if (! comparison)
2461 return 0;
2462
John Kessenich7c1aa102015-10-15 13:29:11 -06002463 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002464
2465 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2466 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2467
John Kessenich22118352015-12-21 20:54:09 -07002468 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002469 }
2470
2471 switch (op) {
2472 case glslang::EOpLessThan:
2473 if (isFloat)
2474 binOp = spv::OpFOrdLessThan;
2475 else if (isUnsigned)
2476 binOp = spv::OpULessThan;
2477 else
2478 binOp = spv::OpSLessThan;
2479 break;
2480 case glslang::EOpGreaterThan:
2481 if (isFloat)
2482 binOp = spv::OpFOrdGreaterThan;
2483 else if (isUnsigned)
2484 binOp = spv::OpUGreaterThan;
2485 else
2486 binOp = spv::OpSGreaterThan;
2487 break;
2488 case glslang::EOpLessThanEqual:
2489 if (isFloat)
2490 binOp = spv::OpFOrdLessThanEqual;
2491 else if (isUnsigned)
2492 binOp = spv::OpULessThanEqual;
2493 else
2494 binOp = spv::OpSLessThanEqual;
2495 break;
2496 case glslang::EOpGreaterThanEqual:
2497 if (isFloat)
2498 binOp = spv::OpFOrdGreaterThanEqual;
2499 else if (isUnsigned)
2500 binOp = spv::OpUGreaterThanEqual;
2501 else
2502 binOp = spv::OpSGreaterThanEqual;
2503 break;
2504 case glslang::EOpEqual:
2505 case glslang::EOpVectorEqual:
2506 if (isFloat)
2507 binOp = spv::OpFOrdEqual;
2508 else
2509 binOp = spv::OpIEqual;
2510 break;
2511 case glslang::EOpNotEqual:
2512 case glslang::EOpVectorNotEqual:
2513 if (isFloat)
2514 binOp = spv::OpFOrdNotEqual;
2515 else
2516 binOp = spv::OpINotEqual;
2517 break;
2518 default:
2519 break;
2520 }
2521
John Kessenich32cfd492016-02-02 12:37:46 -07002522 if (binOp != spv::OpNop)
2523 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002524
2525 return 0;
2526}
2527
John Kessenich04bb8a02015-12-12 12:28:14 -07002528//
2529// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2530// These can be any of:
2531//
2532// matrix * scalar
2533// scalar * matrix
2534// matrix * matrix linear algebraic
2535// matrix * vector
2536// vector * matrix
2537// matrix * matrix componentwise
2538// matrix op matrix op in {+, -, /}
2539// matrix op scalar op in {+, -, /}
2540// scalar op matrix op in {+, -, /}
2541//
2542spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2543{
2544 bool firstClass = true;
2545
2546 // First, handle first-class matrix operations (* and matrix/scalar)
2547 switch (op) {
2548 case spv::OpFDiv:
2549 if (builder.isMatrix(left) && builder.isScalar(right)) {
2550 // turn matrix / scalar into a multiply...
2551 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2552 op = spv::OpMatrixTimesScalar;
2553 } else
2554 firstClass = false;
2555 break;
2556 case spv::OpMatrixTimesScalar:
2557 if (builder.isMatrix(right))
2558 std::swap(left, right);
2559 assert(builder.isScalar(right));
2560 break;
2561 case spv::OpVectorTimesMatrix:
2562 assert(builder.isVector(left));
2563 assert(builder.isMatrix(right));
2564 break;
2565 case spv::OpMatrixTimesVector:
2566 assert(builder.isMatrix(left));
2567 assert(builder.isVector(right));
2568 break;
2569 case spv::OpMatrixTimesMatrix:
2570 assert(builder.isMatrix(left));
2571 assert(builder.isMatrix(right));
2572 break;
2573 default:
2574 firstClass = false;
2575 break;
2576 }
2577
John Kessenich32cfd492016-02-02 12:37:46 -07002578 if (firstClass)
2579 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002580
2581 // Handle component-wise +, -, *, and / for all combinations of type.
2582 // The result type of all of them is the same type as the (a) matrix operand.
2583 // The algorithm is to:
2584 // - break the matrix(es) into vectors
2585 // - smear any scalar to a vector
2586 // - do vector operations
2587 // - make a matrix out the vector results
2588 switch (op) {
2589 case spv::OpFAdd:
2590 case spv::OpFSub:
2591 case spv::OpFDiv:
2592 case spv::OpFMul:
2593 {
2594 // one time set up...
2595 bool leftMat = builder.isMatrix(left);
2596 bool rightMat = builder.isMatrix(right);
2597 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2598 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2599 spv::Id scalarType = builder.getScalarTypeId(typeId);
2600 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2601 std::vector<spv::Id> results;
2602 spv::Id smearVec = spv::NoResult;
2603 if (builder.isScalar(left))
2604 smearVec = builder.smearScalar(precision, left, vecType);
2605 else if (builder.isScalar(right))
2606 smearVec = builder.smearScalar(precision, right, vecType);
2607
2608 // do each vector op
2609 for (unsigned int c = 0; c < numCols; ++c) {
2610 std::vector<unsigned int> indexes;
2611 indexes.push_back(c);
2612 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2613 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2614 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2615 builder.setPrecision(results.back(), precision);
2616 }
2617
2618 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002619 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002620 }
2621 default:
2622 assert(0);
2623 return spv::NoResult;
2624 }
2625}
2626
Rex Xu04db3f52015-09-16 11:44:02 +08002627spv::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 -06002628{
2629 spv::Op unaryOp = spv::OpNop;
2630 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002631 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002632 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002633
2634 switch (op) {
2635 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002636 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002637 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002638 if (builder.isMatrixType(typeId))
2639 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2640 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002641 unaryOp = spv::OpSNegate;
2642 break;
2643
2644 case glslang::EOpLogicalNot:
2645 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002646 unaryOp = spv::OpLogicalNot;
2647 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002648 case glslang::EOpBitwiseNot:
2649 unaryOp = spv::OpNot;
2650 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002651
John Kessenich140f3df2015-06-26 16:58:36 -06002652 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002653 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002654 break;
2655 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002656 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002657 break;
2658 case glslang::EOpTranspose:
2659 unaryOp = spv::OpTranspose;
2660 break;
2661
2662 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002663 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002664 break;
2665 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002666 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002667 break;
2668 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002669 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002670 break;
2671 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002672 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002673 break;
2674 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002675 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002676 break;
2677 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002678 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002679 break;
2680 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002681 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002682 break;
2683 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002684 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002685 break;
2686
2687 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002688 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002689 break;
2690 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002691 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002692 break;
2693 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002694 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002695 break;
2696 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002697 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002698 break;
2699 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002700 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002701 break;
2702 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002703 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002704 break;
2705
2706 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002707 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002708 break;
2709 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002710 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002711 break;
2712
2713 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002714 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002715 break;
2716 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002717 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002718 break;
2719 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002720 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002721 break;
2722 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002723 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002724 break;
2725 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002726 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002727 break;
2728 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002729 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002730 break;
2731
2732 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002733 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002734 break;
2735 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002736 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002737 break;
2738 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002739 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002740 break;
2741 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002742 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002743 break;
2744 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002745 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002746 break;
2747 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002748 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002749 break;
2750
2751 case glslang::EOpIsNan:
2752 unaryOp = spv::OpIsNan;
2753 break;
2754 case glslang::EOpIsInf:
2755 unaryOp = spv::OpIsInf;
2756 break;
2757
Rex Xucbc426e2015-12-15 16:03:10 +08002758 case glslang::EOpFloatBitsToInt:
2759 case glslang::EOpFloatBitsToUint:
2760 case glslang::EOpIntBitsToFloat:
2761 case glslang::EOpUintBitsToFloat:
2762 unaryOp = spv::OpBitcast;
2763 break;
2764
John Kessenich140f3df2015-06-26 16:58:36 -06002765 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002766 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002767 break;
2768 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002769 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002770 break;
2771 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002772 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002773 break;
2774 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002775 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002776 break;
2777 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002778 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002779 break;
2780 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002781 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002782 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002783 case glslang::EOpPackSnorm4x8:
2784 libCall = spv::GLSLstd450PackSnorm4x8;
2785 break;
2786 case glslang::EOpUnpackSnorm4x8:
2787 libCall = spv::GLSLstd450UnpackSnorm4x8;
2788 break;
2789 case glslang::EOpPackUnorm4x8:
2790 libCall = spv::GLSLstd450PackUnorm4x8;
2791 break;
2792 case glslang::EOpUnpackUnorm4x8:
2793 libCall = spv::GLSLstd450UnpackUnorm4x8;
2794 break;
2795 case glslang::EOpPackDouble2x32:
2796 libCall = spv::GLSLstd450PackDouble2x32;
2797 break;
2798 case glslang::EOpUnpackDouble2x32:
2799 libCall = spv::GLSLstd450UnpackDouble2x32;
2800 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002801
2802 case glslang::EOpDPdx:
2803 unaryOp = spv::OpDPdx;
2804 break;
2805 case glslang::EOpDPdy:
2806 unaryOp = spv::OpDPdy;
2807 break;
2808 case glslang::EOpFwidth:
2809 unaryOp = spv::OpFwidth;
2810 break;
2811 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07002812 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002813 unaryOp = spv::OpDPdxFine;
2814 break;
2815 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07002816 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002817 unaryOp = spv::OpDPdyFine;
2818 break;
2819 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07002820 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002821 unaryOp = spv::OpFwidthFine;
2822 break;
2823 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002824 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002825 unaryOp = spv::OpDPdxCoarse;
2826 break;
2827 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002828 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002829 unaryOp = spv::OpDPdyCoarse;
2830 break;
2831 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002832 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002833 unaryOp = spv::OpFwidthCoarse;
2834 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002835 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07002836 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08002837 libCall = spv::GLSLstd450InterpolateAtCentroid;
2838 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002839 case glslang::EOpAny:
2840 unaryOp = spv::OpAny;
2841 break;
2842 case glslang::EOpAll:
2843 unaryOp = spv::OpAll;
2844 break;
2845
2846 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002847 if (isFloat)
2848 libCall = spv::GLSLstd450FAbs;
2849 else
2850 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002851 break;
2852 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002853 if (isFloat)
2854 libCall = spv::GLSLstd450FSign;
2855 else
2856 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002857 break;
2858
John Kessenichfc51d282015-08-19 13:34:18 -06002859 case glslang::EOpAtomicCounterIncrement:
2860 case glslang::EOpAtomicCounterDecrement:
2861 case glslang::EOpAtomicCounter:
2862 {
2863 // Handle all of the atomics in one place, in createAtomicOperation()
2864 std::vector<spv::Id> operands;
2865 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002866 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002867 }
2868
2869 case glslang::EOpImageLoad:
2870 unaryOp = spv::OpImageRead;
2871 break;
2872
2873 case glslang::EOpBitFieldReverse:
2874 unaryOp = spv::OpBitReverse;
2875 break;
2876 case glslang::EOpBitCount:
2877 unaryOp = spv::OpBitCount;
2878 break;
2879 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002880 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002881 break;
2882 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002883 if (isUnsigned)
2884 libCall = spv::GLSLstd450FindUMsb;
2885 else
2886 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002887 break;
2888
John Kessenich140f3df2015-06-26 16:58:36 -06002889 default:
2890 return 0;
2891 }
2892
2893 spv::Id id;
2894 if (libCall >= 0) {
2895 std::vector<spv::Id> args;
2896 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07002897 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06002898 } else
2899 id = builder.createUnaryOp(unaryOp, typeId, operand);
2900
John Kessenich32cfd492016-02-02 12:37:46 -07002901 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002902}
2903
John Kessenich7a53f762016-01-20 11:19:27 -07002904// Create a unary operation on a matrix
2905spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
2906{
2907 // Handle unary operations vector by vector.
2908 // The result type is the same type as the original type.
2909 // The algorithm is to:
2910 // - break the matrix into vectors
2911 // - apply the operation to each vector
2912 // - make a matrix out the vector results
2913
2914 // get the types sorted out
2915 int numCols = builder.getNumColumns(operand);
2916 int numRows = builder.getNumRows(operand);
2917 spv::Id scalarType = builder.getScalarTypeId(typeId);
2918 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2919 std::vector<spv::Id> results;
2920
2921 // do each vector op
2922 for (int c = 0; c < numCols; ++c) {
2923 std::vector<unsigned int> indexes;
2924 indexes.push_back(c);
2925 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
2926 results.push_back(builder.createUnaryOp(op, vecType, vec));
2927 builder.setPrecision(results.back(), precision);
2928 }
2929
2930 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002931 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07002932}
2933
John Kessenich140f3df2015-06-26 16:58:36 -06002934spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2935{
2936 spv::Op convOp = spv::OpNop;
2937 spv::Id zero = 0;
2938 spv::Id one = 0;
2939
2940 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2941
2942 switch (op) {
2943 case glslang::EOpConvIntToBool:
2944 case glslang::EOpConvUintToBool:
2945 zero = builder.makeUintConstant(0);
2946 zero = makeSmearedConstant(zero, vectorSize);
2947 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2948
2949 case glslang::EOpConvFloatToBool:
2950 zero = builder.makeFloatConstant(0.0F);
2951 zero = makeSmearedConstant(zero, vectorSize);
2952 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2953
2954 case glslang::EOpConvDoubleToBool:
2955 zero = builder.makeDoubleConstant(0.0);
2956 zero = makeSmearedConstant(zero, vectorSize);
2957 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2958
2959 case glslang::EOpConvBoolToFloat:
2960 convOp = spv::OpSelect;
2961 zero = builder.makeFloatConstant(0.0);
2962 one = builder.makeFloatConstant(1.0);
2963 break;
2964 case glslang::EOpConvBoolToDouble:
2965 convOp = spv::OpSelect;
2966 zero = builder.makeDoubleConstant(0.0);
2967 one = builder.makeDoubleConstant(1.0);
2968 break;
2969 case glslang::EOpConvBoolToInt:
2970 zero = builder.makeIntConstant(0);
2971 one = builder.makeIntConstant(1);
2972 convOp = spv::OpSelect;
2973 break;
2974 case glslang::EOpConvBoolToUint:
2975 zero = builder.makeUintConstant(0);
2976 one = builder.makeUintConstant(1);
2977 convOp = spv::OpSelect;
2978 break;
2979
2980 case glslang::EOpConvIntToFloat:
2981 case glslang::EOpConvIntToDouble:
2982 convOp = spv::OpConvertSToF;
2983 break;
2984
2985 case glslang::EOpConvUintToFloat:
2986 case glslang::EOpConvUintToDouble:
2987 convOp = spv::OpConvertUToF;
2988 break;
2989
2990 case glslang::EOpConvDoubleToFloat:
2991 case glslang::EOpConvFloatToDouble:
2992 convOp = spv::OpFConvert;
2993 break;
2994
2995 case glslang::EOpConvFloatToInt:
2996 case glslang::EOpConvDoubleToInt:
2997 convOp = spv::OpConvertFToS;
2998 break;
2999
3000 case glslang::EOpConvUintToInt:
3001 case glslang::EOpConvIntToUint:
3002 convOp = spv::OpBitcast;
3003 break;
3004
3005 case glslang::EOpConvFloatToUint:
3006 case glslang::EOpConvDoubleToUint:
3007 convOp = spv::OpConvertFToU;
3008 break;
3009 default:
3010 break;
3011 }
3012
3013 spv::Id result = 0;
3014 if (convOp == spv::OpNop)
3015 return result;
3016
3017 if (convOp == spv::OpSelect) {
3018 zero = makeSmearedConstant(zero, vectorSize);
3019 one = makeSmearedConstant(one, vectorSize);
3020 result = builder.createTriOp(convOp, destType, operand, one, zero);
3021 } else
3022 result = builder.createUnaryOp(convOp, destType, operand);
3023
John Kessenich32cfd492016-02-02 12:37:46 -07003024 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003025}
3026
3027spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3028{
3029 if (vectorSize == 0)
3030 return constant;
3031
3032 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3033 std::vector<spv::Id> components;
3034 for (int c = 0; c < vectorSize; ++c)
3035 components.push_back(constant);
3036 return builder.makeCompositeConstant(vectorTypeId, components);
3037}
3038
John Kessenich426394d2015-07-23 10:22:48 -06003039// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08003040spv::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 -06003041{
3042 spv::Op opCode = spv::OpNop;
3043
3044 switch (op) {
3045 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003046 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003047 opCode = spv::OpAtomicIAdd;
3048 break;
3049 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003050 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003051 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003052 break;
3053 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003054 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003055 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003056 break;
3057 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003058 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003059 opCode = spv::OpAtomicAnd;
3060 break;
3061 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003062 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003063 opCode = spv::OpAtomicOr;
3064 break;
3065 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003066 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003067 opCode = spv::OpAtomicXor;
3068 break;
3069 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003070 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003071 opCode = spv::OpAtomicExchange;
3072 break;
3073 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003074 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003075 opCode = spv::OpAtomicCompareExchange;
3076 break;
3077 case glslang::EOpAtomicCounterIncrement:
3078 opCode = spv::OpAtomicIIncrement;
3079 break;
3080 case glslang::EOpAtomicCounterDecrement:
3081 opCode = spv::OpAtomicIDecrement;
3082 break;
3083 case glslang::EOpAtomicCounter:
3084 opCode = spv::OpAtomicLoad;
3085 break;
3086 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003087 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003088 break;
3089 }
3090
3091 // Sort out the operands
3092 // - mapping from glslang -> SPV
3093 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003094 // - compare-exchange swaps the value and comparator
3095 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003096 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3097 auto opIt = operands.begin(); // walk the glslang operands
3098 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003099 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3100 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3101 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003102 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3103 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003104 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003105 spvAtomicOperands.push_back(*(opIt + 1));
3106 spvAtomicOperands.push_back(*opIt);
3107 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003108 }
John Kessenich426394d2015-07-23 10:22:48 -06003109
John Kessenich3e60a6f2015-09-14 22:45:16 -06003110 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003111 for (; opIt != operands.end(); ++opIt)
3112 spvAtomicOperands.push_back(*opIt);
3113
3114 return builder.createOp(opCode, typeId, spvAtomicOperands);
3115}
3116
John Kessenich5e4b1242015-08-06 22:53:06 -06003117spv::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 -06003118{
John Kessenich5e4b1242015-08-06 22:53:06 -06003119 bool isUnsigned = typeProxy == glslang::EbtUint;
3120 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3121
John Kessenich140f3df2015-06-26 16:58:36 -06003122 spv::Op opCode = spv::OpNop;
3123 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003124 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003125 spv::Id typeId0 = 0;
3126 if (consumedOperands > 0)
3127 typeId0 = builder.getTypeId(operands[0]);
3128 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003129
3130 switch (op) {
3131 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003132 if (isFloat)
3133 libCall = spv::GLSLstd450FMin;
3134 else if (isUnsigned)
3135 libCall = spv::GLSLstd450UMin;
3136 else
3137 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003138 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003139 break;
3140 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003141 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003142 break;
3143 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003144 if (isFloat)
3145 libCall = spv::GLSLstd450FMax;
3146 else if (isUnsigned)
3147 libCall = spv::GLSLstd450UMax;
3148 else
3149 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003150 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003151 break;
3152 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003153 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003154 break;
3155 case glslang::EOpDot:
3156 opCode = spv::OpDot;
3157 break;
3158 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003159 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003160 break;
3161
3162 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003163 if (isFloat)
3164 libCall = spv::GLSLstd450FClamp;
3165 else if (isUnsigned)
3166 libCall = spv::GLSLstd450UClamp;
3167 else
3168 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003169 builder.promoteScalar(precision, operands.front(), operands[1]);
3170 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003171 break;
3172 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003173 if (isFloat)
3174 libCall = spv::GLSLstd450FMix;
3175 else
3176 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003177 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003178 break;
3179 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003180 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003181 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003182 break;
3183 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003184 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003185 builder.promoteScalar(precision, operands[0], operands[2]);
3186 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003187 break;
3188
3189 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003190 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003191 break;
3192 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003193 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003194 break;
3195 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003196 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003197 break;
3198 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003199 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003200 break;
3201 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003202 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003203 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003204 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003205 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003206 libCall = spv::GLSLstd450InterpolateAtSample;
3207 break;
3208 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003209 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003210 libCall = spv::GLSLstd450InterpolateAtOffset;
3211 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003212 case glslang::EOpAddCarry:
3213 opCode = spv::OpIAddCarry;
3214 typeId = builder.makeStructResultType(typeId0, typeId0);
3215 consumedOperands = 2;
3216 break;
3217 case glslang::EOpSubBorrow:
3218 opCode = spv::OpISubBorrow;
3219 typeId = builder.makeStructResultType(typeId0, typeId0);
3220 consumedOperands = 2;
3221 break;
3222 case glslang::EOpUMulExtended:
3223 opCode = spv::OpUMulExtended;
3224 typeId = builder.makeStructResultType(typeId0, typeId0);
3225 consumedOperands = 2;
3226 break;
3227 case glslang::EOpIMulExtended:
3228 opCode = spv::OpSMulExtended;
3229 typeId = builder.makeStructResultType(typeId0, typeId0);
3230 consumedOperands = 2;
3231 break;
3232 case glslang::EOpBitfieldExtract:
3233 if (isUnsigned)
3234 opCode = spv::OpBitFieldUExtract;
3235 else
3236 opCode = spv::OpBitFieldSExtract;
3237 break;
3238 case glslang::EOpBitfieldInsert:
3239 opCode = spv::OpBitFieldInsert;
3240 break;
3241
3242 case glslang::EOpFma:
3243 libCall = spv::GLSLstd450Fma;
3244 break;
3245 case glslang::EOpFrexp:
3246 libCall = spv::GLSLstd450FrexpStruct;
3247 if (builder.getNumComponents(operands[0]) == 1)
3248 frexpIntType = builder.makeIntegerType(32, true);
3249 else
3250 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3251 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3252 consumedOperands = 1;
3253 break;
3254 case glslang::EOpLdexp:
3255 libCall = spv::GLSLstd450Ldexp;
3256 break;
3257
John Kessenich140f3df2015-06-26 16:58:36 -06003258 default:
3259 return 0;
3260 }
3261
3262 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003263 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003264 // Use an extended instruction from the standard library.
3265 // Construct the call arguments, without modifying the original operands vector.
3266 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3267 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003268 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003269 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003270 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003271 case 0:
3272 // should all be handled by visitAggregate and createNoArgOperation
3273 assert(0);
3274 return 0;
3275 case 1:
3276 // should all be handled by createUnaryOperation
3277 assert(0);
3278 return 0;
3279 case 2:
3280 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3281 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003282 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003283 // anything 3 or over doesn't have l-value operands, so all should be consumed
3284 assert(consumedOperands == operands.size());
3285 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003286 break;
3287 }
3288 }
3289
John Kessenich55e7d112015-11-15 21:33:39 -07003290 // Decode the return types that were structures
3291 switch (op) {
3292 case glslang::EOpAddCarry:
3293 case glslang::EOpSubBorrow:
3294 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3295 id = builder.createCompositeExtract(id, typeId0, 0);
3296 break;
3297 case glslang::EOpUMulExtended:
3298 case glslang::EOpIMulExtended:
3299 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3300 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3301 break;
3302 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003303 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003304 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3305 id = builder.createCompositeExtract(id, typeId0, 0);
3306 break;
3307 default:
3308 break;
3309 }
3310
John Kessenich32cfd492016-02-02 12:37:46 -07003311 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003312}
3313
3314// Intrinsics with no arguments, no return value, and no precision.
3315spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3316{
3317 // TODO: get the barrier operands correct
3318
3319 switch (op) {
3320 case glslang::EOpEmitVertex:
3321 builder.createNoResultOp(spv::OpEmitVertex);
3322 return 0;
3323 case glslang::EOpEndPrimitive:
3324 builder.createNoResultOp(spv::OpEndPrimitive);
3325 return 0;
3326 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003327 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3328 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003329 return 0;
3330 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003331 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003332 return 0;
3333 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003334 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003335 return 0;
3336 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003337 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003338 return 0;
3339 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003340 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003341 return 0;
3342 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003343 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003344 return 0;
3345 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003346 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003347 return 0;
3348 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003349 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003350 return 0;
3351 }
3352}
3353
3354spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3355{
John Kessenich2f273362015-07-18 22:34:27 -06003356 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003357 spv::Id id;
3358 if (symbolValues.end() != iter) {
3359 id = iter->second;
3360 return id;
3361 }
3362
3363 // it was not found, create it
3364 id = createSpvVariable(symbol);
3365 symbolValues[symbol->getId()] = id;
3366
3367 if (! symbol->getType().isStruct()) {
3368 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003369 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003370 if (symbol->getQualifier().hasLocation())
3371 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3372 if (symbol->getQualifier().hasIndex())
3373 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3374 if (symbol->getQualifier().hasComponent())
3375 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3376 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003377 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003378 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003379 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003380 if (symbol->getQualifier().hasXfbBuffer())
3381 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3382 if (symbol->getQualifier().hasXfbOffset())
3383 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3384 }
3385 }
3386
John Kesseniche0b6cad2015-12-24 10:30:13 -07003387 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003388 if (symbol->getQualifier().hasStream()) {
3389 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003390 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003391 }
John Kessenich140f3df2015-06-26 16:58:36 -06003392 if (symbol->getQualifier().hasSet())
3393 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3394 if (symbol->getQualifier().hasBinding())
3395 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3396 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003397 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003398 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003399 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003400 if (symbol->getQualifier().hasXfbBuffer())
3401 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3402 }
3403
3404 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003405 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003407 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003408
John Kessenich140f3df2015-06-26 16:58:36 -06003409 return id;
3410}
3411
John Kessenich55e7d112015-11-15 21:33:39 -07003412// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003413void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3414{
3415 if (dec != spv::BadValue)
3416 builder.addDecoration(id, dec);
3417}
3418
John Kessenich55e7d112015-11-15 21:33:39 -07003419// If 'dec' is valid, add a one-operand decoration to an object
3420void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3421{
3422 if (dec != spv::BadValue)
3423 builder.addDecoration(id, dec, value);
3424}
3425
3426// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003427void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3428{
3429 if (dec != spv::BadValue)
3430 builder.addMemberDecoration(id, (unsigned)member, dec);
3431}
3432
John Kessenich92187592016-02-01 13:45:25 -07003433// If 'dec' is valid, add a one-operand decoration to a struct member
3434void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3435{
3436 if (dec != spv::BadValue)
3437 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3438}
3439
John Kessenich55e7d112015-11-15 21:33:39 -07003440// Make a full tree of instructions to build a SPIR-V specialization constant,
3441// or regularly constant if possible.
3442//
3443// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3444//
3445// Recursively walk the nodes. The nodes form a tree whose leaves are
3446// regular constants, which themselves are trees that createSpvConstant()
3447// recursively walks. So, this function walks the "top" of the tree:
3448// - emit specialization constant-building instructions for specConstant
3449// - when running into a non-spec-constant, switch to createSpvConstant()
3450spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3451{
3452 assert(node.getQualifier().storage == glslang::EvqConst);
3453
3454 // hand off to the non-spec-constant path
3455 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3456 int nextConst = 0;
3457 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3458}
3459
John Kessenich140f3df2015-06-26 16:58:36 -06003460// Use 'consts' as the flattened glslang source of scalar constants to recursively
3461// build the aggregate SPIR-V constant.
3462//
3463// If there are not enough elements present in 'consts', 0 will be substituted;
3464// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3465//
John Kessenich55e7d112015-11-15 21:33:39 -07003466spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003467{
3468 // vector of constants for SPIR-V
3469 std::vector<spv::Id> spvConsts;
3470
3471 // Type is used for struct and array constants
3472 spv::Id typeId = convertGlslangToSpvType(glslangType);
3473
3474 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003475 glslang::TType elementType(glslangType, 0);
3476 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003477 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003478 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003479 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003480 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003481 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003482 } else if (glslangType.getStruct()) {
3483 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3484 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003485 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003486 } else if (glslangType.isVector()) {
3487 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3488 bool zero = nextConst >= consts.size();
3489 switch (glslangType.getBasicType()) {
3490 case glslang::EbtInt:
3491 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3492 break;
3493 case glslang::EbtUint:
3494 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3495 break;
3496 case glslang::EbtFloat:
3497 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3498 break;
3499 case glslang::EbtDouble:
3500 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3501 break;
3502 case glslang::EbtBool:
3503 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3504 break;
3505 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003506 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003507 break;
3508 }
3509 ++nextConst;
3510 }
3511 } else {
3512 // we have a non-aggregate (scalar) constant
3513 bool zero = nextConst >= consts.size();
3514 spv::Id scalar = 0;
3515 switch (glslangType.getBasicType()) {
3516 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003517 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003518 break;
3519 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003520 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003521 break;
3522 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003523 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003524 break;
3525 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003526 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003527 break;
3528 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003529 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003530 break;
3531 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003532 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003533 break;
3534 }
3535 ++nextConst;
3536 return scalar;
3537 }
3538
3539 return builder.makeCompositeConstant(typeId, spvConsts);
3540}
3541
John Kessenich7c1aa102015-10-15 13:29:11 -06003542// Return true if the node is a constant or symbol whose reading has no
3543// non-trivial observable cost or effect.
3544bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3545{
3546 // don't know what this is
3547 if (node == nullptr)
3548 return false;
3549
3550 // a constant is safe
3551 if (node->getAsConstantUnion() != nullptr)
3552 return true;
3553
3554 // not a symbol means non-trivial
3555 if (node->getAsSymbolNode() == nullptr)
3556 return false;
3557
3558 // a symbol, depends on what's being read
3559 switch (node->getType().getQualifier().storage) {
3560 case glslang::EvqTemporary:
3561 case glslang::EvqGlobal:
3562 case glslang::EvqIn:
3563 case glslang::EvqInOut:
3564 case glslang::EvqConst:
3565 case glslang::EvqConstReadOnly:
3566 case glslang::EvqUniform:
3567 return true;
3568 default:
3569 return false;
3570 }
3571}
3572
3573// A node is trivial if it is a single operation with no side effects.
3574// Error on the side of saying non-trivial.
3575// Return true if trivial.
3576bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3577{
3578 if (node == nullptr)
3579 return false;
3580
3581 // symbols and constants are trivial
3582 if (isTrivialLeaf(node))
3583 return true;
3584
3585 // otherwise, it needs to be a simple operation or one or two leaf nodes
3586
3587 // not a simple operation
3588 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3589 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3590 if (binaryNode == nullptr && unaryNode == nullptr)
3591 return false;
3592
3593 // not on leaf nodes
3594 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3595 return false;
3596
3597 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3598 return false;
3599 }
3600
3601 switch (node->getAsOperator()->getOp()) {
3602 case glslang::EOpLogicalNot:
3603 case glslang::EOpConvIntToBool:
3604 case glslang::EOpConvUintToBool:
3605 case glslang::EOpConvFloatToBool:
3606 case glslang::EOpConvDoubleToBool:
3607 case glslang::EOpEqual:
3608 case glslang::EOpNotEqual:
3609 case glslang::EOpLessThan:
3610 case glslang::EOpGreaterThan:
3611 case glslang::EOpLessThanEqual:
3612 case glslang::EOpGreaterThanEqual:
3613 case glslang::EOpIndexDirect:
3614 case glslang::EOpIndexDirectStruct:
3615 case glslang::EOpLogicalXor:
3616 case glslang::EOpAny:
3617 case glslang::EOpAll:
3618 return true;
3619 default:
3620 return false;
3621 }
3622}
3623
3624// Emit short-circuiting code, where 'right' is never evaluated unless
3625// the left side is true (for &&) or false (for ||).
3626spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3627{
3628 spv::Id boolTypeId = builder.makeBoolType();
3629
3630 // emit left operand
3631 builder.clearAccessChain();
3632 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003633 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003634
3635 // Operands to accumulate OpPhi operands
3636 std::vector<spv::Id> phiOperands;
3637 // accumulate left operand's phi information
3638 phiOperands.push_back(leftId);
3639 phiOperands.push_back(builder.getBuildPoint()->getId());
3640
3641 // Make the two kinds of operation symmetric with a "!"
3642 // || => emit "if (! left) result = right"
3643 // && => emit "if ( left) result = right"
3644 //
3645 // TODO: this runtime "not" for || could be avoided by adding functionality
3646 // to 'builder' to have an "else" without an "then"
3647 if (op == glslang::EOpLogicalOr)
3648 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3649
3650 // make an "if" based on the left value
3651 spv::Builder::If ifBuilder(leftId, builder);
3652
3653 // emit right operand as the "then" part of the "if"
3654 builder.clearAccessChain();
3655 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003656 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003657
3658 // accumulate left operand's phi information
3659 phiOperands.push_back(rightId);
3660 phiOperands.push_back(builder.getBuildPoint()->getId());
3661
3662 // finish the "if"
3663 ifBuilder.makeEndIf();
3664
3665 // phi together the two results
3666 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3667}
3668
John Kessenich140f3df2015-06-26 16:58:36 -06003669}; // end anonymous namespace
3670
3671namespace glslang {
3672
John Kessenich68d78fd2015-07-12 19:28:10 -06003673void GetSpirvVersion(std::string& version)
3674{
John Kessenich9e55f632015-07-15 10:03:39 -06003675 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003676 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003677 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003678 version = buf;
3679}
3680
John Kessenich140f3df2015-06-26 16:58:36 -06003681// Write SPIR-V out to a binary file
3682void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3683{
3684 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003685 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003686 for (int i = 0; i < (int)spirv.size(); ++i) {
3687 unsigned int word = spirv[i];
3688 out.write((const char*)&word, 4);
3689 }
3690 out.close();
3691}
3692
3693//
3694// Set up the glslang traversal
3695//
3696void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3697{
3698 TIntermNode* root = intermediate.getTreeRoot();
3699
3700 if (root == 0)
3701 return;
3702
3703 glslang::GetThreadPoolAllocator().push();
3704
3705 TGlslangToSpvTraverser it(&intermediate);
3706
3707 root->traverse(&it);
3708
3709 it.dumpSpv(spirv);
3710
3711 glslang::GetThreadPoolAllocator().pop();
3712}
3713
3714}; // end namespace glslang