blob: 2a3ce8ec44e9ba26885705211f2b3f53c2d35b03 [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:
John Kessenich103bef92016-02-08 21:38:15 -07001573 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1574 // a 32-bit int where non-0 means true.
1575 if (explicitLayout != glslang::ElpNone)
1576 spvType = builder.makeUintType(32);
1577 else
1578 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001579 break;
1580 case glslang::EbtInt:
1581 spvType = builder.makeIntType(32);
1582 break;
1583 case glslang::EbtUint:
1584 spvType = builder.makeUintType(32);
1585 break;
John Kessenich426394d2015-07-23 10:22:48 -06001586 case glslang::EbtAtomicUint:
1587 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1588 spvType = builder.makeUintType(32);
1589 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001590 case glslang::EbtSampler:
1591 {
1592 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001593 // an image is present, make its type
1594 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1595 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001596 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001597 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001598 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001599 }
John Kessenich140f3df2015-06-26 16:58:36 -06001600 break;
1601 case glslang::EbtStruct:
1602 case glslang::EbtBlock:
1603 {
1604 // If we've seen this struct type, return it
1605 const glslang::TTypeList* glslangStruct = type.getStruct();
1606 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001607
1608 // Try to share structs for different layouts, but not yet for other
1609 // kinds of qualification (primarily not yet including interpolant qualification).
1610 if (! HasNonLayoutQualifiers(qualifier))
1611 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1612 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001613 break;
1614
1615 // else, we haven't seen it...
1616
1617 // Create a vector of struct types for SPIR-V to consume
1618 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1619 if (type.getBasicType() == glslang::EbtBlock)
1620 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001621 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001622 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1623 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1624 if (glslangType.hiddenMember()) {
1625 ++memberDelta;
1626 if (type.getBasicType() == glslang::EbtBlock)
1627 memberRemapper[glslangStruct][i] = -1;
1628 } else {
1629 if (type.getBasicType() == glslang::EbtBlock)
1630 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001631 // modify just this child's view of the qualifier
1632 glslang::TQualifier subQualifier = glslangType.getQualifier();
1633 InheritQualifiers(subQualifier, qualifier);
John Kessenich7b9fa252016-01-21 18:56:57 -07001634 if (qualifier.hasLocation()) {
1635 subQualifier.layoutLocation += locationOffset;
1636 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1637 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001638 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001639 }
1640 }
1641
1642 // Make the SPIR-V type
1643 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001644 if (! HasNonLayoutQualifiers(qualifier))
1645 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001646
1647 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001648 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001649 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001650 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1651 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1652 int member = i;
1653 if (type.getBasicType() == glslang::EbtBlock)
1654 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001655
John Kesseniche0b6cad2015-12-24 10:30:13 -07001656 // modify just this child's view of the qualifier
1657 glslang::TQualifier subQualifier = glslangType.getQualifier();
1658 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001659
John Kessenich140f3df2015-06-26 16:58:36 -06001660 // using -1 above to indicate a hidden member
1661 if (member >= 0) {
1662 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001663 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001664 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001665 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1666 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich7b9fa252016-01-21 18:56:57 -07001667 if (qualifier.hasLocation()) {
1668 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, qualifier.layoutLocation + locationOffset);
1669 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1670 }
John Kessenich140f3df2015-06-26 16:58:36 -06001671 if (glslangType.getQualifier().hasComponent())
1672 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1673 if (glslangType.getQualifier().hasXfbOffset())
1674 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001675 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001676 // figure out what to do with offset, which is accumulating
1677 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001678 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001679 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001680 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001681 offset = nextOffset;
1682 }
John Kessenich140f3df2015-06-26 16:58:36 -06001683
John Kessenichf85e8062015-12-19 13:57:10 -07001684 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001685 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001686
John Kessenich140f3df2015-06-26 16:58:36 -06001687 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001688 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1689 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001690 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001691 }
1692 }
1693
1694 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001695 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001696 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001697 if (type.getQualifier().hasStream()) {
1698 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001699 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001700 }
John Kessenich140f3df2015-06-26 16:58:36 -06001701 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001702 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001703 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001704 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001705 if (type.getQualifier().hasXfbBuffer())
1706 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1707 }
1708 }
1709 break;
1710 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001711 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001712 break;
1713 }
1714
1715 if (type.isMatrix())
1716 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1717 else {
1718 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1719 if (type.getVectorSize() > 1)
1720 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1721 }
1722
1723 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001724 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1725
John Kessenichc9a80832015-09-12 12:17:44 -06001726 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001727 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001728 // We need to decorate array strides for types needing explicit layout, except blocks.
1729 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001730 // Use a dummy glslang type for querying internal strides of
1731 // arrays of arrays, but using just a one-dimensional array.
1732 glslang::TType simpleArrayType(type, 0); // deference type of the array
1733 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1734 simpleArrayType.getArraySizes().dereference();
1735
1736 // Will compute the higher-order strides here, rather than making a whole
1737 // pile of types and doing repetitive recursion on their contents.
1738 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1739 }
John Kessenichf8842e52016-01-04 19:22:56 -07001740
1741 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001742 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1743 int size = type.getArraySizes()->getDimSize(dim);
1744 assert(size > 0);
1745 spvType = builder.makeArrayType(spvType, size, stride);
1746 if (stride > 0)
1747 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1748 stride *= size;
1749 }
1750 } else {
1751 // single-dimensional array, and don't yet have stride
1752
John Kessenichf8842e52016-01-04 19:22:56 -07001753 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001754 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1755 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001756 }
John Kessenich31ed4832015-09-09 17:51:38 -06001757
John Kessenichc9a80832015-09-12 12:17:44 -06001758 // Do the outer dimension, which might not be known for a runtime-sized array
1759 if (type.isRuntimeSizedArray()) {
1760 spvType = builder.makeRuntimeArray(spvType);
1761 } else {
1762 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001763 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001764 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001765 if (stride > 0)
1766 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001767 }
1768
1769 return spvType;
1770}
1771
John Kessenich103bef92016-02-08 21:38:15 -07001772// Wrap the builder's accessChainLoad to:
1773// - localize handling of RelaxedPrecision
1774// - use the SPIR-V inferred type instead of another conversion of the glslang type
1775// (avoids unnecessary work and possible type punning for structures)
1776// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001777spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1778{
John Kessenich103bef92016-02-08 21:38:15 -07001779 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1780 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1781
1782 // Need to convert to abstract types when necessary
1783 if (builder.isScalarType(nominalTypeId) && type.getBasicType() == glslang::EbtBool && nominalTypeId != builder.makeBoolType())
1784 loadedId = builder.createBinOp(spv::OpINotEqual, builder.makeBoolType(), loadedId, builder.makeUintConstant(0));
1785
1786 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001787}
1788
John Kessenichf85e8062015-12-19 13:57:10 -07001789// Decide whether or not this type should be
1790// decorated with offsets and strides, and if so
1791// whether std140 or std430 rules should be applied.
1792glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001793{
John Kessenichf85e8062015-12-19 13:57:10 -07001794 // has to be a block
1795 if (type.getBasicType() != glslang::EbtBlock)
1796 return glslang::ElpNone;
1797
1798 // has to be a uniform or buffer block
1799 if (type.getQualifier().storage != glslang::EvqUniform &&
1800 type.getQualifier().storage != glslang::EvqBuffer)
1801 return glslang::ElpNone;
1802
1803 // return the layout to use
1804 switch (type.getQualifier().layoutPacking) {
1805 case glslang::ElpStd140:
1806 case glslang::ElpStd430:
1807 return type.getQualifier().layoutPacking;
1808 default:
1809 return glslang::ElpNone;
1810 }
John Kessenich31ed4832015-09-09 17:51:38 -06001811}
1812
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001813// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001814int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001815{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001816 int size;
John Kessenich49987892015-12-29 17:11:44 -07001817 int stride;
1818 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001819
1820 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001821}
1822
John Kessenich49987892015-12-29 17:11:44 -07001823// 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 -07001824// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001825int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001826{
John Kessenich49987892015-12-29 17:11:44 -07001827 glslang::TType elementType;
1828 elementType.shallowCopy(matrixType);
1829 elementType.clearArraySizes();
1830
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001831 int size;
John Kessenich49987892015-12-29 17:11:44 -07001832 int stride;
1833 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1834
1835 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001836}
1837
John Kessenich5e4b1242015-08-06 22:53:06 -06001838// Given a member type of a struct, realign the current offset for it, and compute
1839// the next (not yet aligned) offset for the next member, which will get aligned
1840// on the next call.
1841// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1842// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1843// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001844void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001845 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001846{
1847 // this will get a positive value when deemed necessary
1848 nextOffset = -1;
1849
John Kessenich5e4b1242015-08-06 22:53:06 -06001850 // override anything in currentOffset with user-set offset
1851 if (memberType.getQualifier().hasOffset())
1852 currentOffset = memberType.getQualifier().layoutOffset;
1853
1854 // It could be that current linker usage in glslang updated all the layoutOffset,
1855 // in which case the following code does not matter. But, that's not quite right
1856 // once cross-compilation unit GLSL validation is done, as the original user
1857 // settings are needed in layoutOffset, and then the following will come into play.
1858
John Kessenichf85e8062015-12-19 13:57:10 -07001859 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001860 if (! memberType.getQualifier().hasOffset())
1861 currentOffset = -1;
1862
1863 return;
1864 }
1865
John Kessenichf85e8062015-12-19 13:57:10 -07001866 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001867 if (currentOffset < 0)
1868 currentOffset = 0;
1869
1870 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1871 // but possibly not yet correctly aligned.
1872
1873 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001874 int dummyStride;
1875 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001876 glslang::RoundToPow2(currentOffset, memberAlignment);
1877 nextOffset = currentOffset + memberSize;
1878}
1879
John Kessenich140f3df2015-06-26 16:58:36 -06001880bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1881{
1882 return node->getName() == "main(";
1883}
1884
1885// Make all the functions, skeletally, without actually visiting their bodies.
1886void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1887{
1888 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1889 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1890 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1891 continue;
1892
1893 // We're on a user function. Set up the basic interface for the function now,
1894 // so that it's available to call.
1895 // Translating the body will happen later.
1896 //
1897 // Typically (except for a "const in" parameter), an address will be passed to the
1898 // function. What it is an address of varies:
1899 //
1900 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1901 // so that write needs to be to a copy, hence the address of a copy works.
1902 //
1903 // - "const in" parameters can just be the r-value, as no writes need occur.
1904 //
1905 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1906 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1907
1908 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07001909 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06001910 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1911
1912 for (int p = 0; p < (int)parameters.size(); ++p) {
1913 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1914 spv::Id typeId = convertGlslangToSpvType(paramType);
1915 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1916 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1917 else
1918 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07001919 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06001920 paramTypes.push_back(typeId);
1921 }
1922
1923 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07001924 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
1925 convertGlslangToSpvType(glslFunction->getType()),
1926 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06001927
1928 // Track function to emit/call later
1929 functionMap[glslFunction->getName().c_str()] = function;
1930
1931 // Set the parameter id's
1932 for (int p = 0; p < (int)parameters.size(); ++p) {
1933 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1934 // give a name too
1935 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1936 }
1937 }
1938}
1939
1940// Process all the initializers, while skipping the functions and link objects
1941void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1942{
1943 builder.setBuildPoint(shaderEntry->getLastBlock());
1944 for (int i = 0; i < (int)initializers.size(); ++i) {
1945 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1946 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1947
1948 // We're on a top-level node that's not a function. Treat as an initializer, whose
1949 // code goes into the beginning of main.
1950 initializer->traverse(this);
1951 }
1952 }
1953}
1954
1955// Process all the functions, while skipping initializers.
1956void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1957{
1958 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1959 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1960 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1961 node->traverse(this);
1962 }
1963}
1964
1965void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1966{
1967 // SPIR-V functions should already be in the functionMap from the prepass
1968 // that called makeFunctions().
1969 spv::Function* function = functionMap[node->getName().c_str()];
1970 spv::Block* functionBlock = function->getEntryBlock();
1971 builder.setBuildPoint(functionBlock);
1972}
1973
Rex Xu04db3f52015-09-16 11:44:02 +08001974void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001975{
Rex Xufc618912015-09-09 16:42:49 +08001976 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08001977
1978 glslang::TSampler sampler = {};
1979 bool cubeCompare = false;
1980 if (node.isTexture()) {
1981 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
1982 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1983 }
1984
John Kessenich140f3df2015-06-26 16:58:36 -06001985 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1986 builder.clearAccessChain();
1987 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001988
1989 // Special case l-value operands
1990 bool lvalue = false;
1991 switch (node.getOp()) {
1992 case glslang::EOpImageAtomicAdd:
1993 case glslang::EOpImageAtomicMin:
1994 case glslang::EOpImageAtomicMax:
1995 case glslang::EOpImageAtomicAnd:
1996 case glslang::EOpImageAtomicOr:
1997 case glslang::EOpImageAtomicXor:
1998 case glslang::EOpImageAtomicExchange:
1999 case glslang::EOpImageAtomicCompSwap:
2000 if (i == 0)
2001 lvalue = true;
2002 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002003 case glslang::EOpSparseTexture:
2004 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2005 lvalue = true;
2006 break;
2007 case glslang::EOpSparseTextureClamp:
2008 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2009 lvalue = true;
2010 break;
2011 case glslang::EOpSparseTextureLod:
2012 case glslang::EOpSparseTextureOffset:
2013 if (i == 3)
2014 lvalue = true;
2015 break;
2016 case glslang::EOpSparseTextureFetch:
2017 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2018 lvalue = true;
2019 break;
2020 case glslang::EOpSparseTextureFetchOffset:
2021 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2022 lvalue = true;
2023 break;
2024 case glslang::EOpSparseTextureLodOffset:
2025 case glslang::EOpSparseTextureGrad:
2026 case glslang::EOpSparseTextureOffsetClamp:
2027 if (i == 4)
2028 lvalue = true;
2029 break;
2030 case glslang::EOpSparseTextureGradOffset:
2031 case glslang::EOpSparseTextureGradClamp:
2032 if (i == 5)
2033 lvalue = true;
2034 break;
2035 case glslang::EOpSparseTextureGradOffsetClamp:
2036 if (i == 6)
2037 lvalue = true;
2038 break;
2039 case glslang::EOpSparseTextureGather:
2040 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2041 lvalue = true;
2042 break;
2043 case glslang::EOpSparseTextureGatherOffset:
2044 case glslang::EOpSparseTextureGatherOffsets:
2045 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2046 lvalue = true;
2047 break;
Rex Xufc618912015-09-09 16:42:49 +08002048 default:
2049 break;
2050 }
2051
Rex Xu6b86d492015-09-16 17:48:22 +08002052 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002053 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002054 else
John Kessenich32cfd492016-02-02 12:37:46 -07002055 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002056 }
2057}
2058
John Kessenichfc51d282015-08-19 13:34:18 -06002059void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002060{
John Kessenichfc51d282015-08-19 13:34:18 -06002061 builder.clearAccessChain();
2062 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002063 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002064}
John Kessenich140f3df2015-06-26 16:58:36 -06002065
John Kessenichfc51d282015-08-19 13:34:18 -06002066spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2067{
Rex Xufc618912015-09-09 16:42:49 +08002068 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002069 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002070 }
2071
John Kessenichfc51d282015-08-19 13:34:18 -06002072 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002073 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2074 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2075 std::vector<spv::Id> arguments;
2076 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002077 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002078 else
2079 translateArguments(*node->getAsUnaryNode(), arguments);
2080 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2081
2082 spv::Builder::TextureParameters params = { };
2083 params.sampler = arguments[0];
2084
Rex Xu04db3f52015-09-16 11:44:02 +08002085 glslang::TCrackedTextureOp cracked;
2086 node->crackTexture(sampler, cracked);
2087
John Kessenichfc51d282015-08-19 13:34:18 -06002088 // Check for queries
2089 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002090 // a sampled image needs to have the image extracted first
2091 if (builder.isSampledImage(params.sampler))
2092 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002093 switch (node->getOp()) {
2094 case glslang::EOpImageQuerySize:
2095 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002096 if (arguments.size() > 1) {
2097 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002098 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002099 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002100 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002101 case glslang::EOpImageQuerySamples:
2102 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002103 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002104 case glslang::EOpTextureQueryLod:
2105 params.coords = arguments[1];
2106 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2107 case glslang::EOpTextureQueryLevels:
2108 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002109 case glslang::EOpSparseTexelsResident:
2110 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002111 default:
2112 assert(0);
2113 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002114 }
John Kessenich140f3df2015-06-26 16:58:36 -06002115 }
2116
Rex Xufc618912015-09-09 16:42:49 +08002117 // Check for image functions other than queries
2118 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002119 std::vector<spv::Id> operands;
2120 auto opIt = arguments.begin();
2121 operands.push_back(*(opIt++));
2122 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002123 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002124 if (sampler.ms) {
2125 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002126 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002127 }
John Kessenich56bab042015-09-16 10:54:31 -06002128 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2129 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002130 if (sampler.ms) {
2131 operands.push_back(*(opIt + 1));
2132 operands.push_back(spv::ImageOperandsSampleMask);
2133 operands.push_back(*opIt);
2134 } else
2135 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002136 builder.createNoResultOp(spv::OpImageWrite, operands);
2137 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002138 } else if (node->isSparseImage()) {
2139 spv::MissingFunctionality("sparse image functions");
2140 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002141 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002142 // Process image atomic operations
2143
2144 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2145 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002146 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002147
Rex Xufc618912015-09-09 16:42:49 +08002148 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002149 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002150
2151 std::vector<spv::Id> operands;
2152 operands.push_back(pointer);
2153 for (; opIt != arguments.end(); ++opIt)
2154 operands.push_back(*opIt);
2155
Rex Xu04db3f52015-09-16 11:44:02 +08002156 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002157 }
2158 }
2159
2160 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002161 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002162 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2163
John Kessenichfc51d282015-08-19 13:34:18 -06002164 // check for bias argument
2165 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002166 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002167 int nonBiasArgCount = 2;
2168 if (cracked.offset)
2169 ++nonBiasArgCount;
2170 if (cracked.grad)
2171 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002172 if (cracked.lodClamp)
2173 ++nonBiasArgCount;
2174 if (sparse)
2175 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002176
2177 if ((int)arguments.size() > nonBiasArgCount)
2178 bias = true;
2179 }
2180
John Kessenichfc51d282015-08-19 13:34:18 -06002181 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002182
John Kessenichfc51d282015-08-19 13:34:18 -06002183 params.coords = arguments[1];
2184 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002185
2186 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002187 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002188 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002189 ++extraArgs;
2190 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002191 params.Dref = arguments[2];
2192 ++extraArgs;
2193 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002194 std::vector<spv::Id> indexes;
2195 int comp;
2196 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002197 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002198 else
2199 comp = builder.getNumComponents(params.coords) - 1;
2200 indexes.push_back(comp);
2201 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2202 }
2203 if (cracked.lod) {
2204 params.lod = arguments[2];
2205 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002206 } else if (sampler.ms) {
2207 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002208 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002209 }
2210 if (cracked.grad) {
2211 params.gradX = arguments[2 + extraArgs];
2212 params.gradY = arguments[3 + extraArgs];
2213 extraArgs += 2;
2214 }
John Kessenich55e7d112015-11-15 21:33:39 -07002215 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002216 params.offset = arguments[2 + extraArgs];
2217 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002218 } else if (cracked.offsets) {
2219 params.offsets = arguments[2 + extraArgs];
2220 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002221 }
Rex Xu48edadf2015-12-31 16:11:41 +08002222 if (cracked.lodClamp) {
2223 params.lodClamp = arguments[2 + extraArgs];
2224 ++extraArgs;
2225 }
2226 if (sparse) {
2227 params.texelOut = arguments[2 + extraArgs];
2228 ++extraArgs;
2229 }
John Kessenichfc51d282015-08-19 13:34:18 -06002230 if (bias) {
2231 params.bias = arguments[2 + extraArgs];
2232 ++extraArgs;
2233 }
John Kessenich55e7d112015-11-15 21:33:39 -07002234 if (cracked.gather && ! sampler.shadow) {
2235 // default component is 0, if missing, otherwise an argument
2236 if (2 + extraArgs < (int)arguments.size()) {
2237 params.comp = arguments[2 + extraArgs];
2238 ++extraArgs;
2239 } else {
2240 params.comp = builder.makeIntConstant(0);
2241 }
2242 }
John Kessenichfc51d282015-08-19 13:34:18 -06002243
Rex Xu48edadf2015-12-31 16:11:41 +08002244 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002245}
2246
2247spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2248{
2249 // Grab the function's pointer from the previously created function
2250 spv::Function* function = functionMap[node->getName().c_str()];
2251 if (! function)
2252 return 0;
2253
2254 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2255 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2256
2257 // See comments in makeFunctions() for details about the semantics for parameter passing.
2258 //
2259 // These imply we need a four step process:
2260 // 1. Evaluate the arguments
2261 // 2. Allocate and make copies of in, out, and inout arguments
2262 // 3. Make the call
2263 // 4. Copy back the results
2264
2265 // 1. Evaluate the arguments
2266 std::vector<spv::Builder::AccessChain> lValues;
2267 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002268 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002269 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2270 // build l-value
2271 builder.clearAccessChain();
2272 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002273 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002274 // keep outputs as l-values, evaluate input-only as r-values
2275 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2276 // save l-value
2277 lValues.push_back(builder.getAccessChain());
2278 } else {
2279 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002280 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002281 }
2282 }
2283
2284 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2285 // copy the original into that space.
2286 //
2287 // Also, build up the list of actual arguments to pass in for the call
2288 int lValueCount = 0;
2289 int rValueCount = 0;
2290 std::vector<spv::Id> spvArgs;
2291 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2292 spv::Id arg;
2293 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2294 // need space to hold the copy
2295 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2296 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2297 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2298 // need to copy the input into output space
2299 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002300 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002301 builder.createStore(copy, arg);
2302 }
2303 ++lValueCount;
2304 } else {
2305 arg = rValues[rValueCount];
2306 ++rValueCount;
2307 }
2308 spvArgs.push_back(arg);
2309 }
2310
2311 // 3. Make the call.
2312 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002313 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002314
2315 // 4. Copy back out an "out" arguments.
2316 lValueCount = 0;
2317 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2318 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2319 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2320 spv::Id copy = builder.createLoad(spvArgs[a]);
2321 builder.setAccessChain(lValues[lValueCount]);
2322 builder.accessChainStore(copy);
2323 }
2324 ++lValueCount;
2325 }
2326 }
2327
2328 return result;
2329}
2330
2331// Translate AST operation to SPV operation, already having SPV-based operands/types.
2332spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2333 spv::Id typeId, spv::Id left, spv::Id right,
2334 glslang::TBasicType typeProxy, bool reduceComparison)
2335{
2336 bool isUnsigned = typeProxy == glslang::EbtUint;
2337 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2338
2339 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002340 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002341 bool comparison = false;
2342
2343 switch (op) {
2344 case glslang::EOpAdd:
2345 case glslang::EOpAddAssign:
2346 if (isFloat)
2347 binOp = spv::OpFAdd;
2348 else
2349 binOp = spv::OpIAdd;
2350 break;
2351 case glslang::EOpSub:
2352 case glslang::EOpSubAssign:
2353 if (isFloat)
2354 binOp = spv::OpFSub;
2355 else
2356 binOp = spv::OpISub;
2357 break;
2358 case glslang::EOpMul:
2359 case glslang::EOpMulAssign:
2360 if (isFloat)
2361 binOp = spv::OpFMul;
2362 else
2363 binOp = spv::OpIMul;
2364 break;
2365 case glslang::EOpVectorTimesScalar:
2366 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002367 if (isFloat) {
2368 if (builder.isVector(right))
2369 std::swap(left, right);
2370 assert(builder.isScalar(right));
2371 needMatchingVectors = false;
2372 binOp = spv::OpVectorTimesScalar;
2373 } else
2374 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002375 break;
2376 case glslang::EOpVectorTimesMatrix:
2377 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002378 binOp = spv::OpVectorTimesMatrix;
2379 break;
2380 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002381 binOp = spv::OpMatrixTimesVector;
2382 break;
2383 case glslang::EOpMatrixTimesScalar:
2384 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002385 binOp = spv::OpMatrixTimesScalar;
2386 break;
2387 case glslang::EOpMatrixTimesMatrix:
2388 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002389 binOp = spv::OpMatrixTimesMatrix;
2390 break;
2391 case glslang::EOpOuterProduct:
2392 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002393 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002394 break;
2395
2396 case glslang::EOpDiv:
2397 case glslang::EOpDivAssign:
2398 if (isFloat)
2399 binOp = spv::OpFDiv;
2400 else if (isUnsigned)
2401 binOp = spv::OpUDiv;
2402 else
2403 binOp = spv::OpSDiv;
2404 break;
2405 case glslang::EOpMod:
2406 case glslang::EOpModAssign:
2407 if (isFloat)
2408 binOp = spv::OpFMod;
2409 else if (isUnsigned)
2410 binOp = spv::OpUMod;
2411 else
2412 binOp = spv::OpSMod;
2413 break;
2414 case glslang::EOpRightShift:
2415 case glslang::EOpRightShiftAssign:
2416 if (isUnsigned)
2417 binOp = spv::OpShiftRightLogical;
2418 else
2419 binOp = spv::OpShiftRightArithmetic;
2420 break;
2421 case glslang::EOpLeftShift:
2422 case glslang::EOpLeftShiftAssign:
2423 binOp = spv::OpShiftLeftLogical;
2424 break;
2425 case glslang::EOpAnd:
2426 case glslang::EOpAndAssign:
2427 binOp = spv::OpBitwiseAnd;
2428 break;
2429 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002430 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002431 binOp = spv::OpLogicalAnd;
2432 break;
2433 case glslang::EOpInclusiveOr:
2434 case glslang::EOpInclusiveOrAssign:
2435 binOp = spv::OpBitwiseOr;
2436 break;
2437 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002438 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002439 binOp = spv::OpLogicalOr;
2440 break;
2441 case glslang::EOpExclusiveOr:
2442 case glslang::EOpExclusiveOrAssign:
2443 binOp = spv::OpBitwiseXor;
2444 break;
2445 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002446 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002447 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002448 break;
2449
2450 case glslang::EOpLessThan:
2451 case glslang::EOpGreaterThan:
2452 case glslang::EOpLessThanEqual:
2453 case glslang::EOpGreaterThanEqual:
2454 case glslang::EOpEqual:
2455 case glslang::EOpNotEqual:
2456 case glslang::EOpVectorEqual:
2457 case glslang::EOpVectorNotEqual:
2458 comparison = true;
2459 break;
2460 default:
2461 break;
2462 }
2463
John Kessenich7c1aa102015-10-15 13:29:11 -06002464 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002465 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002466 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002467 if (builder.isMatrix(left) || builder.isMatrix(right))
2468 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002469
2470 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002471 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002472 builder.promoteScalar(precision, left, right);
2473
John Kessenich32cfd492016-02-02 12:37:46 -07002474 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002475 }
2476
2477 if (! comparison)
2478 return 0;
2479
John Kessenich7c1aa102015-10-15 13:29:11 -06002480 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002481
2482 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2483 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2484
John Kessenich22118352015-12-21 20:54:09 -07002485 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002486 }
2487
2488 switch (op) {
2489 case glslang::EOpLessThan:
2490 if (isFloat)
2491 binOp = spv::OpFOrdLessThan;
2492 else if (isUnsigned)
2493 binOp = spv::OpULessThan;
2494 else
2495 binOp = spv::OpSLessThan;
2496 break;
2497 case glslang::EOpGreaterThan:
2498 if (isFloat)
2499 binOp = spv::OpFOrdGreaterThan;
2500 else if (isUnsigned)
2501 binOp = spv::OpUGreaterThan;
2502 else
2503 binOp = spv::OpSGreaterThan;
2504 break;
2505 case glslang::EOpLessThanEqual:
2506 if (isFloat)
2507 binOp = spv::OpFOrdLessThanEqual;
2508 else if (isUnsigned)
2509 binOp = spv::OpULessThanEqual;
2510 else
2511 binOp = spv::OpSLessThanEqual;
2512 break;
2513 case glslang::EOpGreaterThanEqual:
2514 if (isFloat)
2515 binOp = spv::OpFOrdGreaterThanEqual;
2516 else if (isUnsigned)
2517 binOp = spv::OpUGreaterThanEqual;
2518 else
2519 binOp = spv::OpSGreaterThanEqual;
2520 break;
2521 case glslang::EOpEqual:
2522 case glslang::EOpVectorEqual:
2523 if (isFloat)
2524 binOp = spv::OpFOrdEqual;
2525 else
2526 binOp = spv::OpIEqual;
2527 break;
2528 case glslang::EOpNotEqual:
2529 case glslang::EOpVectorNotEqual:
2530 if (isFloat)
2531 binOp = spv::OpFOrdNotEqual;
2532 else
2533 binOp = spv::OpINotEqual;
2534 break;
2535 default:
2536 break;
2537 }
2538
John Kessenich32cfd492016-02-02 12:37:46 -07002539 if (binOp != spv::OpNop)
2540 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002541
2542 return 0;
2543}
2544
John Kessenich04bb8a02015-12-12 12:28:14 -07002545//
2546// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2547// These can be any of:
2548//
2549// matrix * scalar
2550// scalar * matrix
2551// matrix * matrix linear algebraic
2552// matrix * vector
2553// vector * matrix
2554// matrix * matrix componentwise
2555// matrix op matrix op in {+, -, /}
2556// matrix op scalar op in {+, -, /}
2557// scalar op matrix op in {+, -, /}
2558//
2559spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2560{
2561 bool firstClass = true;
2562
2563 // First, handle first-class matrix operations (* and matrix/scalar)
2564 switch (op) {
2565 case spv::OpFDiv:
2566 if (builder.isMatrix(left) && builder.isScalar(right)) {
2567 // turn matrix / scalar into a multiply...
2568 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2569 op = spv::OpMatrixTimesScalar;
2570 } else
2571 firstClass = false;
2572 break;
2573 case spv::OpMatrixTimesScalar:
2574 if (builder.isMatrix(right))
2575 std::swap(left, right);
2576 assert(builder.isScalar(right));
2577 break;
2578 case spv::OpVectorTimesMatrix:
2579 assert(builder.isVector(left));
2580 assert(builder.isMatrix(right));
2581 break;
2582 case spv::OpMatrixTimesVector:
2583 assert(builder.isMatrix(left));
2584 assert(builder.isVector(right));
2585 break;
2586 case spv::OpMatrixTimesMatrix:
2587 assert(builder.isMatrix(left));
2588 assert(builder.isMatrix(right));
2589 break;
2590 default:
2591 firstClass = false;
2592 break;
2593 }
2594
John Kessenich32cfd492016-02-02 12:37:46 -07002595 if (firstClass)
2596 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002597
2598 // Handle component-wise +, -, *, and / for all combinations of type.
2599 // The result type of all of them is the same type as the (a) matrix operand.
2600 // The algorithm is to:
2601 // - break the matrix(es) into vectors
2602 // - smear any scalar to a vector
2603 // - do vector operations
2604 // - make a matrix out the vector results
2605 switch (op) {
2606 case spv::OpFAdd:
2607 case spv::OpFSub:
2608 case spv::OpFDiv:
2609 case spv::OpFMul:
2610 {
2611 // one time set up...
2612 bool leftMat = builder.isMatrix(left);
2613 bool rightMat = builder.isMatrix(right);
2614 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2615 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2616 spv::Id scalarType = builder.getScalarTypeId(typeId);
2617 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2618 std::vector<spv::Id> results;
2619 spv::Id smearVec = spv::NoResult;
2620 if (builder.isScalar(left))
2621 smearVec = builder.smearScalar(precision, left, vecType);
2622 else if (builder.isScalar(right))
2623 smearVec = builder.smearScalar(precision, right, vecType);
2624
2625 // do each vector op
2626 for (unsigned int c = 0; c < numCols; ++c) {
2627 std::vector<unsigned int> indexes;
2628 indexes.push_back(c);
2629 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2630 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2631 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2632 builder.setPrecision(results.back(), precision);
2633 }
2634
2635 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002636 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002637 }
2638 default:
2639 assert(0);
2640 return spv::NoResult;
2641 }
2642}
2643
Rex Xu04db3f52015-09-16 11:44:02 +08002644spv::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 -06002645{
2646 spv::Op unaryOp = spv::OpNop;
2647 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002648 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002649 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002650
2651 switch (op) {
2652 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002653 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002654 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002655 if (builder.isMatrixType(typeId))
2656 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2657 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002658 unaryOp = spv::OpSNegate;
2659 break;
2660
2661 case glslang::EOpLogicalNot:
2662 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002663 unaryOp = spv::OpLogicalNot;
2664 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002665 case glslang::EOpBitwiseNot:
2666 unaryOp = spv::OpNot;
2667 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002668
John Kessenich140f3df2015-06-26 16:58:36 -06002669 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002670 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002671 break;
2672 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002673 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002674 break;
2675 case glslang::EOpTranspose:
2676 unaryOp = spv::OpTranspose;
2677 break;
2678
2679 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002680 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002681 break;
2682 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002683 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002684 break;
2685 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002686 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002687 break;
2688 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002689 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002690 break;
2691 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002692 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002693 break;
2694 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002695 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002696 break;
2697 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002698 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002699 break;
2700 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002701 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002702 break;
2703
2704 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002705 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002706 break;
2707 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002709 break;
2710 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002711 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002712 break;
2713 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002714 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002715 break;
2716 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002717 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002718 break;
2719 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002720 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002721 break;
2722
2723 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002724 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002725 break;
2726 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002727 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002728 break;
2729
2730 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002731 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002732 break;
2733 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002734 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002735 break;
2736 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002737 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002738 break;
2739 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002740 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002741 break;
2742 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002743 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002744 break;
2745 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002746 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002747 break;
2748
2749 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002750 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002751 break;
2752 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002753 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002754 break;
2755 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002756 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002757 break;
2758 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002759 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002760 break;
2761 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002762 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002763 break;
2764 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002765 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002766 break;
2767
2768 case glslang::EOpIsNan:
2769 unaryOp = spv::OpIsNan;
2770 break;
2771 case glslang::EOpIsInf:
2772 unaryOp = spv::OpIsInf;
2773 break;
2774
Rex Xucbc426e2015-12-15 16:03:10 +08002775 case glslang::EOpFloatBitsToInt:
2776 case glslang::EOpFloatBitsToUint:
2777 case glslang::EOpIntBitsToFloat:
2778 case glslang::EOpUintBitsToFloat:
2779 unaryOp = spv::OpBitcast;
2780 break;
2781
John Kessenich140f3df2015-06-26 16:58:36 -06002782 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002783 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002784 break;
2785 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002786 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002787 break;
2788 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002789 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002790 break;
2791 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002792 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002793 break;
2794 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002795 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002796 break;
2797 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002798 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002799 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002800 case glslang::EOpPackSnorm4x8:
2801 libCall = spv::GLSLstd450PackSnorm4x8;
2802 break;
2803 case glslang::EOpUnpackSnorm4x8:
2804 libCall = spv::GLSLstd450UnpackSnorm4x8;
2805 break;
2806 case glslang::EOpPackUnorm4x8:
2807 libCall = spv::GLSLstd450PackUnorm4x8;
2808 break;
2809 case glslang::EOpUnpackUnorm4x8:
2810 libCall = spv::GLSLstd450UnpackUnorm4x8;
2811 break;
2812 case glslang::EOpPackDouble2x32:
2813 libCall = spv::GLSLstd450PackDouble2x32;
2814 break;
2815 case glslang::EOpUnpackDouble2x32:
2816 libCall = spv::GLSLstd450UnpackDouble2x32;
2817 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002818
2819 case glslang::EOpDPdx:
2820 unaryOp = spv::OpDPdx;
2821 break;
2822 case glslang::EOpDPdy:
2823 unaryOp = spv::OpDPdy;
2824 break;
2825 case glslang::EOpFwidth:
2826 unaryOp = spv::OpFwidth;
2827 break;
2828 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07002829 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002830 unaryOp = spv::OpDPdxFine;
2831 break;
2832 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07002833 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002834 unaryOp = spv::OpDPdyFine;
2835 break;
2836 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07002837 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002838 unaryOp = spv::OpFwidthFine;
2839 break;
2840 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002841 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002842 unaryOp = spv::OpDPdxCoarse;
2843 break;
2844 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002845 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002846 unaryOp = spv::OpDPdyCoarse;
2847 break;
2848 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002849 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002850 unaryOp = spv::OpFwidthCoarse;
2851 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002852 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07002853 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08002854 libCall = spv::GLSLstd450InterpolateAtCentroid;
2855 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002856 case glslang::EOpAny:
2857 unaryOp = spv::OpAny;
2858 break;
2859 case glslang::EOpAll:
2860 unaryOp = spv::OpAll;
2861 break;
2862
2863 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002864 if (isFloat)
2865 libCall = spv::GLSLstd450FAbs;
2866 else
2867 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002868 break;
2869 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002870 if (isFloat)
2871 libCall = spv::GLSLstd450FSign;
2872 else
2873 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002874 break;
2875
John Kessenichfc51d282015-08-19 13:34:18 -06002876 case glslang::EOpAtomicCounterIncrement:
2877 case glslang::EOpAtomicCounterDecrement:
2878 case glslang::EOpAtomicCounter:
2879 {
2880 // Handle all of the atomics in one place, in createAtomicOperation()
2881 std::vector<spv::Id> operands;
2882 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002883 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002884 }
2885
2886 case glslang::EOpImageLoad:
2887 unaryOp = spv::OpImageRead;
2888 break;
2889
2890 case glslang::EOpBitFieldReverse:
2891 unaryOp = spv::OpBitReverse;
2892 break;
2893 case glslang::EOpBitCount:
2894 unaryOp = spv::OpBitCount;
2895 break;
2896 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002897 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002898 break;
2899 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002900 if (isUnsigned)
2901 libCall = spv::GLSLstd450FindUMsb;
2902 else
2903 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002904 break;
2905
John Kessenich140f3df2015-06-26 16:58:36 -06002906 default:
2907 return 0;
2908 }
2909
2910 spv::Id id;
2911 if (libCall >= 0) {
2912 std::vector<spv::Id> args;
2913 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07002914 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06002915 } else
2916 id = builder.createUnaryOp(unaryOp, typeId, operand);
2917
John Kessenich32cfd492016-02-02 12:37:46 -07002918 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002919}
2920
John Kessenich7a53f762016-01-20 11:19:27 -07002921// Create a unary operation on a matrix
2922spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
2923{
2924 // Handle unary operations vector by vector.
2925 // The result type is the same type as the original type.
2926 // The algorithm is to:
2927 // - break the matrix into vectors
2928 // - apply the operation to each vector
2929 // - make a matrix out the vector results
2930
2931 // get the types sorted out
2932 int numCols = builder.getNumColumns(operand);
2933 int numRows = builder.getNumRows(operand);
2934 spv::Id scalarType = builder.getScalarTypeId(typeId);
2935 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2936 std::vector<spv::Id> results;
2937
2938 // do each vector op
2939 for (int c = 0; c < numCols; ++c) {
2940 std::vector<unsigned int> indexes;
2941 indexes.push_back(c);
2942 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
2943 results.push_back(builder.createUnaryOp(op, vecType, vec));
2944 builder.setPrecision(results.back(), precision);
2945 }
2946
2947 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002948 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07002949}
2950
John Kessenich140f3df2015-06-26 16:58:36 -06002951spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2952{
2953 spv::Op convOp = spv::OpNop;
2954 spv::Id zero = 0;
2955 spv::Id one = 0;
2956
2957 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2958
2959 switch (op) {
2960 case glslang::EOpConvIntToBool:
2961 case glslang::EOpConvUintToBool:
2962 zero = builder.makeUintConstant(0);
2963 zero = makeSmearedConstant(zero, vectorSize);
2964 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2965
2966 case glslang::EOpConvFloatToBool:
2967 zero = builder.makeFloatConstant(0.0F);
2968 zero = makeSmearedConstant(zero, vectorSize);
2969 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2970
2971 case glslang::EOpConvDoubleToBool:
2972 zero = builder.makeDoubleConstant(0.0);
2973 zero = makeSmearedConstant(zero, vectorSize);
2974 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2975
2976 case glslang::EOpConvBoolToFloat:
2977 convOp = spv::OpSelect;
2978 zero = builder.makeFloatConstant(0.0);
2979 one = builder.makeFloatConstant(1.0);
2980 break;
2981 case glslang::EOpConvBoolToDouble:
2982 convOp = spv::OpSelect;
2983 zero = builder.makeDoubleConstant(0.0);
2984 one = builder.makeDoubleConstant(1.0);
2985 break;
2986 case glslang::EOpConvBoolToInt:
2987 zero = builder.makeIntConstant(0);
2988 one = builder.makeIntConstant(1);
2989 convOp = spv::OpSelect;
2990 break;
2991 case glslang::EOpConvBoolToUint:
2992 zero = builder.makeUintConstant(0);
2993 one = builder.makeUintConstant(1);
2994 convOp = spv::OpSelect;
2995 break;
2996
2997 case glslang::EOpConvIntToFloat:
2998 case glslang::EOpConvIntToDouble:
2999 convOp = spv::OpConvertSToF;
3000 break;
3001
3002 case glslang::EOpConvUintToFloat:
3003 case glslang::EOpConvUintToDouble:
3004 convOp = spv::OpConvertUToF;
3005 break;
3006
3007 case glslang::EOpConvDoubleToFloat:
3008 case glslang::EOpConvFloatToDouble:
3009 convOp = spv::OpFConvert;
3010 break;
3011
3012 case glslang::EOpConvFloatToInt:
3013 case glslang::EOpConvDoubleToInt:
3014 convOp = spv::OpConvertFToS;
3015 break;
3016
3017 case glslang::EOpConvUintToInt:
3018 case glslang::EOpConvIntToUint:
3019 convOp = spv::OpBitcast;
3020 break;
3021
3022 case glslang::EOpConvFloatToUint:
3023 case glslang::EOpConvDoubleToUint:
3024 convOp = spv::OpConvertFToU;
3025 break;
3026 default:
3027 break;
3028 }
3029
3030 spv::Id result = 0;
3031 if (convOp == spv::OpNop)
3032 return result;
3033
3034 if (convOp == spv::OpSelect) {
3035 zero = makeSmearedConstant(zero, vectorSize);
3036 one = makeSmearedConstant(one, vectorSize);
3037 result = builder.createTriOp(convOp, destType, operand, one, zero);
3038 } else
3039 result = builder.createUnaryOp(convOp, destType, operand);
3040
John Kessenich32cfd492016-02-02 12:37:46 -07003041 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003042}
3043
3044spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3045{
3046 if (vectorSize == 0)
3047 return constant;
3048
3049 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3050 std::vector<spv::Id> components;
3051 for (int c = 0; c < vectorSize; ++c)
3052 components.push_back(constant);
3053 return builder.makeCompositeConstant(vectorTypeId, components);
3054}
3055
John Kessenich426394d2015-07-23 10:22:48 -06003056// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08003057spv::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 -06003058{
3059 spv::Op opCode = spv::OpNop;
3060
3061 switch (op) {
3062 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003063 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003064 opCode = spv::OpAtomicIAdd;
3065 break;
3066 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003067 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003068 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003069 break;
3070 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003071 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003072 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003073 break;
3074 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003075 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003076 opCode = spv::OpAtomicAnd;
3077 break;
3078 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003079 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003080 opCode = spv::OpAtomicOr;
3081 break;
3082 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003083 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003084 opCode = spv::OpAtomicXor;
3085 break;
3086 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003087 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003088 opCode = spv::OpAtomicExchange;
3089 break;
3090 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003091 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003092 opCode = spv::OpAtomicCompareExchange;
3093 break;
3094 case glslang::EOpAtomicCounterIncrement:
3095 opCode = spv::OpAtomicIIncrement;
3096 break;
3097 case glslang::EOpAtomicCounterDecrement:
3098 opCode = spv::OpAtomicIDecrement;
3099 break;
3100 case glslang::EOpAtomicCounter:
3101 opCode = spv::OpAtomicLoad;
3102 break;
3103 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003104 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003105 break;
3106 }
3107
3108 // Sort out the operands
3109 // - mapping from glslang -> SPV
3110 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003111 // - compare-exchange swaps the value and comparator
3112 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003113 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3114 auto opIt = operands.begin(); // walk the glslang operands
3115 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003116 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3117 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3118 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003119 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3120 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003121 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003122 spvAtomicOperands.push_back(*(opIt + 1));
3123 spvAtomicOperands.push_back(*opIt);
3124 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003125 }
John Kessenich426394d2015-07-23 10:22:48 -06003126
John Kessenich3e60a6f2015-09-14 22:45:16 -06003127 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003128 for (; opIt != operands.end(); ++opIt)
3129 spvAtomicOperands.push_back(*opIt);
3130
3131 return builder.createOp(opCode, typeId, spvAtomicOperands);
3132}
3133
John Kessenich5e4b1242015-08-06 22:53:06 -06003134spv::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 -06003135{
John Kessenich5e4b1242015-08-06 22:53:06 -06003136 bool isUnsigned = typeProxy == glslang::EbtUint;
3137 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3138
John Kessenich140f3df2015-06-26 16:58:36 -06003139 spv::Op opCode = spv::OpNop;
3140 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003141 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003142 spv::Id typeId0 = 0;
3143 if (consumedOperands > 0)
3144 typeId0 = builder.getTypeId(operands[0]);
3145 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003146
3147 switch (op) {
3148 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003149 if (isFloat)
3150 libCall = spv::GLSLstd450FMin;
3151 else if (isUnsigned)
3152 libCall = spv::GLSLstd450UMin;
3153 else
3154 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003155 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003156 break;
3157 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003158 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003159 break;
3160 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003161 if (isFloat)
3162 libCall = spv::GLSLstd450FMax;
3163 else if (isUnsigned)
3164 libCall = spv::GLSLstd450UMax;
3165 else
3166 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003167 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003168 break;
3169 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003170 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003171 break;
3172 case glslang::EOpDot:
3173 opCode = spv::OpDot;
3174 break;
3175 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003176 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003177 break;
3178
3179 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003180 if (isFloat)
3181 libCall = spv::GLSLstd450FClamp;
3182 else if (isUnsigned)
3183 libCall = spv::GLSLstd450UClamp;
3184 else
3185 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003186 builder.promoteScalar(precision, operands.front(), operands[1]);
3187 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003188 break;
3189 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003190 if (isFloat)
3191 libCall = spv::GLSLstd450FMix;
3192 else
3193 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003194 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003195 break;
3196 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003197 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003198 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003199 break;
3200 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003201 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003202 builder.promoteScalar(precision, operands[0], operands[2]);
3203 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003204 break;
3205
3206 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003207 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003208 break;
3209 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003210 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003211 break;
3212 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003213 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003214 break;
3215 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003216 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003217 break;
3218 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003219 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003220 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003221 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003222 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003223 libCall = spv::GLSLstd450InterpolateAtSample;
3224 break;
3225 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003226 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003227 libCall = spv::GLSLstd450InterpolateAtOffset;
3228 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003229 case glslang::EOpAddCarry:
3230 opCode = spv::OpIAddCarry;
3231 typeId = builder.makeStructResultType(typeId0, typeId0);
3232 consumedOperands = 2;
3233 break;
3234 case glslang::EOpSubBorrow:
3235 opCode = spv::OpISubBorrow;
3236 typeId = builder.makeStructResultType(typeId0, typeId0);
3237 consumedOperands = 2;
3238 break;
3239 case glslang::EOpUMulExtended:
3240 opCode = spv::OpUMulExtended;
3241 typeId = builder.makeStructResultType(typeId0, typeId0);
3242 consumedOperands = 2;
3243 break;
3244 case glslang::EOpIMulExtended:
3245 opCode = spv::OpSMulExtended;
3246 typeId = builder.makeStructResultType(typeId0, typeId0);
3247 consumedOperands = 2;
3248 break;
3249 case glslang::EOpBitfieldExtract:
3250 if (isUnsigned)
3251 opCode = spv::OpBitFieldUExtract;
3252 else
3253 opCode = spv::OpBitFieldSExtract;
3254 break;
3255 case glslang::EOpBitfieldInsert:
3256 opCode = spv::OpBitFieldInsert;
3257 break;
3258
3259 case glslang::EOpFma:
3260 libCall = spv::GLSLstd450Fma;
3261 break;
3262 case glslang::EOpFrexp:
3263 libCall = spv::GLSLstd450FrexpStruct;
3264 if (builder.getNumComponents(operands[0]) == 1)
3265 frexpIntType = builder.makeIntegerType(32, true);
3266 else
3267 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3268 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3269 consumedOperands = 1;
3270 break;
3271 case glslang::EOpLdexp:
3272 libCall = spv::GLSLstd450Ldexp;
3273 break;
3274
John Kessenich140f3df2015-06-26 16:58:36 -06003275 default:
3276 return 0;
3277 }
3278
3279 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003280 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003281 // Use an extended instruction from the standard library.
3282 // Construct the call arguments, without modifying the original operands vector.
3283 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3284 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003285 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003286 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003287 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003288 case 0:
3289 // should all be handled by visitAggregate and createNoArgOperation
3290 assert(0);
3291 return 0;
3292 case 1:
3293 // should all be handled by createUnaryOperation
3294 assert(0);
3295 return 0;
3296 case 2:
3297 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3298 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003299 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003300 // anything 3 or over doesn't have l-value operands, so all should be consumed
3301 assert(consumedOperands == operands.size());
3302 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003303 break;
3304 }
3305 }
3306
John Kessenich55e7d112015-11-15 21:33:39 -07003307 // Decode the return types that were structures
3308 switch (op) {
3309 case glslang::EOpAddCarry:
3310 case glslang::EOpSubBorrow:
3311 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3312 id = builder.createCompositeExtract(id, typeId0, 0);
3313 break;
3314 case glslang::EOpUMulExtended:
3315 case glslang::EOpIMulExtended:
3316 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3317 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3318 break;
3319 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003320 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003321 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3322 id = builder.createCompositeExtract(id, typeId0, 0);
3323 break;
3324 default:
3325 break;
3326 }
3327
John Kessenich32cfd492016-02-02 12:37:46 -07003328 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003329}
3330
3331// Intrinsics with no arguments, no return value, and no precision.
3332spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3333{
3334 // TODO: get the barrier operands correct
3335
3336 switch (op) {
3337 case glslang::EOpEmitVertex:
3338 builder.createNoResultOp(spv::OpEmitVertex);
3339 return 0;
3340 case glslang::EOpEndPrimitive:
3341 builder.createNoResultOp(spv::OpEndPrimitive);
3342 return 0;
3343 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003344 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3345 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003346 return 0;
3347 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003348 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003349 return 0;
3350 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003351 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003352 return 0;
3353 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003354 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003355 return 0;
3356 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003357 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003358 return 0;
3359 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003360 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003361 return 0;
3362 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003363 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003364 return 0;
3365 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003366 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003367 return 0;
3368 }
3369}
3370
3371spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3372{
John Kessenich2f273362015-07-18 22:34:27 -06003373 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003374 spv::Id id;
3375 if (symbolValues.end() != iter) {
3376 id = iter->second;
3377 return id;
3378 }
3379
3380 // it was not found, create it
3381 id = createSpvVariable(symbol);
3382 symbolValues[symbol->getId()] = id;
3383
3384 if (! symbol->getType().isStruct()) {
3385 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003386 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003387 if (symbol->getQualifier().hasLocation())
3388 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3389 if (symbol->getQualifier().hasIndex())
3390 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3391 if (symbol->getQualifier().hasComponent())
3392 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3393 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003394 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003395 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003396 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003397 if (symbol->getQualifier().hasXfbBuffer())
3398 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3399 if (symbol->getQualifier().hasXfbOffset())
3400 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3401 }
3402 }
3403
John Kesseniche0b6cad2015-12-24 10:30:13 -07003404 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003405 if (symbol->getQualifier().hasStream()) {
3406 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003407 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003408 }
John Kessenich140f3df2015-06-26 16:58:36 -06003409 if (symbol->getQualifier().hasSet())
3410 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3411 if (symbol->getQualifier().hasBinding())
3412 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3413 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003414 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003415 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003416 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003417 if (symbol->getQualifier().hasXfbBuffer())
3418 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3419 }
3420
3421 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003422 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003423 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003424 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003425
John Kessenich140f3df2015-06-26 16:58:36 -06003426 return id;
3427}
3428
John Kessenich55e7d112015-11-15 21:33:39 -07003429// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003430void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3431{
3432 if (dec != spv::BadValue)
3433 builder.addDecoration(id, dec);
3434}
3435
John Kessenich55e7d112015-11-15 21:33:39 -07003436// If 'dec' is valid, add a one-operand decoration to an object
3437void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3438{
3439 if (dec != spv::BadValue)
3440 builder.addDecoration(id, dec, value);
3441}
3442
3443// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003444void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3445{
3446 if (dec != spv::BadValue)
3447 builder.addMemberDecoration(id, (unsigned)member, dec);
3448}
3449
John Kessenich92187592016-02-01 13:45:25 -07003450// If 'dec' is valid, add a one-operand decoration to a struct member
3451void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3452{
3453 if (dec != spv::BadValue)
3454 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3455}
3456
John Kessenich55e7d112015-11-15 21:33:39 -07003457// Make a full tree of instructions to build a SPIR-V specialization constant,
3458// or regularly constant if possible.
3459//
3460// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3461//
3462// Recursively walk the nodes. The nodes form a tree whose leaves are
3463// regular constants, which themselves are trees that createSpvConstant()
3464// recursively walks. So, this function walks the "top" of the tree:
3465// - emit specialization constant-building instructions for specConstant
3466// - when running into a non-spec-constant, switch to createSpvConstant()
3467spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3468{
3469 assert(node.getQualifier().storage == glslang::EvqConst);
3470
3471 // hand off to the non-spec-constant path
3472 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3473 int nextConst = 0;
3474 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3475}
3476
John Kessenich140f3df2015-06-26 16:58:36 -06003477// Use 'consts' as the flattened glslang source of scalar constants to recursively
3478// build the aggregate SPIR-V constant.
3479//
3480// If there are not enough elements present in 'consts', 0 will be substituted;
3481// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3482//
John Kessenich55e7d112015-11-15 21:33:39 -07003483spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003484{
3485 // vector of constants for SPIR-V
3486 std::vector<spv::Id> spvConsts;
3487
3488 // Type is used for struct and array constants
3489 spv::Id typeId = convertGlslangToSpvType(glslangType);
3490
3491 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003492 glslang::TType elementType(glslangType, 0);
3493 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003494 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003495 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003496 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003497 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003498 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003499 } else if (glslangType.getStruct()) {
3500 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3501 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003502 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003503 } else if (glslangType.isVector()) {
3504 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3505 bool zero = nextConst >= consts.size();
3506 switch (glslangType.getBasicType()) {
3507 case glslang::EbtInt:
3508 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3509 break;
3510 case glslang::EbtUint:
3511 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3512 break;
3513 case glslang::EbtFloat:
3514 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3515 break;
3516 case glslang::EbtDouble:
3517 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3518 break;
3519 case glslang::EbtBool:
3520 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3521 break;
3522 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003523 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003524 break;
3525 }
3526 ++nextConst;
3527 }
3528 } else {
3529 // we have a non-aggregate (scalar) constant
3530 bool zero = nextConst >= consts.size();
3531 spv::Id scalar = 0;
3532 switch (glslangType.getBasicType()) {
3533 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003534 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003535 break;
3536 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003537 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003538 break;
3539 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003540 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003541 break;
3542 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003543 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003544 break;
3545 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003546 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003547 break;
3548 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003549 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003550 break;
3551 }
3552 ++nextConst;
3553 return scalar;
3554 }
3555
3556 return builder.makeCompositeConstant(typeId, spvConsts);
3557}
3558
John Kessenich7c1aa102015-10-15 13:29:11 -06003559// Return true if the node is a constant or symbol whose reading has no
3560// non-trivial observable cost or effect.
3561bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3562{
3563 // don't know what this is
3564 if (node == nullptr)
3565 return false;
3566
3567 // a constant is safe
3568 if (node->getAsConstantUnion() != nullptr)
3569 return true;
3570
3571 // not a symbol means non-trivial
3572 if (node->getAsSymbolNode() == nullptr)
3573 return false;
3574
3575 // a symbol, depends on what's being read
3576 switch (node->getType().getQualifier().storage) {
3577 case glslang::EvqTemporary:
3578 case glslang::EvqGlobal:
3579 case glslang::EvqIn:
3580 case glslang::EvqInOut:
3581 case glslang::EvqConst:
3582 case glslang::EvqConstReadOnly:
3583 case glslang::EvqUniform:
3584 return true;
3585 default:
3586 return false;
3587 }
3588}
3589
3590// A node is trivial if it is a single operation with no side effects.
3591// Error on the side of saying non-trivial.
3592// Return true if trivial.
3593bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3594{
3595 if (node == nullptr)
3596 return false;
3597
3598 // symbols and constants are trivial
3599 if (isTrivialLeaf(node))
3600 return true;
3601
3602 // otherwise, it needs to be a simple operation or one or two leaf nodes
3603
3604 // not a simple operation
3605 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3606 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3607 if (binaryNode == nullptr && unaryNode == nullptr)
3608 return false;
3609
3610 // not on leaf nodes
3611 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3612 return false;
3613
3614 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3615 return false;
3616 }
3617
3618 switch (node->getAsOperator()->getOp()) {
3619 case glslang::EOpLogicalNot:
3620 case glslang::EOpConvIntToBool:
3621 case glslang::EOpConvUintToBool:
3622 case glslang::EOpConvFloatToBool:
3623 case glslang::EOpConvDoubleToBool:
3624 case glslang::EOpEqual:
3625 case glslang::EOpNotEqual:
3626 case glslang::EOpLessThan:
3627 case glslang::EOpGreaterThan:
3628 case glslang::EOpLessThanEqual:
3629 case glslang::EOpGreaterThanEqual:
3630 case glslang::EOpIndexDirect:
3631 case glslang::EOpIndexDirectStruct:
3632 case glslang::EOpLogicalXor:
3633 case glslang::EOpAny:
3634 case glslang::EOpAll:
3635 return true;
3636 default:
3637 return false;
3638 }
3639}
3640
3641// Emit short-circuiting code, where 'right' is never evaluated unless
3642// the left side is true (for &&) or false (for ||).
3643spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3644{
3645 spv::Id boolTypeId = builder.makeBoolType();
3646
3647 // emit left operand
3648 builder.clearAccessChain();
3649 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003650 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003651
3652 // Operands to accumulate OpPhi operands
3653 std::vector<spv::Id> phiOperands;
3654 // accumulate left operand's phi information
3655 phiOperands.push_back(leftId);
3656 phiOperands.push_back(builder.getBuildPoint()->getId());
3657
3658 // Make the two kinds of operation symmetric with a "!"
3659 // || => emit "if (! left) result = right"
3660 // && => emit "if ( left) result = right"
3661 //
3662 // TODO: this runtime "not" for || could be avoided by adding functionality
3663 // to 'builder' to have an "else" without an "then"
3664 if (op == glslang::EOpLogicalOr)
3665 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3666
3667 // make an "if" based on the left value
3668 spv::Builder::If ifBuilder(leftId, builder);
3669
3670 // emit right operand as the "then" part of the "if"
3671 builder.clearAccessChain();
3672 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003673 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003674
3675 // accumulate left operand's phi information
3676 phiOperands.push_back(rightId);
3677 phiOperands.push_back(builder.getBuildPoint()->getId());
3678
3679 // finish the "if"
3680 ifBuilder.makeEndIf();
3681
3682 // phi together the two results
3683 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3684}
3685
John Kessenich140f3df2015-06-26 16:58:36 -06003686}; // end anonymous namespace
3687
3688namespace glslang {
3689
John Kessenich68d78fd2015-07-12 19:28:10 -06003690void GetSpirvVersion(std::string& version)
3691{
John Kessenich9e55f632015-07-15 10:03:39 -06003692 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003693 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003694 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003695 version = buf;
3696}
3697
John Kessenich140f3df2015-06-26 16:58:36 -06003698// Write SPIR-V out to a binary file
3699void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3700{
3701 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003702 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003703 for (int i = 0; i < (int)spirv.size(); ++i) {
3704 unsigned int word = spirv[i];
3705 out.write((const char*)&word, 4);
3706 }
3707 out.close();
3708}
3709
3710//
3711// Set up the glslang traversal
3712//
3713void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3714{
3715 TIntermNode* root = intermediate.getTreeRoot();
3716
3717 if (root == 0)
3718 return;
3719
3720 glslang::GetThreadPoolAllocator().push();
3721
3722 TGlslangToSpvTraverser it(&intermediate);
3723
3724 root->traverse(&it);
3725
3726 it.dumpSpv(spirv);
3727
3728 glslang::GetThreadPoolAllocator().pop();
3729}
3730
3731}; // end namespace glslang