blob: a75c7caf9fa85476bf3bba9f9575e6a8f39a7fa3 [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 Kessenichf85e8062015-12-19 13:57:10 -070096 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -070097 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
98 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
99 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 -0600100
101 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
102 void makeFunctions(const glslang::TIntermSequence&);
103 void makeGlobalInitializers(const glslang::TIntermSequence&);
104 void visitFunctions(const glslang::TIntermSequence&);
105 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800106 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600107 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
108 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600109 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
110
111 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 -0700112 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800113 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 -0700114 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600115 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
116 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800117 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 -0600118 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 -0600119 spv::Id createNoArgOperation(glslang::TOperator op);
120 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
121 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700122 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600123 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700124 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700125 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
126 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600127 bool isTrivialLeaf(const glslang::TIntermTyped* node);
128 bool isTrivial(const glslang::TIntermTyped* node);
129 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600130
131 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700132 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600133 int sequenceDepth;
134
135 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
136 spv::Builder builder;
137 bool inMain;
138 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700139 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 -0700140 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600141 const glslang::TIntermediate* glslangIntermediate;
142 spv::Id stdBuiltins;
143
John Kessenich2f273362015-07-18 22:34:27 -0600144 std::unordered_map<int, spv::Id> symbolValues;
145 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
146 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700147 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600148 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 -0600149 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600150};
151
152//
153// Helper functions for translating glslang representations to SPIR-V enumerants.
154//
155
156// Translate glslang profile to SPIR-V source language.
157spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
158{
159 switch (profile) {
160 case ENoProfile:
161 case ECoreProfile:
162 case ECompatibilityProfile:
163 return spv::SourceLanguageGLSL;
164 case EEsProfile:
165 return spv::SourceLanguageESSL;
166 default:
167 return spv::SourceLanguageUnknown;
168 }
169}
170
171// Translate glslang language (stage) to SPIR-V execution model.
172spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
173{
174 switch (stage) {
175 case EShLangVertex: return spv::ExecutionModelVertex;
176 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
177 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
178 case EShLangGeometry: return spv::ExecutionModelGeometry;
179 case EShLangFragment: return spv::ExecutionModelFragment;
180 case EShLangCompute: return spv::ExecutionModelGLCompute;
181 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700182 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600183 return spv::ExecutionModelFragment;
184 }
185}
186
187// Translate glslang type to SPIR-V storage class.
188spv::StorageClass TranslateStorageClass(const glslang::TType& type)
189{
190 if (type.getQualifier().isPipeInput())
191 return spv::StorageClassInput;
192 else if (type.getQualifier().isPipeOutput())
193 return spv::StorageClassOutput;
194 else if (type.getQualifier().isUniformOrBuffer()) {
195 if (type.getBasicType() == glslang::EbtBlock)
196 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800197 else if (type.getBasicType() == glslang::EbtAtomicUint)
198 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600199 else
200 return spv::StorageClassUniformConstant;
201 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
202 } else {
203 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700204 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
205 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600206 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
207 case glslang::EvqTemporary: return spv::StorageClassFunction;
208 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700209 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600210 return spv::StorageClassFunction;
211 }
212 }
213}
214
215// Translate glslang sampler type to SPIR-V dimensionality.
216spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
217{
218 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700219 case glslang::Esd1D: return spv::Dim1D;
220 case glslang::Esd2D: return spv::Dim2D;
221 case glslang::Esd3D: return spv::Dim3D;
222 case glslang::EsdCube: return spv::DimCube;
223 case glslang::EsdRect: return spv::DimRect;
224 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600225 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700226 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600227 return spv::Dim2D;
228 }
229}
230
231// Translate glslang type to SPIR-V precision decorations.
232spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
233{
234 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700235 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600236 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
237 case glslang::EpqHigh: return spv::NoPrecision;
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 Kessenichfa668da2015-09-13 14:46:30 -0600712 spv::Id rValue = builder.accessChainLoad(convertGlslangToSpvType(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 Kessenichfa668da2015-09-13 14:46:30 -0600717 spv::Id leftRValue = builder.accessChainLoad(convertGlslangToSpvType(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 Kessenichfa668da2015-09-13 14:46:30 -0600785 spv::Id index = builder.accessChainLoad(convertGlslangToSpvType(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
827 // Get the operands
828 builder.clearAccessChain();
829 node->getLeft()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600830 spv::Id left = builder.accessChainLoad(convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600831
832 builder.clearAccessChain();
833 node->getRight()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -0600834 spv::Id right = builder.accessChainLoad(convertGlslangToSpvType(node->getRight()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600835
836 spv::Id result;
837 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
838
839 result = createBinaryOperation(node->getOp(), precision,
840 convertGlslangToSpvType(node->getType()), left, right,
841 node->getLeft()->getType().getBasicType());
842
John Kessenich50e57562015-12-21 21:21:11 -0700843 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600844 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700845 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700846 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600847 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600848 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600849 return false;
850 }
John Kessenich140f3df2015-06-26 16:58:36 -0600851}
852
853bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
854{
John Kessenichfc51d282015-08-19 13:34:18 -0600855 spv::Id result = spv::NoResult;
856
857 // try texturing first
858 result = createImageTextureFunctionCall(node);
859 if (result != spv::NoResult) {
860 builder.clearAccessChain();
861 builder.setAccessChainRValue(result);
862
863 return false; // done with this node
864 }
865
866 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600867
868 if (node->getOp() == glslang::EOpArrayLength) {
869 // Quite special; won't want to evaluate the operand.
870
871 // Normal .length() would have been constant folded by the front-end.
872 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600873 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600874 assert(node->getOperand()->getType().isRuntimeSizedArray());
875 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
876 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600877 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
878 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600879
880 builder.clearAccessChain();
881 builder.setAccessChainRValue(length);
882
883 return false;
884 }
885
John Kessenichfc51d282015-08-19 13:34:18 -0600886 // Start by evaluating the operand
887
John Kessenich140f3df2015-06-26 16:58:36 -0600888 builder.clearAccessChain();
889 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800890
Rex Xufc618912015-09-09 16:42:49 +0800891 spv::Id operand = spv::NoResult;
892
893 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
894 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800895 node->getOp() == glslang::EOpAtomicCounter ||
896 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800897 operand = builder.accessChainGetLValue(); // Special case l-value operands
898 else
Rex Xu30f92582015-09-14 10:38:56 +0800899 operand = builder.accessChainLoad(convertGlslangToSpvType(node->getOperand()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600900
901 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
902
903 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600904 if (! result)
905 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600906
907 // if not, then possibly an operation
908 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700909 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600910
911 if (result) {
912 builder.clearAccessChain();
913 builder.setAccessChainRValue(result);
914
915 return false; // done with this node
916 }
917
918 // it must be a special case, check...
919 switch (node->getOp()) {
920 case glslang::EOpPostIncrement:
921 case glslang::EOpPostDecrement:
922 case glslang::EOpPreIncrement:
923 case glslang::EOpPreDecrement:
924 {
925 // we need the integer value "1" or the floating point "1.0" to add/subtract
926 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
927 builder.makeFloatConstant(1.0F) :
928 builder.makeIntConstant(1);
929 glslang::TOperator op;
930 if (node->getOp() == glslang::EOpPreIncrement ||
931 node->getOp() == glslang::EOpPostIncrement)
932 op = glslang::EOpAdd;
933 else
934 op = glslang::EOpSub;
935
936 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
937 convertGlslangToSpvType(node->getType()), operand, one,
938 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700939 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600940
941 // The result of operation is always stored, but conditionally the
942 // consumed result. The consumed result is always an r-value.
943 builder.accessChainStore(result);
944 builder.clearAccessChain();
945 if (node->getOp() == glslang::EOpPreIncrement ||
946 node->getOp() == glslang::EOpPreDecrement)
947 builder.setAccessChainRValue(result);
948 else
949 builder.setAccessChainRValue(operand);
950 }
951
952 return false;
953
954 case glslang::EOpEmitStreamVertex:
955 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
956 return false;
957 case glslang::EOpEndStreamPrimitive:
958 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
959 return false;
960
961 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700962 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -0700963 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -0600964 }
John Kessenich140f3df2015-06-26 16:58:36 -0600965}
966
967bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
968{
John Kessenichfc51d282015-08-19 13:34:18 -0600969 spv::Id result = spv::NoResult;
970
971 // try texturing
972 result = createImageTextureFunctionCall(node);
973 if (result != spv::NoResult) {
974 builder.clearAccessChain();
975 builder.setAccessChainRValue(result);
976
977 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600978 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800979 // "imageStore" is a special case, which has no result
980 return false;
981 }
John Kessenichfc51d282015-08-19 13:34:18 -0600982
John Kessenich140f3df2015-06-26 16:58:36 -0600983 glslang::TOperator binOp = glslang::EOpNull;
984 bool reduceComparison = true;
985 bool isMatrix = false;
986 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600987 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600988
989 assert(node->getOp());
990
991 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
992
993 switch (node->getOp()) {
994 case glslang::EOpSequence:
995 {
996 if (preVisit)
997 ++sequenceDepth;
998 else
999 --sequenceDepth;
1000
1001 if (sequenceDepth == 1) {
1002 // If this is the parent node of all the functions, we want to see them
1003 // early, so all call points have actual SPIR-V functions to reference.
1004 // In all cases, still let the traverser visit the children for us.
1005 makeFunctions(node->getAsAggregate()->getSequence());
1006
1007 // Also, we want all globals initializers to go into the entry of main(), before
1008 // anything else gets there, so visit out of order, doing them all now.
1009 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1010
1011 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1012 // so do them manually.
1013 visitFunctions(node->getAsAggregate()->getSequence());
1014
1015 return false;
1016 }
1017
1018 return true;
1019 }
1020 case glslang::EOpLinkerObjects:
1021 {
1022 if (visit == glslang::EvPreVisit)
1023 linkageOnly = true;
1024 else
1025 linkageOnly = false;
1026
1027 return true;
1028 }
1029 case glslang::EOpComma:
1030 {
1031 // processing from left to right naturally leaves the right-most
1032 // lying around in the access chain
1033 glslang::TIntermSequence& glslangOperands = node->getSequence();
1034 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1035 glslangOperands[i]->traverse(this);
1036
1037 return false;
1038 }
1039 case glslang::EOpFunction:
1040 if (visit == glslang::EvPreVisit) {
1041 if (isShaderEntrypoint(node)) {
1042 inMain = true;
1043 builder.setBuildPoint(shaderEntry->getLastBlock());
1044 } else {
1045 handleFunctionEntry(node);
1046 }
1047 } else {
1048 if (inMain)
1049 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001050 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001051 inMain = false;
1052 }
1053
1054 return true;
1055 case glslang::EOpParameters:
1056 // Parameters will have been consumed by EOpFunction processing, but not
1057 // the body, so we still visited the function node's children, making this
1058 // child redundant.
1059 return false;
1060 case glslang::EOpFunctionCall:
1061 {
1062 if (node->isUserDefined())
1063 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001064 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001065 builder.clearAccessChain();
1066 builder.setAccessChainRValue(result);
1067
1068 return false;
1069 }
1070 case glslang::EOpConstructMat2x2:
1071 case glslang::EOpConstructMat2x3:
1072 case glslang::EOpConstructMat2x4:
1073 case glslang::EOpConstructMat3x2:
1074 case glslang::EOpConstructMat3x3:
1075 case glslang::EOpConstructMat3x4:
1076 case glslang::EOpConstructMat4x2:
1077 case glslang::EOpConstructMat4x3:
1078 case glslang::EOpConstructMat4x4:
1079 case glslang::EOpConstructDMat2x2:
1080 case glslang::EOpConstructDMat2x3:
1081 case glslang::EOpConstructDMat2x4:
1082 case glslang::EOpConstructDMat3x2:
1083 case glslang::EOpConstructDMat3x3:
1084 case glslang::EOpConstructDMat3x4:
1085 case glslang::EOpConstructDMat4x2:
1086 case glslang::EOpConstructDMat4x3:
1087 case glslang::EOpConstructDMat4x4:
1088 isMatrix = true;
1089 // fall through
1090 case glslang::EOpConstructFloat:
1091 case glslang::EOpConstructVec2:
1092 case glslang::EOpConstructVec3:
1093 case glslang::EOpConstructVec4:
1094 case glslang::EOpConstructDouble:
1095 case glslang::EOpConstructDVec2:
1096 case glslang::EOpConstructDVec3:
1097 case glslang::EOpConstructDVec4:
1098 case glslang::EOpConstructBool:
1099 case glslang::EOpConstructBVec2:
1100 case glslang::EOpConstructBVec3:
1101 case glslang::EOpConstructBVec4:
1102 case glslang::EOpConstructInt:
1103 case glslang::EOpConstructIVec2:
1104 case glslang::EOpConstructIVec3:
1105 case glslang::EOpConstructIVec4:
1106 case glslang::EOpConstructUint:
1107 case glslang::EOpConstructUVec2:
1108 case glslang::EOpConstructUVec3:
1109 case glslang::EOpConstructUVec4:
1110 case glslang::EOpConstructStruct:
1111 {
1112 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001113 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001114 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1115 spv::Id constructed;
1116 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1117 std::vector<spv::Id> constituents;
1118 for (int c = 0; c < (int)arguments.size(); ++c)
1119 constituents.push_back(arguments[c]);
1120 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001121 } else if (isMatrix)
1122 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1123 else
1124 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001125
1126 builder.clearAccessChain();
1127 builder.setAccessChainRValue(constructed);
1128
1129 return false;
1130 }
1131
1132 // These six are component-wise compares with component-wise results.
1133 // Forward on to createBinaryOperation(), requesting a vector result.
1134 case glslang::EOpLessThan:
1135 case glslang::EOpGreaterThan:
1136 case glslang::EOpLessThanEqual:
1137 case glslang::EOpGreaterThanEqual:
1138 case glslang::EOpVectorEqual:
1139 case glslang::EOpVectorNotEqual:
1140 {
1141 // Map the operation to a binary
1142 binOp = node->getOp();
1143 reduceComparison = false;
1144 switch (node->getOp()) {
1145 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1146 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1147 default: binOp = node->getOp(); break;
1148 }
1149
1150 break;
1151 }
1152 case glslang::EOpMul:
1153 // compontent-wise matrix multiply
1154 binOp = glslang::EOpMul;
1155 break;
1156 case glslang::EOpOuterProduct:
1157 // two vectors multiplied to make a matrix
1158 binOp = glslang::EOpOuterProduct;
1159 break;
1160 case glslang::EOpDot:
1161 {
1162 // for scalar dot product, use multiply
1163 glslang::TIntermSequence& glslangOperands = node->getSequence();
1164 if (! glslangOperands[0]->getAsTyped()->isVector())
1165 binOp = glslang::EOpMul;
1166 break;
1167 }
1168 case glslang::EOpMod:
1169 // when an aggregate, this is the floating-point mod built-in function,
1170 // which can be emitted by the one in createBinaryOperation()
1171 binOp = glslang::EOpMod;
1172 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001173 case glslang::EOpEmitVertex:
1174 case glslang::EOpEndPrimitive:
1175 case glslang::EOpBarrier:
1176 case glslang::EOpMemoryBarrier:
1177 case glslang::EOpMemoryBarrierAtomicCounter:
1178 case glslang::EOpMemoryBarrierBuffer:
1179 case glslang::EOpMemoryBarrierImage:
1180 case glslang::EOpMemoryBarrierShared:
1181 case glslang::EOpGroupMemoryBarrier:
1182 noReturnValue = true;
1183 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1184 break;
1185
John Kessenich426394d2015-07-23 10:22:48 -06001186 case glslang::EOpAtomicAdd:
1187 case glslang::EOpAtomicMin:
1188 case glslang::EOpAtomicMax:
1189 case glslang::EOpAtomicAnd:
1190 case glslang::EOpAtomicOr:
1191 case glslang::EOpAtomicXor:
1192 case glslang::EOpAtomicExchange:
1193 case glslang::EOpAtomicCompSwap:
1194 atomic = true;
1195 break;
1196
John Kessenich140f3df2015-06-26 16:58:36 -06001197 default:
1198 break;
1199 }
1200
1201 //
1202 // See if it maps to a regular operation.
1203 //
John Kessenich140f3df2015-06-26 16:58:36 -06001204 if (binOp != glslang::EOpNull) {
1205 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1206 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1207 assert(left && right);
1208
1209 builder.clearAccessChain();
1210 left->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001211 spv::Id leftId = builder.accessChainLoad(convertGlslangToSpvType(left->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001212
1213 builder.clearAccessChain();
1214 right->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001215 spv::Id rightId = builder.accessChainLoad(convertGlslangToSpvType(right->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001216
1217 result = createBinaryOperation(binOp, precision,
1218 convertGlslangToSpvType(node->getType()), leftId, rightId,
1219 left->getType().getBasicType(), reduceComparison);
1220
1221 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001222 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001223 builder.clearAccessChain();
1224 builder.setAccessChainRValue(result);
1225
1226 return false;
1227 }
1228
John Kessenich426394d2015-07-23 10:22:48 -06001229 //
1230 // Create the list of operands.
1231 //
John Kessenich140f3df2015-06-26 16:58:36 -06001232 glslang::TIntermSequence& glslangOperands = node->getSequence();
1233 std::vector<spv::Id> operands;
1234 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1235 builder.clearAccessChain();
1236 glslangOperands[arg]->traverse(this);
1237
1238 // special case l-value operands; there are just a few
1239 bool lvalue = false;
1240 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001241 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001242 case glslang::EOpModf:
1243 if (arg == 1)
1244 lvalue = true;
1245 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001246 case glslang::EOpInterpolateAtSample:
1247 case glslang::EOpInterpolateAtOffset:
1248 if (arg == 0)
1249 lvalue = true;
1250 break;
Rex Xud4782c12015-09-06 16:30:11 +08001251 case glslang::EOpAtomicAdd:
1252 case glslang::EOpAtomicMin:
1253 case glslang::EOpAtomicMax:
1254 case glslang::EOpAtomicAnd:
1255 case glslang::EOpAtomicOr:
1256 case glslang::EOpAtomicXor:
1257 case glslang::EOpAtomicExchange:
1258 case glslang::EOpAtomicCompSwap:
1259 if (arg == 0)
1260 lvalue = true;
1261 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001262 case glslang::EOpAddCarry:
1263 case glslang::EOpSubBorrow:
1264 if (arg == 2)
1265 lvalue = true;
1266 break;
1267 case glslang::EOpUMulExtended:
1268 case glslang::EOpIMulExtended:
1269 if (arg >= 2)
1270 lvalue = true;
1271 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001272 default:
1273 break;
1274 }
1275 if (lvalue)
1276 operands.push_back(builder.accessChainGetLValue());
1277 else
John Kessenichfa668da2015-09-13 14:46:30 -06001278 operands.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangOperands[arg]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001279 }
John Kessenich426394d2015-07-23 10:22:48 -06001280
1281 if (atomic) {
1282 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001283 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001284 } else {
1285 // Pass through to generic operations.
1286 switch (glslangOperands.size()) {
1287 case 0:
1288 result = createNoArgOperation(node->getOp());
1289 break;
1290 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001291 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001292 break;
1293 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001294 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001295 break;
1296 }
John Kessenich140f3df2015-06-26 16:58:36 -06001297 }
1298
1299 if (noReturnValue)
1300 return false;
1301
1302 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001303 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001304 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001305 } else {
1306 builder.clearAccessChain();
1307 builder.setAccessChainRValue(result);
1308 return false;
1309 }
1310}
1311
1312bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1313{
1314 // This path handles both if-then-else and ?:
1315 // The if-then-else has a node type of void, while
1316 // ?: has a non-void node type
1317 spv::Id result = 0;
1318 if (node->getBasicType() != glslang::EbtVoid) {
1319 // don't handle this as just on-the-fly temporaries, because there will be two names
1320 // and better to leave SSA to later passes
1321 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1322 }
1323
1324 // emit the condition before doing anything with selection
1325 node->getCondition()->traverse(this);
1326
1327 // make an "if" based on the value created by the condition
John Kessenichfa668da2015-09-13 14:46:30 -06001328 spv::Builder::If ifBuilder(builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getType())), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 if (node->getTrueBlock()) {
1331 // emit the "then" statement
1332 node->getTrueBlock()->traverse(this);
1333 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001334 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getTrueBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001335 }
1336
1337 if (node->getFalseBlock()) {
1338 ifBuilder.makeBeginElse();
1339 // emit the "else" statement
1340 node->getFalseBlock()->traverse(this);
1341 if (result)
John Kessenichfa668da2015-09-13 14:46:30 -06001342 builder.createStore(builder.accessChainLoad(convertGlslangToSpvType(node->getFalseBlock()->getAsTyped()->getType())), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001343 }
1344
1345 ifBuilder.makeEndIf();
1346
1347 if (result) {
1348 // GLSL only has r-values as the result of a :?, but
1349 // if we have an l-value, that can be more efficient if it will
1350 // become the base of a complex r-value expression, because the
1351 // next layer copies r-values into memory to use the access-chain mechanism
1352 builder.clearAccessChain();
1353 builder.setAccessChainLValue(result);
1354 }
1355
1356 return false;
1357}
1358
1359bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1360{
1361 // emit and get the condition before doing anything with switch
1362 node->getCondition()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06001363 spv::Id selector = builder.accessChainLoad(convertGlslangToSpvType(node->getCondition()->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001364
1365 // browse the children to sort out code segments
1366 int defaultSegment = -1;
1367 std::vector<TIntermNode*> codeSegments;
1368 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1369 std::vector<int> caseValues;
1370 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1371 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1372 TIntermNode* child = *c;
1373 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001374 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001375 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001376 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001377 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1378 } else
1379 codeSegments.push_back(child);
1380 }
1381
1382 // handle the case where the last code segment is missing, due to no code
1383 // statements between the last case and the end of the switch statement
1384 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1385 (int)codeSegments.size() == defaultSegment)
1386 codeSegments.push_back(nullptr);
1387
1388 // make the switch statement
1389 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001390 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001391
1392 // emit all the code in the segments
1393 breakForLoop.push(false);
1394 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1395 builder.nextSwitchSegment(segmentBlocks, s);
1396 if (codeSegments[s])
1397 codeSegments[s]->traverse(this);
1398 else
1399 builder.addSwitchBreak();
1400 }
1401 breakForLoop.pop();
1402
1403 builder.endSwitch(segmentBlocks);
1404
1405 return false;
1406}
1407
1408void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1409{
1410 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001411 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001412
1413 builder.clearAccessChain();
1414 builder.setAccessChainRValue(constant);
1415}
1416
1417bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1418{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001419 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001420 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001421 // Spec requires back edges to target header blocks, and every header block
1422 // must dominate its merge block. Make a header block first to ensure these
1423 // conditions are met. By definition, it will contain OpLoopMerge, followed
1424 // by a block-ending branch. But we don't want to put any other body/test
1425 // instructions in it, since the body/test may have arbitrary instructions,
1426 // including merges of its own.
1427 builder.setBuildPoint(&blocks.head);
1428 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001429 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001430 spv::Block& test = builder.makeNewBlock();
1431 builder.createBranch(&test);
1432
1433 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001434 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001435 spv::Id condition =
1436 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001437 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1438
1439 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001440 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001441 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001442 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001443 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001444 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001445
1446 builder.setBuildPoint(&blocks.continue_target);
1447 if (node->getTerminal())
1448 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001449 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001450 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001451 builder.createBranch(&blocks.body);
1452
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001453 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001454 builder.setBuildPoint(&blocks.body);
1455 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001456 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001457 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001458 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001459
1460 builder.setBuildPoint(&blocks.continue_target);
1461 if (node->getTerminal())
1462 node->getTerminal()->traverse(this);
1463 if (node->getTest()) {
1464 node->getTest()->traverse(this);
1465 spv::Id condition =
1466 builder.accessChainLoad(convertGlslangToSpvType(node->getTest()->getType()));
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001467 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001468 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001469 // TODO: unless there was a break/return/discard instruction
1470 // somewhere in the body, this is an infinite loop, so we should
1471 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001472 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001473 }
John Kessenich140f3df2015-06-26 16:58:36 -06001474 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001475 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001476 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001477 return false;
1478}
1479
1480bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1481{
1482 if (node->getExpression())
1483 node->getExpression()->traverse(this);
1484
1485 switch (node->getFlowOp()) {
1486 case glslang::EOpKill:
1487 builder.makeDiscard();
1488 break;
1489 case glslang::EOpBreak:
1490 if (breakForLoop.top())
1491 builder.createLoopExit();
1492 else
1493 builder.addSwitchBreak();
1494 break;
1495 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001496 builder.createLoopContinue();
1497 break;
1498 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001499 if (node->getExpression())
John Kessenichfa668da2015-09-13 14:46:30 -06001500 builder.makeReturn(false, builder.accessChainLoad(convertGlslangToSpvType(node->getExpression()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06001501 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001502 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001503
1504 builder.clearAccessChain();
1505 break;
1506
1507 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001508 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001509 break;
1510 }
1511
1512 return false;
1513}
1514
1515spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1516{
1517 // First, steer off constants, which are not SPIR-V variables, but
1518 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001519 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001520 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001521 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001522 }
1523
1524 // Now, handle actual variables
1525 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1526 spv::Id spvType = convertGlslangToSpvType(node->getType());
1527
1528 const char* name = node->getName().c_str();
1529 if (glslang::IsAnonymous(name))
1530 name = "";
1531
1532 return builder.createVariable(storageClass, spvType, name);
1533}
1534
1535// Return type Id of the sampled type.
1536spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1537{
1538 switch (sampler.type) {
1539 case glslang::EbtFloat: return builder.makeFloatType(32);
1540 case glslang::EbtInt: return builder.makeIntType(32);
1541 case glslang::EbtUint: return builder.makeUintType(32);
1542 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001543 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001544 return builder.makeFloatType(32);
1545 }
1546}
1547
John Kessenich3ac051e2015-12-20 11:29:16 -07001548// Convert from a glslang type to an SPV type, by calling into a
1549// recursive version of this function. This establishes the inherited
1550// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001551spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1552{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001553 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001554}
1555
1556// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001557// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001558spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001559{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001560 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001561
1562 switch (type.getBasicType()) {
1563 case glslang::EbtVoid:
1564 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001565 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001566 break;
1567 case glslang::EbtFloat:
1568 spvType = builder.makeFloatType(32);
1569 break;
1570 case glslang::EbtDouble:
1571 spvType = builder.makeFloatType(64);
1572 break;
1573 case glslang::EbtBool:
1574 spvType = builder.makeBoolType();
1575 break;
1576 case glslang::EbtInt:
1577 spvType = builder.makeIntType(32);
1578 break;
1579 case glslang::EbtUint:
1580 spvType = builder.makeUintType(32);
1581 break;
John Kessenich426394d2015-07-23 10:22:48 -06001582 case glslang::EbtAtomicUint:
1583 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1584 spvType = builder.makeUintType(32);
1585 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001586 case glslang::EbtSampler:
1587 {
1588 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001589 // an image is present, make its type
1590 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1591 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001592 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001593 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001594 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001595 }
John Kessenich140f3df2015-06-26 16:58:36 -06001596 break;
1597 case glslang::EbtStruct:
1598 case glslang::EbtBlock:
1599 {
1600 // If we've seen this struct type, return it
1601 const glslang::TTypeList* glslangStruct = type.getStruct();
1602 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001603
1604 // Try to share structs for different layouts, but not yet for other
1605 // kinds of qualification (primarily not yet including interpolant qualification).
1606 if (! HasNonLayoutQualifiers(qualifier))
1607 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1608 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001609 break;
1610
1611 // else, we haven't seen it...
1612
1613 // Create a vector of struct types for SPIR-V to consume
1614 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1615 if (type.getBasicType() == glslang::EbtBlock)
1616 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001617 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001618 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1619 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1620 if (glslangType.hiddenMember()) {
1621 ++memberDelta;
1622 if (type.getBasicType() == glslang::EbtBlock)
1623 memberRemapper[glslangStruct][i] = -1;
1624 } else {
1625 if (type.getBasicType() == glslang::EbtBlock)
1626 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001627 // modify just this child's view of the qualifier
1628 glslang::TQualifier subQualifier = glslangType.getQualifier();
1629 InheritQualifiers(subQualifier, qualifier);
John Kessenich7b9fa252016-01-21 18:56:57 -07001630 if (qualifier.hasLocation()) {
1631 subQualifier.layoutLocation += locationOffset;
1632 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1633 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001634 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001635 }
1636 }
1637
1638 // Make the SPIR-V type
1639 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001640 if (! HasNonLayoutQualifiers(qualifier))
1641 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001642
1643 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001644 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001645 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001646 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1647 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1648 int member = i;
1649 if (type.getBasicType() == glslang::EbtBlock)
1650 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001651
John Kesseniche0b6cad2015-12-24 10:30:13 -07001652 // modify just this child's view of the qualifier
1653 glslang::TQualifier subQualifier = glslangType.getQualifier();
1654 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001655
John Kessenich140f3df2015-06-26 16:58:36 -06001656 // using -1 above to indicate a hidden member
1657 if (member >= 0) {
1658 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001659 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001660 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001661 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1662 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich7b9fa252016-01-21 18:56:57 -07001663 if (qualifier.hasLocation()) {
1664 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, qualifier.layoutLocation + locationOffset);
1665 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1666 }
John Kessenich140f3df2015-06-26 16:58:36 -06001667 if (glslangType.getQualifier().hasComponent())
1668 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1669 if (glslangType.getQualifier().hasXfbOffset())
1670 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001671 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001672 // figure out what to do with offset, which is accumulating
1673 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001674 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001675 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001676 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001677 offset = nextOffset;
1678 }
John Kessenich140f3df2015-06-26 16:58:36 -06001679
John Kessenichf85e8062015-12-19 13:57:10 -07001680 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001681 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001682
John Kessenich140f3df2015-06-26 16:58:36 -06001683 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001684 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1685 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001686 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001687 }
1688 }
1689
1690 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001691 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001692 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001693 if (type.getQualifier().hasStream()) {
1694 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001695 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001696 }
John Kessenich140f3df2015-06-26 16:58:36 -06001697 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001698 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001699 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001700 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001701 if (type.getQualifier().hasXfbBuffer())
1702 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1703 }
1704 }
1705 break;
1706 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001707 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001708 break;
1709 }
1710
1711 if (type.isMatrix())
1712 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1713 else {
1714 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1715 if (type.getVectorSize() > 1)
1716 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1717 }
1718
1719 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001720 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1721
John Kessenichc9a80832015-09-12 12:17:44 -06001722 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001723 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001724 // We need to decorate array strides for types needing explicit layout, except blocks.
1725 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001726 // Use a dummy glslang type for querying internal strides of
1727 // arrays of arrays, but using just a one-dimensional array.
1728 glslang::TType simpleArrayType(type, 0); // deference type of the array
1729 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1730 simpleArrayType.getArraySizes().dereference();
1731
1732 // Will compute the higher-order strides here, rather than making a whole
1733 // pile of types and doing repetitive recursion on their contents.
1734 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1735 }
John Kessenichf8842e52016-01-04 19:22:56 -07001736
1737 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001738 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1739 int size = type.getArraySizes()->getDimSize(dim);
1740 assert(size > 0);
1741 spvType = builder.makeArrayType(spvType, size, stride);
1742 if (stride > 0)
1743 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1744 stride *= size;
1745 }
1746 } else {
1747 // single-dimensional array, and don't yet have stride
1748
John Kessenichf8842e52016-01-04 19:22:56 -07001749 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001750 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1751 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001752 }
John Kessenich31ed4832015-09-09 17:51:38 -06001753
John Kessenichc9a80832015-09-12 12:17:44 -06001754 // Do the outer dimension, which might not be known for a runtime-sized array
1755 if (type.isRuntimeSizedArray()) {
1756 spvType = builder.makeRuntimeArray(spvType);
1757 } else {
1758 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001759 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001760 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001761 if (stride > 0)
1762 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001763 }
1764
1765 return spvType;
1766}
1767
John Kessenichf85e8062015-12-19 13:57:10 -07001768// Decide whether or not this type should be
1769// decorated with offsets and strides, and if so
1770// whether std140 or std430 rules should be applied.
1771glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001772{
John Kessenichf85e8062015-12-19 13:57:10 -07001773 // has to be a block
1774 if (type.getBasicType() != glslang::EbtBlock)
1775 return glslang::ElpNone;
1776
1777 // has to be a uniform or buffer block
1778 if (type.getQualifier().storage != glslang::EvqUniform &&
1779 type.getQualifier().storage != glslang::EvqBuffer)
1780 return glslang::ElpNone;
1781
1782 // return the layout to use
1783 switch (type.getQualifier().layoutPacking) {
1784 case glslang::ElpStd140:
1785 case glslang::ElpStd430:
1786 return type.getQualifier().layoutPacking;
1787 default:
1788 return glslang::ElpNone;
1789 }
John Kessenich31ed4832015-09-09 17:51:38 -06001790}
1791
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001792// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001793int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001794{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001795 int size;
John Kessenich49987892015-12-29 17:11:44 -07001796 int stride;
1797 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001798
1799 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001800}
1801
John Kessenich49987892015-12-29 17:11:44 -07001802// 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 -07001803// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001804int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001805{
John Kessenich49987892015-12-29 17:11:44 -07001806 glslang::TType elementType;
1807 elementType.shallowCopy(matrixType);
1808 elementType.clearArraySizes();
1809
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001810 int size;
John Kessenich49987892015-12-29 17:11:44 -07001811 int stride;
1812 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1813
1814 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001815}
1816
John Kessenich5e4b1242015-08-06 22:53:06 -06001817// Given a member type of a struct, realign the current offset for it, and compute
1818// the next (not yet aligned) offset for the next member, which will get aligned
1819// on the next call.
1820// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1821// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1822// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001823void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001824 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001825{
1826 // this will get a positive value when deemed necessary
1827 nextOffset = -1;
1828
John Kessenich5e4b1242015-08-06 22:53:06 -06001829 // override anything in currentOffset with user-set offset
1830 if (memberType.getQualifier().hasOffset())
1831 currentOffset = memberType.getQualifier().layoutOffset;
1832
1833 // It could be that current linker usage in glslang updated all the layoutOffset,
1834 // in which case the following code does not matter. But, that's not quite right
1835 // once cross-compilation unit GLSL validation is done, as the original user
1836 // settings are needed in layoutOffset, and then the following will come into play.
1837
John Kessenichf85e8062015-12-19 13:57:10 -07001838 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001839 if (! memberType.getQualifier().hasOffset())
1840 currentOffset = -1;
1841
1842 return;
1843 }
1844
John Kessenichf85e8062015-12-19 13:57:10 -07001845 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001846 if (currentOffset < 0)
1847 currentOffset = 0;
1848
1849 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1850 // but possibly not yet correctly aligned.
1851
1852 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001853 int dummyStride;
1854 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001855 glslang::RoundToPow2(currentOffset, memberAlignment);
1856 nextOffset = currentOffset + memberSize;
1857}
1858
John Kessenich140f3df2015-06-26 16:58:36 -06001859bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1860{
1861 return node->getName() == "main(";
1862}
1863
1864// Make all the functions, skeletally, without actually visiting their bodies.
1865void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1866{
1867 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1868 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1869 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1870 continue;
1871
1872 // We're on a user function. Set up the basic interface for the function now,
1873 // so that it's available to call.
1874 // Translating the body will happen later.
1875 //
1876 // Typically (except for a "const in" parameter), an address will be passed to the
1877 // function. What it is an address of varies:
1878 //
1879 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1880 // so that write needs to be to a copy, hence the address of a copy works.
1881 //
1882 // - "const in" parameters can just be the r-value, as no writes need occur.
1883 //
1884 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1885 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1886
1887 std::vector<spv::Id> paramTypes;
1888 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1889
1890 for (int p = 0; p < (int)parameters.size(); ++p) {
1891 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1892 spv::Id typeId = convertGlslangToSpvType(paramType);
1893 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1894 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1895 else
1896 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
1897 paramTypes.push_back(typeId);
1898 }
1899
1900 spv::Block* functionBlock;
1901 spv::Function *function = builder.makeFunctionEntry(convertGlslangToSpvType(glslFunction->getType()), glslFunction->getName().c_str(),
1902 paramTypes, &functionBlock);
1903
1904 // Track function to emit/call later
1905 functionMap[glslFunction->getName().c_str()] = function;
1906
1907 // Set the parameter id's
1908 for (int p = 0; p < (int)parameters.size(); ++p) {
1909 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1910 // give a name too
1911 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1912 }
1913 }
1914}
1915
1916// Process all the initializers, while skipping the functions and link objects
1917void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1918{
1919 builder.setBuildPoint(shaderEntry->getLastBlock());
1920 for (int i = 0; i < (int)initializers.size(); ++i) {
1921 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1922 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1923
1924 // We're on a top-level node that's not a function. Treat as an initializer, whose
1925 // code goes into the beginning of main.
1926 initializer->traverse(this);
1927 }
1928 }
1929}
1930
1931// Process all the functions, while skipping initializers.
1932void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1933{
1934 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1935 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1936 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1937 node->traverse(this);
1938 }
1939}
1940
1941void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1942{
1943 // SPIR-V functions should already be in the functionMap from the prepass
1944 // that called makeFunctions().
1945 spv::Function* function = functionMap[node->getName().c_str()];
1946 spv::Block* functionBlock = function->getEntryBlock();
1947 builder.setBuildPoint(functionBlock);
1948}
1949
Rex Xu04db3f52015-09-16 11:44:02 +08001950void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001951{
Rex Xufc618912015-09-09 16:42:49 +08001952 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08001953
1954 glslang::TSampler sampler = {};
1955 bool cubeCompare = false;
1956 if (node.isTexture()) {
1957 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
1958 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1959 }
1960
John Kessenich140f3df2015-06-26 16:58:36 -06001961 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1962 builder.clearAccessChain();
1963 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001964
1965 // Special case l-value operands
1966 bool lvalue = false;
1967 switch (node.getOp()) {
1968 case glslang::EOpImageAtomicAdd:
1969 case glslang::EOpImageAtomicMin:
1970 case glslang::EOpImageAtomicMax:
1971 case glslang::EOpImageAtomicAnd:
1972 case glslang::EOpImageAtomicOr:
1973 case glslang::EOpImageAtomicXor:
1974 case glslang::EOpImageAtomicExchange:
1975 case glslang::EOpImageAtomicCompSwap:
1976 if (i == 0)
1977 lvalue = true;
1978 break;
Rex Xu48edadf2015-12-31 16:11:41 +08001979 case glslang::EOpSparseTexture:
1980 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
1981 lvalue = true;
1982 break;
1983 case glslang::EOpSparseTextureClamp:
1984 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
1985 lvalue = true;
1986 break;
1987 case glslang::EOpSparseTextureLod:
1988 case glslang::EOpSparseTextureOffset:
1989 if (i == 3)
1990 lvalue = true;
1991 break;
1992 case glslang::EOpSparseTextureFetch:
1993 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
1994 lvalue = true;
1995 break;
1996 case glslang::EOpSparseTextureFetchOffset:
1997 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
1998 lvalue = true;
1999 break;
2000 case glslang::EOpSparseTextureLodOffset:
2001 case glslang::EOpSparseTextureGrad:
2002 case glslang::EOpSparseTextureOffsetClamp:
2003 if (i == 4)
2004 lvalue = true;
2005 break;
2006 case glslang::EOpSparseTextureGradOffset:
2007 case glslang::EOpSparseTextureGradClamp:
2008 if (i == 5)
2009 lvalue = true;
2010 break;
2011 case glslang::EOpSparseTextureGradOffsetClamp:
2012 if (i == 6)
2013 lvalue = true;
2014 break;
2015 case glslang::EOpSparseTextureGather:
2016 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2017 lvalue = true;
2018 break;
2019 case glslang::EOpSparseTextureGatherOffset:
2020 case glslang::EOpSparseTextureGatherOffsets:
2021 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2022 lvalue = true;
2023 break;
Rex Xufc618912015-09-09 16:42:49 +08002024 default:
2025 break;
2026 }
2027
Rex Xu6b86d492015-09-16 17:48:22 +08002028 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002029 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002030 else
Rex Xu30f92582015-09-14 10:38:56 +08002031 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(glslangArguments[i]->getAsTyped()->getType())));
John Kessenich140f3df2015-06-26 16:58:36 -06002032 }
2033}
2034
John Kessenichfc51d282015-08-19 13:34:18 -06002035void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002036{
John Kessenichfc51d282015-08-19 13:34:18 -06002037 builder.clearAccessChain();
2038 node.getOperand()->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002039 arguments.push_back(builder.accessChainLoad(convertGlslangToSpvType(node.getOperand()->getType())));
John Kessenichfc51d282015-08-19 13:34:18 -06002040}
John Kessenich140f3df2015-06-26 16:58:36 -06002041
John Kessenichfc51d282015-08-19 13:34:18 -06002042spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2043{
Rex Xufc618912015-09-09 16:42:49 +08002044 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002045 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002046 }
2047
John Kessenichfc51d282015-08-19 13:34:18 -06002048 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002049 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2050 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2051 std::vector<spv::Id> arguments;
2052 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002053 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002054 else
2055 translateArguments(*node->getAsUnaryNode(), arguments);
2056 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2057
2058 spv::Builder::TextureParameters params = { };
2059 params.sampler = arguments[0];
2060
Rex Xu04db3f52015-09-16 11:44:02 +08002061 glslang::TCrackedTextureOp cracked;
2062 node->crackTexture(sampler, cracked);
2063
John Kessenichfc51d282015-08-19 13:34:18 -06002064 // Check for queries
2065 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002066 // a sampled image needs to have the image extracted first
2067 if (builder.isSampledImage(params.sampler))
2068 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002069 switch (node->getOp()) {
2070 case glslang::EOpImageQuerySize:
2071 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002072 if (arguments.size() > 1) {
2073 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002074 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002075 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002076 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002077 case glslang::EOpImageQuerySamples:
2078 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002079 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002080 case glslang::EOpTextureQueryLod:
2081 params.coords = arguments[1];
2082 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2083 case glslang::EOpTextureQueryLevels:
2084 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002085 case glslang::EOpSparseTexelsResident:
2086 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002087 default:
2088 assert(0);
2089 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002090 }
John Kessenich140f3df2015-06-26 16:58:36 -06002091 }
2092
Rex Xufc618912015-09-09 16:42:49 +08002093 // Check for image functions other than queries
2094 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002095 std::vector<spv::Id> operands;
2096 auto opIt = arguments.begin();
2097 operands.push_back(*(opIt++));
2098 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002099 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002100 if (sampler.ms) {
2101 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002102 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002103 }
John Kessenich56bab042015-09-16 10:54:31 -06002104 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2105 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002106 if (sampler.ms) {
2107 operands.push_back(*(opIt + 1));
2108 operands.push_back(spv::ImageOperandsSampleMask);
2109 operands.push_back(*opIt);
2110 } else
2111 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002112 builder.createNoResultOp(spv::OpImageWrite, operands);
2113 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002114 } else if (node->isSparseImage()) {
2115 spv::MissingFunctionality("sparse image functions");
2116 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002117 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002118 // Process image atomic operations
2119
2120 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2121 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002122 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002123
Rex Xufc618912015-09-09 16:42:49 +08002124 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002125 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002126
2127 std::vector<spv::Id> operands;
2128 operands.push_back(pointer);
2129 for (; opIt != arguments.end(); ++opIt)
2130 operands.push_back(*opIt);
2131
Rex Xu04db3f52015-09-16 11:44:02 +08002132 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002133 }
2134 }
2135
2136 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002137 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002138 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2139
John Kessenichfc51d282015-08-19 13:34:18 -06002140 // check for bias argument
2141 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002142 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002143 int nonBiasArgCount = 2;
2144 if (cracked.offset)
2145 ++nonBiasArgCount;
2146 if (cracked.grad)
2147 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002148 if (cracked.lodClamp)
2149 ++nonBiasArgCount;
2150 if (sparse)
2151 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002152
2153 if ((int)arguments.size() > nonBiasArgCount)
2154 bias = true;
2155 }
2156
John Kessenichfc51d282015-08-19 13:34:18 -06002157 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002158
John Kessenichfc51d282015-08-19 13:34:18 -06002159 params.coords = arguments[1];
2160 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002161
2162 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002163 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002164 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002165 ++extraArgs;
2166 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002167 params.Dref = arguments[2];
2168 ++extraArgs;
2169 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002170 std::vector<spv::Id> indexes;
2171 int comp;
2172 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002173 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002174 else
2175 comp = builder.getNumComponents(params.coords) - 1;
2176 indexes.push_back(comp);
2177 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2178 }
2179 if (cracked.lod) {
2180 params.lod = arguments[2];
2181 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002182 } else if (sampler.ms) {
2183 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002184 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002185 }
2186 if (cracked.grad) {
2187 params.gradX = arguments[2 + extraArgs];
2188 params.gradY = arguments[3 + extraArgs];
2189 extraArgs += 2;
2190 }
John Kessenich55e7d112015-11-15 21:33:39 -07002191 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002192 params.offset = arguments[2 + extraArgs];
2193 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002194 } else if (cracked.offsets) {
2195 params.offsets = arguments[2 + extraArgs];
2196 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002197 }
Rex Xu48edadf2015-12-31 16:11:41 +08002198 if (cracked.lodClamp) {
2199 params.lodClamp = arguments[2 + extraArgs];
2200 ++extraArgs;
2201 }
2202 if (sparse) {
2203 params.texelOut = arguments[2 + extraArgs];
2204 ++extraArgs;
2205 }
John Kessenichfc51d282015-08-19 13:34:18 -06002206 if (bias) {
2207 params.bias = arguments[2 + extraArgs];
2208 ++extraArgs;
2209 }
John Kessenich55e7d112015-11-15 21:33:39 -07002210 if (cracked.gather && ! sampler.shadow) {
2211 // default component is 0, if missing, otherwise an argument
2212 if (2 + extraArgs < (int)arguments.size()) {
2213 params.comp = arguments[2 + extraArgs];
2214 ++extraArgs;
2215 } else {
2216 params.comp = builder.makeIntConstant(0);
2217 }
2218 }
John Kessenichfc51d282015-08-19 13:34:18 -06002219
Rex Xu48edadf2015-12-31 16:11:41 +08002220 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002221}
2222
2223spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2224{
2225 // Grab the function's pointer from the previously created function
2226 spv::Function* function = functionMap[node->getName().c_str()];
2227 if (! function)
2228 return 0;
2229
2230 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2231 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2232
2233 // See comments in makeFunctions() for details about the semantics for parameter passing.
2234 //
2235 // These imply we need a four step process:
2236 // 1. Evaluate the arguments
2237 // 2. Allocate and make copies of in, out, and inout arguments
2238 // 3. Make the call
2239 // 4. Copy back the results
2240
2241 // 1. Evaluate the arguments
2242 std::vector<spv::Builder::AccessChain> lValues;
2243 std::vector<spv::Id> rValues;
John Kessenichfa668da2015-09-13 14:46:30 -06002244 std::vector<spv::Id> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002245 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2246 // build l-value
2247 builder.clearAccessChain();
2248 glslangArgs[a]->traverse(this);
John Kessenichfa668da2015-09-13 14:46:30 -06002249 argTypes.push_back(convertGlslangToSpvType(glslangArgs[a]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002250 // keep outputs as l-values, evaluate input-only as r-values
2251 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2252 // save l-value
2253 lValues.push_back(builder.getAccessChain());
2254 } else {
2255 // process r-value
John Kessenichfa668da2015-09-13 14:46:30 -06002256 rValues.push_back(builder.accessChainLoad(argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002257 }
2258 }
2259
2260 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2261 // copy the original into that space.
2262 //
2263 // Also, build up the list of actual arguments to pass in for the call
2264 int lValueCount = 0;
2265 int rValueCount = 0;
2266 std::vector<spv::Id> spvArgs;
2267 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2268 spv::Id arg;
2269 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2270 // need space to hold the copy
2271 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2272 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2273 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2274 // need to copy the input into output space
2275 builder.setAccessChain(lValues[lValueCount]);
John Kessenichfa668da2015-09-13 14:46:30 -06002276 spv::Id copy = builder.accessChainLoad(argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002277 builder.createStore(copy, arg);
2278 }
2279 ++lValueCount;
2280 } else {
2281 arg = rValues[rValueCount];
2282 ++rValueCount;
2283 }
2284 spvArgs.push_back(arg);
2285 }
2286
2287 // 3. Make the call.
2288 spv::Id result = builder.createFunctionCall(function, spvArgs);
2289
2290 // 4. Copy back out an "out" arguments.
2291 lValueCount = 0;
2292 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2293 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2294 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2295 spv::Id copy = builder.createLoad(spvArgs[a]);
2296 builder.setAccessChain(lValues[lValueCount]);
2297 builder.accessChainStore(copy);
2298 }
2299 ++lValueCount;
2300 }
2301 }
2302
2303 return result;
2304}
2305
2306// Translate AST operation to SPV operation, already having SPV-based operands/types.
2307spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2308 spv::Id typeId, spv::Id left, spv::Id right,
2309 glslang::TBasicType typeProxy, bool reduceComparison)
2310{
2311 bool isUnsigned = typeProxy == glslang::EbtUint;
2312 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2313
2314 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002315 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002316 bool comparison = false;
2317
2318 switch (op) {
2319 case glslang::EOpAdd:
2320 case glslang::EOpAddAssign:
2321 if (isFloat)
2322 binOp = spv::OpFAdd;
2323 else
2324 binOp = spv::OpIAdd;
2325 break;
2326 case glslang::EOpSub:
2327 case glslang::EOpSubAssign:
2328 if (isFloat)
2329 binOp = spv::OpFSub;
2330 else
2331 binOp = spv::OpISub;
2332 break;
2333 case glslang::EOpMul:
2334 case glslang::EOpMulAssign:
2335 if (isFloat)
2336 binOp = spv::OpFMul;
2337 else
2338 binOp = spv::OpIMul;
2339 break;
2340 case glslang::EOpVectorTimesScalar:
2341 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002342 if (isFloat) {
2343 if (builder.isVector(right))
2344 std::swap(left, right);
2345 assert(builder.isScalar(right));
2346 needMatchingVectors = false;
2347 binOp = spv::OpVectorTimesScalar;
2348 } else
2349 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002350 break;
2351 case glslang::EOpVectorTimesMatrix:
2352 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002353 binOp = spv::OpVectorTimesMatrix;
2354 break;
2355 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002356 binOp = spv::OpMatrixTimesVector;
2357 break;
2358 case glslang::EOpMatrixTimesScalar:
2359 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002360 binOp = spv::OpMatrixTimesScalar;
2361 break;
2362 case glslang::EOpMatrixTimesMatrix:
2363 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002364 binOp = spv::OpMatrixTimesMatrix;
2365 break;
2366 case glslang::EOpOuterProduct:
2367 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002368 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002369 break;
2370
2371 case glslang::EOpDiv:
2372 case glslang::EOpDivAssign:
2373 if (isFloat)
2374 binOp = spv::OpFDiv;
2375 else if (isUnsigned)
2376 binOp = spv::OpUDiv;
2377 else
2378 binOp = spv::OpSDiv;
2379 break;
2380 case glslang::EOpMod:
2381 case glslang::EOpModAssign:
2382 if (isFloat)
2383 binOp = spv::OpFMod;
2384 else if (isUnsigned)
2385 binOp = spv::OpUMod;
2386 else
2387 binOp = spv::OpSMod;
2388 break;
2389 case glslang::EOpRightShift:
2390 case glslang::EOpRightShiftAssign:
2391 if (isUnsigned)
2392 binOp = spv::OpShiftRightLogical;
2393 else
2394 binOp = spv::OpShiftRightArithmetic;
2395 break;
2396 case glslang::EOpLeftShift:
2397 case glslang::EOpLeftShiftAssign:
2398 binOp = spv::OpShiftLeftLogical;
2399 break;
2400 case glslang::EOpAnd:
2401 case glslang::EOpAndAssign:
2402 binOp = spv::OpBitwiseAnd;
2403 break;
2404 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002405 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002406 binOp = spv::OpLogicalAnd;
2407 break;
2408 case glslang::EOpInclusiveOr:
2409 case glslang::EOpInclusiveOrAssign:
2410 binOp = spv::OpBitwiseOr;
2411 break;
2412 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002413 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002414 binOp = spv::OpLogicalOr;
2415 break;
2416 case glslang::EOpExclusiveOr:
2417 case glslang::EOpExclusiveOrAssign:
2418 binOp = spv::OpBitwiseXor;
2419 break;
2420 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002421 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002422 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002423 break;
2424
2425 case glslang::EOpLessThan:
2426 case glslang::EOpGreaterThan:
2427 case glslang::EOpLessThanEqual:
2428 case glslang::EOpGreaterThanEqual:
2429 case glslang::EOpEqual:
2430 case glslang::EOpNotEqual:
2431 case glslang::EOpVectorEqual:
2432 case glslang::EOpVectorNotEqual:
2433 comparison = true;
2434 break;
2435 default:
2436 break;
2437 }
2438
John Kessenich7c1aa102015-10-15 13:29:11 -06002439 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002440 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002441 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002442 if (builder.isMatrix(left) || builder.isMatrix(right))
2443 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002444
2445 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002446 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002447 builder.promoteScalar(precision, left, right);
2448
2449 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2450 builder.setPrecision(id, precision);
2451
2452 return id;
2453 }
2454
2455 if (! comparison)
2456 return 0;
2457
John Kessenich7c1aa102015-10-15 13:29:11 -06002458 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002459
2460 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2461 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2462
John Kessenich22118352015-12-21 20:54:09 -07002463 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002464 }
2465
2466 switch (op) {
2467 case glslang::EOpLessThan:
2468 if (isFloat)
2469 binOp = spv::OpFOrdLessThan;
2470 else if (isUnsigned)
2471 binOp = spv::OpULessThan;
2472 else
2473 binOp = spv::OpSLessThan;
2474 break;
2475 case glslang::EOpGreaterThan:
2476 if (isFloat)
2477 binOp = spv::OpFOrdGreaterThan;
2478 else if (isUnsigned)
2479 binOp = spv::OpUGreaterThan;
2480 else
2481 binOp = spv::OpSGreaterThan;
2482 break;
2483 case glslang::EOpLessThanEqual:
2484 if (isFloat)
2485 binOp = spv::OpFOrdLessThanEqual;
2486 else if (isUnsigned)
2487 binOp = spv::OpULessThanEqual;
2488 else
2489 binOp = spv::OpSLessThanEqual;
2490 break;
2491 case glslang::EOpGreaterThanEqual:
2492 if (isFloat)
2493 binOp = spv::OpFOrdGreaterThanEqual;
2494 else if (isUnsigned)
2495 binOp = spv::OpUGreaterThanEqual;
2496 else
2497 binOp = spv::OpSGreaterThanEqual;
2498 break;
2499 case glslang::EOpEqual:
2500 case glslang::EOpVectorEqual:
2501 if (isFloat)
2502 binOp = spv::OpFOrdEqual;
2503 else
2504 binOp = spv::OpIEqual;
2505 break;
2506 case glslang::EOpNotEqual:
2507 case glslang::EOpVectorNotEqual:
2508 if (isFloat)
2509 binOp = spv::OpFOrdNotEqual;
2510 else
2511 binOp = spv::OpINotEqual;
2512 break;
2513 default:
2514 break;
2515 }
2516
2517 if (binOp != spv::OpNop) {
2518 spv::Id id = builder.createBinOp(binOp, typeId, left, right);
2519 builder.setPrecision(id, precision);
2520
2521 return id;
2522 }
2523
2524 return 0;
2525}
2526
John Kessenich04bb8a02015-12-12 12:28:14 -07002527//
2528// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2529// These can be any of:
2530//
2531// matrix * scalar
2532// scalar * matrix
2533// matrix * matrix linear algebraic
2534// matrix * vector
2535// vector * matrix
2536// matrix * matrix componentwise
2537// matrix op matrix op in {+, -, /}
2538// matrix op scalar op in {+, -, /}
2539// scalar op matrix op in {+, -, /}
2540//
2541spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2542{
2543 bool firstClass = true;
2544
2545 // First, handle first-class matrix operations (* and matrix/scalar)
2546 switch (op) {
2547 case spv::OpFDiv:
2548 if (builder.isMatrix(left) && builder.isScalar(right)) {
2549 // turn matrix / scalar into a multiply...
2550 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2551 op = spv::OpMatrixTimesScalar;
2552 } else
2553 firstClass = false;
2554 break;
2555 case spv::OpMatrixTimesScalar:
2556 if (builder.isMatrix(right))
2557 std::swap(left, right);
2558 assert(builder.isScalar(right));
2559 break;
2560 case spv::OpVectorTimesMatrix:
2561 assert(builder.isVector(left));
2562 assert(builder.isMatrix(right));
2563 break;
2564 case spv::OpMatrixTimesVector:
2565 assert(builder.isMatrix(left));
2566 assert(builder.isVector(right));
2567 break;
2568 case spv::OpMatrixTimesMatrix:
2569 assert(builder.isMatrix(left));
2570 assert(builder.isMatrix(right));
2571 break;
2572 default:
2573 firstClass = false;
2574 break;
2575 }
2576
2577 if (firstClass) {
2578 spv::Id id = builder.createBinOp(op, typeId, left, right);
2579 builder.setPrecision(id, precision);
2580
2581 return id;
2582 }
2583
2584 // Handle component-wise +, -, *, and / for all combinations of type.
2585 // The result type of all of them is the same type as the (a) matrix operand.
2586 // The algorithm is to:
2587 // - break the matrix(es) into vectors
2588 // - smear any scalar to a vector
2589 // - do vector operations
2590 // - make a matrix out the vector results
2591 switch (op) {
2592 case spv::OpFAdd:
2593 case spv::OpFSub:
2594 case spv::OpFDiv:
2595 case spv::OpFMul:
2596 {
2597 // one time set up...
2598 bool leftMat = builder.isMatrix(left);
2599 bool rightMat = builder.isMatrix(right);
2600 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2601 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2602 spv::Id scalarType = builder.getScalarTypeId(typeId);
2603 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2604 std::vector<spv::Id> results;
2605 spv::Id smearVec = spv::NoResult;
2606 if (builder.isScalar(left))
2607 smearVec = builder.smearScalar(precision, left, vecType);
2608 else if (builder.isScalar(right))
2609 smearVec = builder.smearScalar(precision, right, vecType);
2610
2611 // do each vector op
2612 for (unsigned int c = 0; c < numCols; ++c) {
2613 std::vector<unsigned int> indexes;
2614 indexes.push_back(c);
2615 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2616 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2617 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2618 builder.setPrecision(results.back(), precision);
2619 }
2620
2621 // put the pieces together
2622 spv::Id id = builder.createCompositeConstruct(typeId, results);
2623 builder.setPrecision(id, precision);
2624 return id;
2625 }
2626 default:
2627 assert(0);
2628 return spv::NoResult;
2629 }
2630}
2631
Rex Xu04db3f52015-09-16 11:44:02 +08002632spv::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 -06002633{
2634 spv::Op unaryOp = spv::OpNop;
2635 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002636 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002637 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002638
2639 switch (op) {
2640 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002641 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002642 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002643 if (builder.isMatrixType(typeId))
2644 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2645 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002646 unaryOp = spv::OpSNegate;
2647 break;
2648
2649 case glslang::EOpLogicalNot:
2650 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002651 unaryOp = spv::OpLogicalNot;
2652 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002653 case glslang::EOpBitwiseNot:
2654 unaryOp = spv::OpNot;
2655 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002656
John Kessenich140f3df2015-06-26 16:58:36 -06002657 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002658 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002659 break;
2660 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002661 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002662 break;
2663 case glslang::EOpTranspose:
2664 unaryOp = spv::OpTranspose;
2665 break;
2666
2667 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002668 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002669 break;
2670 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002671 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002672 break;
2673 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002674 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002675 break;
2676 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002677 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002678 break;
2679 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002680 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002681 break;
2682 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002683 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002684 break;
2685 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002686 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002687 break;
2688 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002689 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002690 break;
2691
2692 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002693 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002694 break;
2695 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002696 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002697 break;
2698 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002699 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002700 break;
2701 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002702 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002703 break;
2704 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002705 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002706 break;
2707 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002709 break;
2710
2711 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002712 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002713 break;
2714 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002715 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002716 break;
2717
2718 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002719 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002720 break;
2721 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002722 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002723 break;
2724 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002725 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002726 break;
2727 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002728 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002729 break;
2730 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002731 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002732 break;
2733 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002734 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002735 break;
2736
2737 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002738 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002739 break;
2740 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002741 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002742 break;
2743 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002744 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002745 break;
2746 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002747 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002748 break;
2749 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002750 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002751 break;
2752 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002753 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002754 break;
2755
2756 case glslang::EOpIsNan:
2757 unaryOp = spv::OpIsNan;
2758 break;
2759 case glslang::EOpIsInf:
2760 unaryOp = spv::OpIsInf;
2761 break;
2762
Rex Xucbc426e2015-12-15 16:03:10 +08002763 case glslang::EOpFloatBitsToInt:
2764 case glslang::EOpFloatBitsToUint:
2765 case glslang::EOpIntBitsToFloat:
2766 case glslang::EOpUintBitsToFloat:
2767 unaryOp = spv::OpBitcast;
2768 break;
2769
John Kessenich140f3df2015-06-26 16:58:36 -06002770 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002771 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002772 break;
2773 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002774 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002775 break;
2776 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002777 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002778 break;
2779 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002780 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002781 break;
2782 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002783 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002784 break;
2785 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002786 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002787 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002788 case glslang::EOpPackSnorm4x8:
2789 libCall = spv::GLSLstd450PackSnorm4x8;
2790 break;
2791 case glslang::EOpUnpackSnorm4x8:
2792 libCall = spv::GLSLstd450UnpackSnorm4x8;
2793 break;
2794 case glslang::EOpPackUnorm4x8:
2795 libCall = spv::GLSLstd450PackUnorm4x8;
2796 break;
2797 case glslang::EOpUnpackUnorm4x8:
2798 libCall = spv::GLSLstd450UnpackUnorm4x8;
2799 break;
2800 case glslang::EOpPackDouble2x32:
2801 libCall = spv::GLSLstd450PackDouble2x32;
2802 break;
2803 case glslang::EOpUnpackDouble2x32:
2804 libCall = spv::GLSLstd450UnpackDouble2x32;
2805 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002806
2807 case glslang::EOpDPdx:
2808 unaryOp = spv::OpDPdx;
2809 break;
2810 case glslang::EOpDPdy:
2811 unaryOp = spv::OpDPdy;
2812 break;
2813 case glslang::EOpFwidth:
2814 unaryOp = spv::OpFwidth;
2815 break;
2816 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07002817 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002818 unaryOp = spv::OpDPdxFine;
2819 break;
2820 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07002821 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002822 unaryOp = spv::OpDPdyFine;
2823 break;
2824 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07002825 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002826 unaryOp = spv::OpFwidthFine;
2827 break;
2828 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002829 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002830 unaryOp = spv::OpDPdxCoarse;
2831 break;
2832 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002833 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002834 unaryOp = spv::OpDPdyCoarse;
2835 break;
2836 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002837 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002838 unaryOp = spv::OpFwidthCoarse;
2839 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002840 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07002841 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08002842 libCall = spv::GLSLstd450InterpolateAtCentroid;
2843 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002844 case glslang::EOpAny:
2845 unaryOp = spv::OpAny;
2846 break;
2847 case glslang::EOpAll:
2848 unaryOp = spv::OpAll;
2849 break;
2850
2851 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002852 if (isFloat)
2853 libCall = spv::GLSLstd450FAbs;
2854 else
2855 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002856 break;
2857 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002858 if (isFloat)
2859 libCall = spv::GLSLstd450FSign;
2860 else
2861 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002862 break;
2863
John Kessenichfc51d282015-08-19 13:34:18 -06002864 case glslang::EOpAtomicCounterIncrement:
2865 case glslang::EOpAtomicCounterDecrement:
2866 case glslang::EOpAtomicCounter:
2867 {
2868 // Handle all of the atomics in one place, in createAtomicOperation()
2869 std::vector<spv::Id> operands;
2870 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002871 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002872 }
2873
2874 case glslang::EOpImageLoad:
2875 unaryOp = spv::OpImageRead;
2876 break;
2877
2878 case glslang::EOpBitFieldReverse:
2879 unaryOp = spv::OpBitReverse;
2880 break;
2881 case glslang::EOpBitCount:
2882 unaryOp = spv::OpBitCount;
2883 break;
2884 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002885 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002886 break;
2887 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002888 if (isUnsigned)
2889 libCall = spv::GLSLstd450FindUMsb;
2890 else
2891 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002892 break;
2893
John Kessenich140f3df2015-06-26 16:58:36 -06002894 default:
2895 return 0;
2896 }
2897
2898 spv::Id id;
2899 if (libCall >= 0) {
2900 std::vector<spv::Id> args;
2901 args.push_back(operand);
2902 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, args);
2903 } else
2904 id = builder.createUnaryOp(unaryOp, typeId, operand);
2905
2906 builder.setPrecision(id, precision);
2907
2908 return id;
2909}
2910
John Kessenich7a53f762016-01-20 11:19:27 -07002911// Create a unary operation on a matrix
2912spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
2913{
2914 // Handle unary operations vector by vector.
2915 // The result type is the same type as the original type.
2916 // The algorithm is to:
2917 // - break the matrix into vectors
2918 // - apply the operation to each vector
2919 // - make a matrix out the vector results
2920
2921 // get the types sorted out
2922 int numCols = builder.getNumColumns(operand);
2923 int numRows = builder.getNumRows(operand);
2924 spv::Id scalarType = builder.getScalarTypeId(typeId);
2925 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2926 std::vector<spv::Id> results;
2927
2928 // do each vector op
2929 for (int c = 0; c < numCols; ++c) {
2930 std::vector<unsigned int> indexes;
2931 indexes.push_back(c);
2932 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
2933 results.push_back(builder.createUnaryOp(op, vecType, vec));
2934 builder.setPrecision(results.back(), precision);
2935 }
2936
2937 // put the pieces together
2938 spv::Id id = builder.createCompositeConstruct(typeId, results);
2939 builder.setPrecision(id, precision);
2940
2941 return id;
2942}
2943
John Kessenich140f3df2015-06-26 16:58:36 -06002944spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2945{
2946 spv::Op convOp = spv::OpNop;
2947 spv::Id zero = 0;
2948 spv::Id one = 0;
2949
2950 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2951
2952 switch (op) {
2953 case glslang::EOpConvIntToBool:
2954 case glslang::EOpConvUintToBool:
2955 zero = builder.makeUintConstant(0);
2956 zero = makeSmearedConstant(zero, vectorSize);
2957 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2958
2959 case glslang::EOpConvFloatToBool:
2960 zero = builder.makeFloatConstant(0.0F);
2961 zero = makeSmearedConstant(zero, vectorSize);
2962 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2963
2964 case glslang::EOpConvDoubleToBool:
2965 zero = builder.makeDoubleConstant(0.0);
2966 zero = makeSmearedConstant(zero, vectorSize);
2967 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2968
2969 case glslang::EOpConvBoolToFloat:
2970 convOp = spv::OpSelect;
2971 zero = builder.makeFloatConstant(0.0);
2972 one = builder.makeFloatConstant(1.0);
2973 break;
2974 case glslang::EOpConvBoolToDouble:
2975 convOp = spv::OpSelect;
2976 zero = builder.makeDoubleConstant(0.0);
2977 one = builder.makeDoubleConstant(1.0);
2978 break;
2979 case glslang::EOpConvBoolToInt:
2980 zero = builder.makeIntConstant(0);
2981 one = builder.makeIntConstant(1);
2982 convOp = spv::OpSelect;
2983 break;
2984 case glslang::EOpConvBoolToUint:
2985 zero = builder.makeUintConstant(0);
2986 one = builder.makeUintConstant(1);
2987 convOp = spv::OpSelect;
2988 break;
2989
2990 case glslang::EOpConvIntToFloat:
2991 case glslang::EOpConvIntToDouble:
2992 convOp = spv::OpConvertSToF;
2993 break;
2994
2995 case glslang::EOpConvUintToFloat:
2996 case glslang::EOpConvUintToDouble:
2997 convOp = spv::OpConvertUToF;
2998 break;
2999
3000 case glslang::EOpConvDoubleToFloat:
3001 case glslang::EOpConvFloatToDouble:
3002 convOp = spv::OpFConvert;
3003 break;
3004
3005 case glslang::EOpConvFloatToInt:
3006 case glslang::EOpConvDoubleToInt:
3007 convOp = spv::OpConvertFToS;
3008 break;
3009
3010 case glslang::EOpConvUintToInt:
3011 case glslang::EOpConvIntToUint:
3012 convOp = spv::OpBitcast;
3013 break;
3014
3015 case glslang::EOpConvFloatToUint:
3016 case glslang::EOpConvDoubleToUint:
3017 convOp = spv::OpConvertFToU;
3018 break;
3019 default:
3020 break;
3021 }
3022
3023 spv::Id result = 0;
3024 if (convOp == spv::OpNop)
3025 return result;
3026
3027 if (convOp == spv::OpSelect) {
3028 zero = makeSmearedConstant(zero, vectorSize);
3029 one = makeSmearedConstant(one, vectorSize);
3030 result = builder.createTriOp(convOp, destType, operand, one, zero);
3031 } else
3032 result = builder.createUnaryOp(convOp, destType, operand);
3033
3034 builder.setPrecision(result, precision);
3035
3036 return result;
3037}
3038
3039spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3040{
3041 if (vectorSize == 0)
3042 return constant;
3043
3044 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3045 std::vector<spv::Id> components;
3046 for (int c = 0; c < vectorSize; ++c)
3047 components.push_back(constant);
3048 return builder.makeCompositeConstant(vectorTypeId, components);
3049}
3050
John Kessenich426394d2015-07-23 10:22:48 -06003051// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08003052spv::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 -06003053{
3054 spv::Op opCode = spv::OpNop;
3055
3056 switch (op) {
3057 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003058 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003059 opCode = spv::OpAtomicIAdd;
3060 break;
3061 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003062 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003063 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003064 break;
3065 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003066 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003067 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003068 break;
3069 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003070 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003071 opCode = spv::OpAtomicAnd;
3072 break;
3073 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003074 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003075 opCode = spv::OpAtomicOr;
3076 break;
3077 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003078 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003079 opCode = spv::OpAtomicXor;
3080 break;
3081 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003082 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003083 opCode = spv::OpAtomicExchange;
3084 break;
3085 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003086 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003087 opCode = spv::OpAtomicCompareExchange;
3088 break;
3089 case glslang::EOpAtomicCounterIncrement:
3090 opCode = spv::OpAtomicIIncrement;
3091 break;
3092 case glslang::EOpAtomicCounterDecrement:
3093 opCode = spv::OpAtomicIDecrement;
3094 break;
3095 case glslang::EOpAtomicCounter:
3096 opCode = spv::OpAtomicLoad;
3097 break;
3098 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003099 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003100 break;
3101 }
3102
3103 // Sort out the operands
3104 // - mapping from glslang -> SPV
3105 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003106 // - compare-exchange swaps the value and comparator
3107 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003108 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3109 auto opIt = operands.begin(); // walk the glslang operands
3110 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003111 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3112 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3113 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003114 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3115 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003116 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003117 spvAtomicOperands.push_back(*(opIt + 1));
3118 spvAtomicOperands.push_back(*opIt);
3119 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003120 }
John Kessenich426394d2015-07-23 10:22:48 -06003121
John Kessenich3e60a6f2015-09-14 22:45:16 -06003122 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003123 for (; opIt != operands.end(); ++opIt)
3124 spvAtomicOperands.push_back(*opIt);
3125
3126 return builder.createOp(opCode, typeId, spvAtomicOperands);
3127}
3128
John Kessenich5e4b1242015-08-06 22:53:06 -06003129spv::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 -06003130{
John Kessenich5e4b1242015-08-06 22:53:06 -06003131 bool isUnsigned = typeProxy == glslang::EbtUint;
3132 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3133
John Kessenich140f3df2015-06-26 16:58:36 -06003134 spv::Op opCode = spv::OpNop;
3135 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003136 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003137 spv::Id typeId0 = 0;
3138 if (consumedOperands > 0)
3139 typeId0 = builder.getTypeId(operands[0]);
3140 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003141
3142 switch (op) {
3143 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003144 if (isFloat)
3145 libCall = spv::GLSLstd450FMin;
3146 else if (isUnsigned)
3147 libCall = spv::GLSLstd450UMin;
3148 else
3149 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003150 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003151 break;
3152 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003153 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003154 break;
3155 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003156 if (isFloat)
3157 libCall = spv::GLSLstd450FMax;
3158 else if (isUnsigned)
3159 libCall = spv::GLSLstd450UMax;
3160 else
3161 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003162 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003163 break;
3164 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003165 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003166 break;
3167 case glslang::EOpDot:
3168 opCode = spv::OpDot;
3169 break;
3170 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003171 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003172 break;
3173
3174 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003175 if (isFloat)
3176 libCall = spv::GLSLstd450FClamp;
3177 else if (isUnsigned)
3178 libCall = spv::GLSLstd450UClamp;
3179 else
3180 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003181 builder.promoteScalar(precision, operands.front(), operands[1]);
3182 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003183 break;
3184 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003185 if (isFloat)
3186 libCall = spv::GLSLstd450FMix;
3187 else
3188 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003189 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003190 break;
3191 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003192 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003193 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003194 break;
3195 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003196 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003197 builder.promoteScalar(precision, operands[0], operands[2]);
3198 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003199 break;
3200
3201 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003202 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003203 break;
3204 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003205 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003206 break;
3207 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003208 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003209 break;
3210 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003211 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003212 break;
3213 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003214 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003215 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003216 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003217 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003218 libCall = spv::GLSLstd450InterpolateAtSample;
3219 break;
3220 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003221 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003222 libCall = spv::GLSLstd450InterpolateAtOffset;
3223 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003224 case glslang::EOpAddCarry:
3225 opCode = spv::OpIAddCarry;
3226 typeId = builder.makeStructResultType(typeId0, typeId0);
3227 consumedOperands = 2;
3228 break;
3229 case glslang::EOpSubBorrow:
3230 opCode = spv::OpISubBorrow;
3231 typeId = builder.makeStructResultType(typeId0, typeId0);
3232 consumedOperands = 2;
3233 break;
3234 case glslang::EOpUMulExtended:
3235 opCode = spv::OpUMulExtended;
3236 typeId = builder.makeStructResultType(typeId0, typeId0);
3237 consumedOperands = 2;
3238 break;
3239 case glslang::EOpIMulExtended:
3240 opCode = spv::OpSMulExtended;
3241 typeId = builder.makeStructResultType(typeId0, typeId0);
3242 consumedOperands = 2;
3243 break;
3244 case glslang::EOpBitfieldExtract:
3245 if (isUnsigned)
3246 opCode = spv::OpBitFieldUExtract;
3247 else
3248 opCode = spv::OpBitFieldSExtract;
3249 break;
3250 case glslang::EOpBitfieldInsert:
3251 opCode = spv::OpBitFieldInsert;
3252 break;
3253
3254 case glslang::EOpFma:
3255 libCall = spv::GLSLstd450Fma;
3256 break;
3257 case glslang::EOpFrexp:
3258 libCall = spv::GLSLstd450FrexpStruct;
3259 if (builder.getNumComponents(operands[0]) == 1)
3260 frexpIntType = builder.makeIntegerType(32, true);
3261 else
3262 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3263 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3264 consumedOperands = 1;
3265 break;
3266 case glslang::EOpLdexp:
3267 libCall = spv::GLSLstd450Ldexp;
3268 break;
3269
John Kessenich140f3df2015-06-26 16:58:36 -06003270 default:
3271 return 0;
3272 }
3273
3274 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003275 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003276 // Use an extended instruction from the standard library.
3277 // Construct the call arguments, without modifying the original operands vector.
3278 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3279 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
3280 id = builder.createBuiltinCall(precision, typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003281 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003282 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003283 case 0:
3284 // should all be handled by visitAggregate and createNoArgOperation
3285 assert(0);
3286 return 0;
3287 case 1:
3288 // should all be handled by createUnaryOperation
3289 assert(0);
3290 return 0;
3291 case 2:
3292 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3293 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003294 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003295 // anything 3 or over doesn't have l-value operands, so all should be consumed
3296 assert(consumedOperands == operands.size());
3297 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003298 break;
3299 }
3300 }
3301
John Kessenich55e7d112015-11-15 21:33:39 -07003302 // Decode the return types that were structures
3303 switch (op) {
3304 case glslang::EOpAddCarry:
3305 case glslang::EOpSubBorrow:
3306 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3307 id = builder.createCompositeExtract(id, typeId0, 0);
3308 break;
3309 case glslang::EOpUMulExtended:
3310 case glslang::EOpIMulExtended:
3311 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3312 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3313 break;
3314 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003315 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003316 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3317 id = builder.createCompositeExtract(id, typeId0, 0);
3318 break;
3319 default:
3320 break;
3321 }
3322
John Kessenich140f3df2015-06-26 16:58:36 -06003323 builder.setPrecision(id, precision);
3324
3325 return id;
3326}
3327
3328// Intrinsics with no arguments, no return value, and no precision.
3329spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3330{
3331 // TODO: get the barrier operands correct
3332
3333 switch (op) {
3334 case glslang::EOpEmitVertex:
3335 builder.createNoResultOp(spv::OpEmitVertex);
3336 return 0;
3337 case glslang::EOpEndPrimitive:
3338 builder.createNoResultOp(spv::OpEndPrimitive);
3339 return 0;
3340 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003341 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3342 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003343 return 0;
3344 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003345 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003346 return 0;
3347 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003348 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003349 return 0;
3350 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003351 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003352 return 0;
3353 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003354 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003355 return 0;
3356 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003357 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003358 return 0;
3359 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003360 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003361 return 0;
3362 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003363 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003364 return 0;
3365 }
3366}
3367
3368spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3369{
John Kessenich2f273362015-07-18 22:34:27 -06003370 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003371 spv::Id id;
3372 if (symbolValues.end() != iter) {
3373 id = iter->second;
3374 return id;
3375 }
3376
3377 // it was not found, create it
3378 id = createSpvVariable(symbol);
3379 symbolValues[symbol->getId()] = id;
3380
3381 if (! symbol->getType().isStruct()) {
3382 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003383 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003384 if (symbol->getQualifier().hasLocation())
3385 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3386 if (symbol->getQualifier().hasIndex())
3387 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3388 if (symbol->getQualifier().hasComponent())
3389 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3390 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003391 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003392 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003393 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003394 if (symbol->getQualifier().hasXfbBuffer())
3395 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3396 if (symbol->getQualifier().hasXfbOffset())
3397 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3398 }
3399 }
3400
John Kesseniche0b6cad2015-12-24 10:30:13 -07003401 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003402 if (symbol->getQualifier().hasStream()) {
3403 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003404 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003405 }
John Kessenich140f3df2015-06-26 16:58:36 -06003406 if (symbol->getQualifier().hasSet())
3407 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3408 if (symbol->getQualifier().hasBinding())
3409 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3410 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003411 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003412 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003413 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003414 if (symbol->getQualifier().hasXfbBuffer())
3415 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3416 }
3417
3418 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003419 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003420 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003421 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003422
John Kessenich140f3df2015-06-26 16:58:36 -06003423 return id;
3424}
3425
John Kessenich55e7d112015-11-15 21:33:39 -07003426// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003427void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3428{
3429 if (dec != spv::BadValue)
3430 builder.addDecoration(id, dec);
3431}
3432
John Kessenich55e7d112015-11-15 21:33:39 -07003433// If 'dec' is valid, add a one-operand decoration to an object
3434void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3435{
3436 if (dec != spv::BadValue)
3437 builder.addDecoration(id, dec, value);
3438}
3439
3440// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003441void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3442{
3443 if (dec != spv::BadValue)
3444 builder.addMemberDecoration(id, (unsigned)member, dec);
3445}
3446
John Kessenich92187592016-02-01 13:45:25 -07003447// If 'dec' is valid, add a one-operand decoration to a struct member
3448void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3449{
3450 if (dec != spv::BadValue)
3451 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3452}
3453
John Kessenich55e7d112015-11-15 21:33:39 -07003454// Make a full tree of instructions to build a SPIR-V specialization constant,
3455// or regularly constant if possible.
3456//
3457// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3458//
3459// Recursively walk the nodes. The nodes form a tree whose leaves are
3460// regular constants, which themselves are trees that createSpvConstant()
3461// recursively walks. So, this function walks the "top" of the tree:
3462// - emit specialization constant-building instructions for specConstant
3463// - when running into a non-spec-constant, switch to createSpvConstant()
3464spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3465{
3466 assert(node.getQualifier().storage == glslang::EvqConst);
3467
3468 // hand off to the non-spec-constant path
3469 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3470 int nextConst = 0;
3471 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3472}
3473
John Kessenich140f3df2015-06-26 16:58:36 -06003474// Use 'consts' as the flattened glslang source of scalar constants to recursively
3475// build the aggregate SPIR-V constant.
3476//
3477// If there are not enough elements present in 'consts', 0 will be substituted;
3478// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3479//
John Kessenich55e7d112015-11-15 21:33:39 -07003480spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003481{
3482 // vector of constants for SPIR-V
3483 std::vector<spv::Id> spvConsts;
3484
3485 // Type is used for struct and array constants
3486 spv::Id typeId = convertGlslangToSpvType(glslangType);
3487
3488 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003489 glslang::TType elementType(glslangType, 0);
3490 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003491 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003492 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003493 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003494 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003495 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003496 } else if (glslangType.getStruct()) {
3497 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3498 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003499 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003500 } else if (glslangType.isVector()) {
3501 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3502 bool zero = nextConst >= consts.size();
3503 switch (glslangType.getBasicType()) {
3504 case glslang::EbtInt:
3505 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3506 break;
3507 case glslang::EbtUint:
3508 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3509 break;
3510 case glslang::EbtFloat:
3511 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3512 break;
3513 case glslang::EbtDouble:
3514 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3515 break;
3516 case glslang::EbtBool:
3517 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3518 break;
3519 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003520 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003521 break;
3522 }
3523 ++nextConst;
3524 }
3525 } else {
3526 // we have a non-aggregate (scalar) constant
3527 bool zero = nextConst >= consts.size();
3528 spv::Id scalar = 0;
3529 switch (glslangType.getBasicType()) {
3530 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003531 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003532 break;
3533 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003534 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003535 break;
3536 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003537 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003538 break;
3539 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003540 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003541 break;
3542 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003543 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003544 break;
3545 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003546 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003547 break;
3548 }
3549 ++nextConst;
3550 return scalar;
3551 }
3552
3553 return builder.makeCompositeConstant(typeId, spvConsts);
3554}
3555
John Kessenich7c1aa102015-10-15 13:29:11 -06003556// Return true if the node is a constant or symbol whose reading has no
3557// non-trivial observable cost or effect.
3558bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3559{
3560 // don't know what this is
3561 if (node == nullptr)
3562 return false;
3563
3564 // a constant is safe
3565 if (node->getAsConstantUnion() != nullptr)
3566 return true;
3567
3568 // not a symbol means non-trivial
3569 if (node->getAsSymbolNode() == nullptr)
3570 return false;
3571
3572 // a symbol, depends on what's being read
3573 switch (node->getType().getQualifier().storage) {
3574 case glslang::EvqTemporary:
3575 case glslang::EvqGlobal:
3576 case glslang::EvqIn:
3577 case glslang::EvqInOut:
3578 case glslang::EvqConst:
3579 case glslang::EvqConstReadOnly:
3580 case glslang::EvqUniform:
3581 return true;
3582 default:
3583 return false;
3584 }
3585}
3586
3587// A node is trivial if it is a single operation with no side effects.
3588// Error on the side of saying non-trivial.
3589// Return true if trivial.
3590bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3591{
3592 if (node == nullptr)
3593 return false;
3594
3595 // symbols and constants are trivial
3596 if (isTrivialLeaf(node))
3597 return true;
3598
3599 // otherwise, it needs to be a simple operation or one or two leaf nodes
3600
3601 // not a simple operation
3602 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3603 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3604 if (binaryNode == nullptr && unaryNode == nullptr)
3605 return false;
3606
3607 // not on leaf nodes
3608 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3609 return false;
3610
3611 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3612 return false;
3613 }
3614
3615 switch (node->getAsOperator()->getOp()) {
3616 case glslang::EOpLogicalNot:
3617 case glslang::EOpConvIntToBool:
3618 case glslang::EOpConvUintToBool:
3619 case glslang::EOpConvFloatToBool:
3620 case glslang::EOpConvDoubleToBool:
3621 case glslang::EOpEqual:
3622 case glslang::EOpNotEqual:
3623 case glslang::EOpLessThan:
3624 case glslang::EOpGreaterThan:
3625 case glslang::EOpLessThanEqual:
3626 case glslang::EOpGreaterThanEqual:
3627 case glslang::EOpIndexDirect:
3628 case glslang::EOpIndexDirectStruct:
3629 case glslang::EOpLogicalXor:
3630 case glslang::EOpAny:
3631 case glslang::EOpAll:
3632 return true;
3633 default:
3634 return false;
3635 }
3636}
3637
3638// Emit short-circuiting code, where 'right' is never evaluated unless
3639// the left side is true (for &&) or false (for ||).
3640spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3641{
3642 spv::Id boolTypeId = builder.makeBoolType();
3643
3644 // emit left operand
3645 builder.clearAccessChain();
3646 left.traverse(this);
3647 spv::Id leftId = builder.accessChainLoad(boolTypeId);
3648
3649 // Operands to accumulate OpPhi operands
3650 std::vector<spv::Id> phiOperands;
3651 // accumulate left operand's phi information
3652 phiOperands.push_back(leftId);
3653 phiOperands.push_back(builder.getBuildPoint()->getId());
3654
3655 // Make the two kinds of operation symmetric with a "!"
3656 // || => emit "if (! left) result = right"
3657 // && => emit "if ( left) result = right"
3658 //
3659 // TODO: this runtime "not" for || could be avoided by adding functionality
3660 // to 'builder' to have an "else" without an "then"
3661 if (op == glslang::EOpLogicalOr)
3662 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3663
3664 // make an "if" based on the left value
3665 spv::Builder::If ifBuilder(leftId, builder);
3666
3667 // emit right operand as the "then" part of the "if"
3668 builder.clearAccessChain();
3669 right.traverse(this);
3670 spv::Id rightId = builder.accessChainLoad(boolTypeId);
3671
3672 // accumulate left operand's phi information
3673 phiOperands.push_back(rightId);
3674 phiOperands.push_back(builder.getBuildPoint()->getId());
3675
3676 // finish the "if"
3677 ifBuilder.makeEndIf();
3678
3679 // phi together the two results
3680 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3681}
3682
John Kessenich140f3df2015-06-26 16:58:36 -06003683}; // end anonymous namespace
3684
3685namespace glslang {
3686
John Kessenich68d78fd2015-07-12 19:28:10 -06003687void GetSpirvVersion(std::string& version)
3688{
John Kessenich9e55f632015-07-15 10:03:39 -06003689 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003690 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003691 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003692 version = buf;
3693}
3694
John Kessenich140f3df2015-06-26 16:58:36 -06003695// Write SPIR-V out to a binary file
3696void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3697{
3698 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003699 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003700 for (int i = 0; i < (int)spirv.size(); ++i) {
3701 unsigned int word = spirv[i];
3702 out.write((const char*)&word, 4);
3703 }
3704 out.close();
3705}
3706
3707//
3708// Set up the glslang traversal
3709//
3710void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3711{
3712 TIntermNode* root = intermediate.getTreeRoot();
3713
3714 if (root == 0)
3715 return;
3716
3717 glslang::GetThreadPoolAllocator().push();
3718
3719 TGlslangToSpvTraverser it(&intermediate);
3720
3721 root->traverse(&it);
3722
3723 it.dumpSpv(spirv);
3724
3725 glslang::GetThreadPoolAllocator().pop();
3726}
3727
3728}; // end namespace glslang