blob: ed86cc2d77bd1c485c5040caaaddfa765418bcfa [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 Kessenich5e801132016-02-15 11:09:46 -070091 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -070092 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -070093 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -060094 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
95 spv::Id getSampledType(const glslang::TSampler&);
96 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070097 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich32cfd492016-02-02 12:37:46 -070098 spv::Id accessChainLoad(const glslang::TType& type);
John Kessenichf85e8062015-12-19 13:57:10 -070099 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700100 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
101 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
102 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 -0600103
104 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
105 void makeFunctions(const glslang::TIntermSequence&);
106 void makeGlobalInitializers(const glslang::TIntermSequence&);
107 void visitFunctions(const glslang::TIntermSequence&);
108 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800109 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600110 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
111 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600112 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
113
114 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 -0700115 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800116 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 -0700117 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600118 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
119 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800120 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 -0600121 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 -0600122 spv::Id createNoArgOperation(glslang::TOperator op);
123 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
124 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700125 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600126 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700127 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700128 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
129 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600130 bool isTrivialLeaf(const glslang::TIntermTyped* node);
131 bool isTrivial(const glslang::TIntermTyped* node);
132 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600133
134 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700135 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600136 int sequenceDepth;
137
138 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
139 spv::Builder builder;
140 bool inMain;
141 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700142 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 -0700143 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600144 const glslang::TIntermediate* glslangIntermediate;
145 spv::Id stdBuiltins;
146
John Kessenich2f273362015-07-18 22:34:27 -0600147 std::unordered_map<int, spv::Id> symbolValues;
148 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
149 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700150 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600151 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 -0600152 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600153};
154
155//
156// Helper functions for translating glslang representations to SPIR-V enumerants.
157//
158
159// Translate glslang profile to SPIR-V source language.
160spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
161{
162 switch (profile) {
163 case ENoProfile:
164 case ECoreProfile:
165 case ECompatibilityProfile:
166 return spv::SourceLanguageGLSL;
167 case EEsProfile:
168 return spv::SourceLanguageESSL;
169 default:
170 return spv::SourceLanguageUnknown;
171 }
172}
173
174// Translate glslang language (stage) to SPIR-V execution model.
175spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
176{
177 switch (stage) {
178 case EShLangVertex: return spv::ExecutionModelVertex;
179 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
180 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
181 case EShLangGeometry: return spv::ExecutionModelGeometry;
182 case EShLangFragment: return spv::ExecutionModelFragment;
183 case EShLangCompute: return spv::ExecutionModelGLCompute;
184 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700185 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600186 return spv::ExecutionModelFragment;
187 }
188}
189
190// Translate glslang type to SPIR-V storage class.
191spv::StorageClass TranslateStorageClass(const glslang::TType& type)
192{
193 if (type.getQualifier().isPipeInput())
194 return spv::StorageClassInput;
195 else if (type.getQualifier().isPipeOutput())
196 return spv::StorageClassOutput;
197 else if (type.getQualifier().isUniformOrBuffer()) {
198 if (type.getBasicType() == glslang::EbtBlock)
199 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800200 else if (type.getBasicType() == glslang::EbtAtomicUint)
201 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 else
203 return spv::StorageClassUniformConstant;
204 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
205 } else {
206 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700207 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
208 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600209 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
210 case glslang::EvqTemporary: return spv::StorageClassFunction;
211 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700212 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600213 return spv::StorageClassFunction;
214 }
215 }
216}
217
218// Translate glslang sampler type to SPIR-V dimensionality.
219spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
220{
221 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700222 case glslang::Esd1D: return spv::Dim1D;
223 case glslang::Esd2D: return spv::Dim2D;
224 case glslang::Esd3D: return spv::Dim3D;
225 case glslang::EsdCube: return spv::DimCube;
226 case glslang::EsdRect: return spv::DimRect;
227 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700229 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600230 return spv::Dim2D;
231 }
232}
233
234// Translate glslang type to SPIR-V precision decorations.
235spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
236{
237 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700238 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600239 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600240 default:
241 return spv::NoPrecision;
242 }
243}
244
245// Translate glslang type to SPIR-V block decorations.
246spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
247{
248 if (type.getBasicType() == glslang::EbtBlock) {
249 switch (type.getQualifier().storage) {
250 case glslang::EvqUniform: return spv::DecorationBlock;
251 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
252 case glslang::EvqVaryingIn: return spv::DecorationBlock;
253 case glslang::EvqVaryingOut: return spv::DecorationBlock;
254 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700255 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600256 break;
257 }
258 }
259
260 return (spv::Decoration)spv::BadValue;
261}
262
263// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700264spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600265{
266 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700267 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600268 case glslang::ElmRowMajor:
269 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700270 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600271 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700272 default:
273 // opaque layouts don't need a majorness
274 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600275 }
276 } else {
277 switch (type.getBasicType()) {
278 default:
279 return (spv::Decoration)spv::BadValue;
280 break;
281 case glslang::EbtBlock:
282 switch (type.getQualifier().storage) {
283 case glslang::EvqUniform:
284 case glslang::EvqBuffer:
285 switch (type.getQualifier().layoutPacking) {
286 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600287 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
288 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600289 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 }
291 case glslang::EvqVaryingIn:
292 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 return (spv::Decoration)spv::BadValue;
295 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700296 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600297 return (spv::Decoration)spv::BadValue;
298 }
299 }
300 }
301}
302
303// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700304// Returns spv::Decoration(spv::BadValue) when no decoration
305// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700306spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600307{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700308 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700309 // Smooth decoration doesn't exist in SPIR-V 1.0
310 return (spv::Decoration)spv::BadValue;
311 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700312 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700313 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700314 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700316 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600317 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700318 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600319 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700320 else if (qualifier.sample) {
321 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700323 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return (spv::Decoration)spv::BadValue;
325}
326
John Kessenich92187592016-02-01 13:45:25 -0700327// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700328spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600329{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700330 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600331 return spv::DecorationInvariant;
332 else
333 return (spv::Decoration)spv::BadValue;
334}
335
336// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700337spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600338{
339 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700340 case glslang::EbvPointSize:
341 switch (glslangIntermediate->getStage()) {
342 case EShLangGeometry:
343 builder.addCapability(spv::CapabilityGeometryPointSize);
344 break;
345 case EShLangTessControl:
346 case EShLangTessEvaluation:
347 builder.addCapability(spv::CapabilityTessellationPointSize);
348 break;
349 }
350 return spv::BuiltInPointSize;
351
352 case glslang::EbvClipDistance:
353 builder.addCapability(spv::CapabilityClipDistance);
354 return spv::BuiltInClipDistance;
355
356 case glslang::EbvCullDistance:
357 builder.addCapability(spv::CapabilityCullDistance);
358 return spv::BuiltInCullDistance;
359
360 case glslang::EbvViewportIndex:
361 // TODO: builder.addCapability(spv::CapabilityMultiViewport);
362 return spv::BuiltInViewportIndex;
363
John Kessenich5e801132016-02-15 11:09:46 -0700364 case glslang::EbvSampleId:
365 builder.addCapability(spv::CapabilitySampleRateShading);
366 return spv::BuiltInSampleId;
367
368 case glslang::EbvSamplePosition:
369 builder.addCapability(spv::CapabilitySampleRateShading);
370 return spv::BuiltInSamplePosition;
371
372 case glslang::EbvSampleMask:
373 builder.addCapability(spv::CapabilitySampleRateShading);
374 return spv::BuiltInSampleMask;
375
John Kessenich140f3df2015-06-26 16:58:36 -0600376 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600377 case glslang::EbvVertexId: return spv::BuiltInVertexId;
378 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600379 case glslang::EbvBaseVertex:
380 case glslang::EbvBaseInstance:
381 case glslang::EbvDrawId:
382 // TODO: Add SPIR-V builtin ID.
383 spv::MissingFunctionality("Draw parameters");
384 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600385 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
386 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
387 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600388 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
389 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
390 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
391 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
392 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
393 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
394 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600395 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
396 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
397 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
398 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
399 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
400 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
401 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
402 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
403 default: return (spv::BuiltIn)spv::BadValue;
404 }
405}
406
Rex Xufc618912015-09-09 16:42:49 +0800407// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700408spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800409{
410 assert(type.getBasicType() == glslang::EbtSampler);
411
John Kessenich5d0fa972016-02-15 11:57:00 -0700412 // Check for capabilities
413 switch (type.getQualifier().layoutFormat) {
414 case glslang::ElfRg32f:
415 case glslang::ElfRg16f:
416 case glslang::ElfR11fG11fB10f:
417 case glslang::ElfR16f:
418 case glslang::ElfRgba16:
419 case glslang::ElfRgb10A2:
420 case glslang::ElfRg16:
421 case glslang::ElfRg8:
422 case glslang::ElfR16:
423 case glslang::ElfR8:
424 case glslang::ElfRgba16Snorm:
425 case glslang::ElfRg16Snorm:
426 case glslang::ElfRg8Snorm:
427 case glslang::ElfR16Snorm:
428 case glslang::ElfR8Snorm:
429
430 case glslang::ElfRg32i:
431 case glslang::ElfRg16i:
432 case glslang::ElfRg8i:
433 case glslang::ElfR16i:
434 case glslang::ElfR8i:
435
436 case glslang::ElfRgb10a2ui:
437 case glslang::ElfRg32ui:
438 case glslang::ElfRg16ui:
439 case glslang::ElfRg8ui:
440 case glslang::ElfR16ui:
441 case glslang::ElfR8ui:
442 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
443 break;
444
445 default:
446 break;
447 }
448
449 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800450 switch (type.getQualifier().layoutFormat) {
451 case glslang::ElfNone: return spv::ImageFormatUnknown;
452 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
453 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
454 case glslang::ElfR32f: return spv::ImageFormatR32f;
455 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
456 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
457 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
458 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
459 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
460 case glslang::ElfR16f: return spv::ImageFormatR16f;
461 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
462 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
463 case glslang::ElfRg16: return spv::ImageFormatRg16;
464 case glslang::ElfRg8: return spv::ImageFormatRg8;
465 case glslang::ElfR16: return spv::ImageFormatR16;
466 case glslang::ElfR8: return spv::ImageFormatR8;
467 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
468 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
469 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
470 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
471 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
472 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
473 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
474 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
475 case glslang::ElfR32i: return spv::ImageFormatR32i;
476 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
477 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
478 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
479 case glslang::ElfR16i: return spv::ImageFormatR16i;
480 case glslang::ElfR8i: return spv::ImageFormatR8i;
481 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
482 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
483 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
484 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
485 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
486 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
487 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
488 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
489 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
490 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
491 default: return (spv::ImageFormat)spv::BadValue;
492 }
493}
494
John Kesseniche0b6cad2015-12-24 10:30:13 -0700495void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
496{
497 if (child.layoutMatrix == glslang::ElmNone)
498 child.layoutMatrix = parent.layoutMatrix;
499
500 if (parent.invariant)
501 child.invariant = true;
502 if (parent.nopersp)
503 child.nopersp = true;
504 if (parent.flat)
505 child.flat = true;
506 if (parent.centroid)
507 child.centroid = true;
508 if (parent.patch)
509 child.patch = true;
510 if (parent.sample)
511 child.sample = true;
John Kessenich7b9fa252016-01-21 18:56:57 -0700512
513 child.layoutLocation = parent.layoutLocation;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700514}
515
516bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
517{
John Kessenich7b9fa252016-01-21 18:56:57 -0700518 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700519 // - struct members can inherit from a struct declaration
520 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
521 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700522 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700523}
524
John Kessenich140f3df2015-06-26 16:58:36 -0600525//
526// Implement the TGlslangToSpvTraverser class.
527//
528
529TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
530 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700531 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600532 inMain(false), mainTerminated(false), linkageOnly(false),
533 glslangIntermediate(glslangIntermediate)
534{
535 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
536
537 builder.clearAccessChain();
538 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
539 stdBuiltins = builder.import("GLSL.std.450");
540 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
541 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700542 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600543
544 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600545 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
546 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600547 builder.addSourceExtension(it->c_str());
548
549 // Add the top-level modes for this shader.
550
John Kessenich92187592016-02-01 13:45:25 -0700551 if (glslangIntermediate->getXfbMode()) {
552 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600553 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700554 }
John Kessenich140f3df2015-06-26 16:58:36 -0600555
556 unsigned int mode;
557 switch (glslangIntermediate->getStage()) {
558 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600559 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600560 break;
561
562 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600563 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600564 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
565 break;
566
567 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600568 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600569 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700570 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
571 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
572 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600573 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600574 }
575 if (mode != spv::BadValue)
576 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
577
John Kesseniche6903322015-10-13 16:29:02 -0600578 switch (glslangIntermediate->getVertexSpacing()) {
579 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
580 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
581 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
582 default: mode = spv::BadValue; break;
583 }
584 if (mode != spv::BadValue)
585 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
586
587 switch (glslangIntermediate->getVertexOrder()) {
588 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
589 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
590 default: mode = spv::BadValue; break;
591 }
592 if (mode != spv::BadValue)
593 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
594
595 if (glslangIntermediate->getPointMode())
596 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600597 break;
598
599 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600600 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600601 switch (glslangIntermediate->getInputPrimitive()) {
602 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
603 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
604 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700605 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600606 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
607 default: mode = spv::BadValue; break;
608 }
609 if (mode != spv::BadValue)
610 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600611
John Kessenich140f3df2015-06-26 16:58:36 -0600612 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
613
614 switch (glslangIntermediate->getOutputPrimitive()) {
615 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
616 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
617 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
618 default: mode = spv::BadValue; break;
619 }
620 if (mode != spv::BadValue)
621 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
622 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
623 break;
624
625 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600626 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600627 if (glslangIntermediate->getPixelCenterInteger())
628 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600629
John Kessenich140f3df2015-06-26 16:58:36 -0600630 if (glslangIntermediate->getOriginUpperLeft())
631 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600632 else
633 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600634
635 if (glslangIntermediate->getEarlyFragmentTests())
636 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
637
638 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600639 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
640 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
641 default: mode = spv::BadValue; break;
642 }
643 if (mode != spv::BadValue)
644 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
645
646 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
647 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600648 break;
649
650 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600651 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600652 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
653 glslangIntermediate->getLocalSize(1),
654 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600655 break;
656
657 default:
658 break;
659 }
660
661}
662
John Kessenich7ba63412015-12-20 17:37:07 -0700663// Finish everything and dump
664void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
665{
666 // finish off the entry-point SPV instruction by adding the Input/Output <id>
667 for (auto it : iOSet)
668 entryPoint->addIdOperand(it);
669
670 builder.dump(out);
671}
672
John Kessenich140f3df2015-06-26 16:58:36 -0600673TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
674{
675 if (! mainTerminated) {
676 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
677 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600678 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600679 }
680}
681
682//
683// Implement the traversal functions.
684//
685// Return true from interior nodes to have the external traversal
686// continue on to children. Return false if children were
687// already processed.
688//
689
690//
691// Symbols can turn into
692// - uniform/input reads
693// - output writes
694// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
695// - something simple that degenerates into the last bullet
696//
697void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
698{
699 // getSymbolId() will set up all the IO decorations on the first call.
700 // Formal function parameters were mapped during makeFunctions().
701 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700702
703 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
704 if (builder.isPointer(id)) {
705 spv::StorageClass sc = builder.getStorageClass(id);
706 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
707 iOSet.insert(id);
708 }
709
710 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600711 if (! linkageOnly) {
712 // Prepare to generate code for the access
713
714 // L-value chains will be computed left to right. We're on the symbol now,
715 // which is the left-most part of the access chain, so now is "clear" time,
716 // followed by setting the base.
717 builder.clearAccessChain();
718
719 // For now, we consider all user variables as being in memory, so they are pointers,
720 // except for "const in" arguments to a function, which are an intermediate object.
721 // See comments in handleUserFunctionCall().
722 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
723 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
724 builder.setAccessChainRValue(id);
725 else
726 builder.setAccessChainLValue(id);
727 }
728}
729
730bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
731{
732 // First, handle special cases
733 switch (node->getOp()) {
734 case glslang::EOpAssign:
735 case glslang::EOpAddAssign:
736 case glslang::EOpSubAssign:
737 case glslang::EOpMulAssign:
738 case glslang::EOpVectorTimesMatrixAssign:
739 case glslang::EOpVectorTimesScalarAssign:
740 case glslang::EOpMatrixTimesScalarAssign:
741 case glslang::EOpMatrixTimesMatrixAssign:
742 case glslang::EOpDivAssign:
743 case glslang::EOpModAssign:
744 case glslang::EOpAndAssign:
745 case glslang::EOpInclusiveOrAssign:
746 case glslang::EOpExclusiveOrAssign:
747 case glslang::EOpLeftShiftAssign:
748 case glslang::EOpRightShiftAssign:
749 // A bin-op assign "a += b" means the same thing as "a = a + b"
750 // where a is evaluated before b. For a simple assignment, GLSL
751 // says to evaluate the left before the right. So, always, left
752 // node then right node.
753 {
754 // get the left l-value, save it away
755 builder.clearAccessChain();
756 node->getLeft()->traverse(this);
757 spv::Builder::AccessChain lValue = builder.getAccessChain();
758
759 // evaluate the right
760 builder.clearAccessChain();
761 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700762 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600763
764 if (node->getOp() != glslang::EOpAssign) {
765 // the left is also an r-value
766 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700767 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600768
769 // do the operation
770 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
771 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
772 node->getType().getBasicType());
773
774 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700775 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600776 }
777
778 // store the result
779 builder.setAccessChain(lValue);
780 builder.accessChainStore(rValue);
781
782 // assignments are expressions having an rValue after they are evaluated...
783 builder.clearAccessChain();
784 builder.setAccessChainRValue(rValue);
785 }
786 return false;
787 case glslang::EOpIndexDirect:
788 case glslang::EOpIndexDirectStruct:
789 {
790 // Get the left part of the access chain.
791 node->getLeft()->traverse(this);
792
793 // Add the next element in the chain
794
John Kessenich55e7d112015-11-15 21:33:39 -0700795 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600796 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
797 // This may be, e.g., an anonymous block-member selection, which generally need
798 // index remapping due to hidden members in anonymous blocks.
799 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700800 assert(remapper.size() > 0);
801 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600802 }
803
804 if (! node->getLeft()->getType().isArray() &&
805 node->getLeft()->getType().isVector() &&
806 node->getOp() == glslang::EOpIndexDirect) {
807 // This is essentially a hard-coded vector swizzle of size 1,
808 // so short circuit the access-chain stuff with a swizzle.
809 std::vector<unsigned> swizzle;
810 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600811 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600812 } else {
813 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600814 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600815 }
816 }
817 return false;
818 case glslang::EOpIndexIndirect:
819 {
820 // Structure or array or vector indirection.
821 // Will use native SPIR-V access-chain for struct and array indirection;
822 // matrices are arrays of vectors, so will also work for a matrix.
823 // Will use the access chain's 'component' for variable index into a vector.
824
825 // This adapter is building access chains left to right.
826 // Set up the access chain to the left.
827 node->getLeft()->traverse(this);
828
829 // save it so that computing the right side doesn't trash it
830 spv::Builder::AccessChain partial = builder.getAccessChain();
831
832 // compute the next index in the chain
833 builder.clearAccessChain();
834 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700835 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600836
837 // restore the saved access chain
838 builder.setAccessChain(partial);
839
840 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600841 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600842 else
John Kessenichfa668da2015-09-13 14:46:30 -0600843 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600844 }
845 return false;
846 case glslang::EOpVectorSwizzle:
847 {
848 node->getLeft()->traverse(this);
849 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
850 std::vector<unsigned> swizzle;
851 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
852 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600853 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600854 }
855 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600856 case glslang::EOpLogicalOr:
857 case glslang::EOpLogicalAnd:
858 {
859
860 // These may require short circuiting, but can sometimes be done as straight
861 // binary operations. The right operand must be short circuited if it has
862 // side effects, and should probably be if it is complex.
863 if (isTrivial(node->getRight()->getAsTyped()))
864 break; // handle below as a normal binary operation
865 // otherwise, we need to do dynamic short circuiting on the right operand
866 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
867 builder.clearAccessChain();
868 builder.setAccessChainRValue(result);
869 }
870 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600871 default:
872 break;
873 }
874
875 // Assume generic binary op...
876
John Kessenich32cfd492016-02-02 12:37:46 -0700877 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600878 builder.clearAccessChain();
879 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700880 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600881
John Kessenich32cfd492016-02-02 12:37:46 -0700882 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600883 builder.clearAccessChain();
884 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700885 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600886
John Kessenich32cfd492016-02-02 12:37:46 -0700887 // get result
888 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
889 convertGlslangToSpvType(node->getType()), left, right,
890 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600891
John Kessenich50e57562015-12-21 21:21:11 -0700892 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600893 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700894 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700895 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600896 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600897 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600898 return false;
899 }
John Kessenich140f3df2015-06-26 16:58:36 -0600900}
901
902bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
903{
John Kessenichfc51d282015-08-19 13:34:18 -0600904 spv::Id result = spv::NoResult;
905
906 // try texturing first
907 result = createImageTextureFunctionCall(node);
908 if (result != spv::NoResult) {
909 builder.clearAccessChain();
910 builder.setAccessChainRValue(result);
911
912 return false; // done with this node
913 }
914
915 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600916
917 if (node->getOp() == glslang::EOpArrayLength) {
918 // Quite special; won't want to evaluate the operand.
919
920 // Normal .length() would have been constant folded by the front-end.
921 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600922 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600923 assert(node->getOperand()->getType().isRuntimeSizedArray());
924 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
925 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600926 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
927 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600928
929 builder.clearAccessChain();
930 builder.setAccessChainRValue(length);
931
932 return false;
933 }
934
John Kessenichfc51d282015-08-19 13:34:18 -0600935 // Start by evaluating the operand
936
John Kessenich140f3df2015-06-26 16:58:36 -0600937 builder.clearAccessChain();
938 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800939
Rex Xufc618912015-09-09 16:42:49 +0800940 spv::Id operand = spv::NoResult;
941
942 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
943 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800944 node->getOp() == glslang::EOpAtomicCounter ||
945 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800946 operand = builder.accessChainGetLValue(); // Special case l-value operands
947 else
John Kessenich32cfd492016-02-02 12:37:46 -0700948 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600949
950 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
951
952 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600953 if (! result)
954 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600955
956 // if not, then possibly an operation
957 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700958 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600959
960 if (result) {
961 builder.clearAccessChain();
962 builder.setAccessChainRValue(result);
963
964 return false; // done with this node
965 }
966
967 // it must be a special case, check...
968 switch (node->getOp()) {
969 case glslang::EOpPostIncrement:
970 case glslang::EOpPostDecrement:
971 case glslang::EOpPreIncrement:
972 case glslang::EOpPreDecrement:
973 {
974 // we need the integer value "1" or the floating point "1.0" to add/subtract
975 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
976 builder.makeFloatConstant(1.0F) :
977 builder.makeIntConstant(1);
978 glslang::TOperator op;
979 if (node->getOp() == glslang::EOpPreIncrement ||
980 node->getOp() == glslang::EOpPostIncrement)
981 op = glslang::EOpAdd;
982 else
983 op = glslang::EOpSub;
984
985 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
986 convertGlslangToSpvType(node->getType()), operand, one,
987 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700988 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600989
990 // The result of operation is always stored, but conditionally the
991 // consumed result. The consumed result is always an r-value.
992 builder.accessChainStore(result);
993 builder.clearAccessChain();
994 if (node->getOp() == glslang::EOpPreIncrement ||
995 node->getOp() == glslang::EOpPreDecrement)
996 builder.setAccessChainRValue(result);
997 else
998 builder.setAccessChainRValue(operand);
999 }
1000
1001 return false;
1002
1003 case glslang::EOpEmitStreamVertex:
1004 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1005 return false;
1006 case glslang::EOpEndStreamPrimitive:
1007 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1008 return false;
1009
1010 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001011 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001012 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001013 }
John Kessenich140f3df2015-06-26 16:58:36 -06001014}
1015
1016bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1017{
John Kessenichfc51d282015-08-19 13:34:18 -06001018 spv::Id result = spv::NoResult;
1019
1020 // try texturing
1021 result = createImageTextureFunctionCall(node);
1022 if (result != spv::NoResult) {
1023 builder.clearAccessChain();
1024 builder.setAccessChainRValue(result);
1025
1026 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001027 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001028 // "imageStore" is a special case, which has no result
1029 return false;
1030 }
John Kessenichfc51d282015-08-19 13:34:18 -06001031
John Kessenich140f3df2015-06-26 16:58:36 -06001032 glslang::TOperator binOp = glslang::EOpNull;
1033 bool reduceComparison = true;
1034 bool isMatrix = false;
1035 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001036 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001037
1038 assert(node->getOp());
1039
1040 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1041
1042 switch (node->getOp()) {
1043 case glslang::EOpSequence:
1044 {
1045 if (preVisit)
1046 ++sequenceDepth;
1047 else
1048 --sequenceDepth;
1049
1050 if (sequenceDepth == 1) {
1051 // If this is the parent node of all the functions, we want to see them
1052 // early, so all call points have actual SPIR-V functions to reference.
1053 // In all cases, still let the traverser visit the children for us.
1054 makeFunctions(node->getAsAggregate()->getSequence());
1055
1056 // Also, we want all globals initializers to go into the entry of main(), before
1057 // anything else gets there, so visit out of order, doing them all now.
1058 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1059
1060 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1061 // so do them manually.
1062 visitFunctions(node->getAsAggregate()->getSequence());
1063
1064 return false;
1065 }
1066
1067 return true;
1068 }
1069 case glslang::EOpLinkerObjects:
1070 {
1071 if (visit == glslang::EvPreVisit)
1072 linkageOnly = true;
1073 else
1074 linkageOnly = false;
1075
1076 return true;
1077 }
1078 case glslang::EOpComma:
1079 {
1080 // processing from left to right naturally leaves the right-most
1081 // lying around in the access chain
1082 glslang::TIntermSequence& glslangOperands = node->getSequence();
1083 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1084 glslangOperands[i]->traverse(this);
1085
1086 return false;
1087 }
1088 case glslang::EOpFunction:
1089 if (visit == glslang::EvPreVisit) {
1090 if (isShaderEntrypoint(node)) {
1091 inMain = true;
1092 builder.setBuildPoint(shaderEntry->getLastBlock());
1093 } else {
1094 handleFunctionEntry(node);
1095 }
1096 } else {
1097 if (inMain)
1098 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001099 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001100 inMain = false;
1101 }
1102
1103 return true;
1104 case glslang::EOpParameters:
1105 // Parameters will have been consumed by EOpFunction processing, but not
1106 // the body, so we still visited the function node's children, making this
1107 // child redundant.
1108 return false;
1109 case glslang::EOpFunctionCall:
1110 {
1111 if (node->isUserDefined())
1112 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001113 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001114 builder.clearAccessChain();
1115 builder.setAccessChainRValue(result);
1116
1117 return false;
1118 }
1119 case glslang::EOpConstructMat2x2:
1120 case glslang::EOpConstructMat2x3:
1121 case glslang::EOpConstructMat2x4:
1122 case glslang::EOpConstructMat3x2:
1123 case glslang::EOpConstructMat3x3:
1124 case glslang::EOpConstructMat3x4:
1125 case glslang::EOpConstructMat4x2:
1126 case glslang::EOpConstructMat4x3:
1127 case glslang::EOpConstructMat4x4:
1128 case glslang::EOpConstructDMat2x2:
1129 case glslang::EOpConstructDMat2x3:
1130 case glslang::EOpConstructDMat2x4:
1131 case glslang::EOpConstructDMat3x2:
1132 case glslang::EOpConstructDMat3x3:
1133 case glslang::EOpConstructDMat3x4:
1134 case glslang::EOpConstructDMat4x2:
1135 case glslang::EOpConstructDMat4x3:
1136 case glslang::EOpConstructDMat4x4:
1137 isMatrix = true;
1138 // fall through
1139 case glslang::EOpConstructFloat:
1140 case glslang::EOpConstructVec2:
1141 case glslang::EOpConstructVec3:
1142 case glslang::EOpConstructVec4:
1143 case glslang::EOpConstructDouble:
1144 case glslang::EOpConstructDVec2:
1145 case glslang::EOpConstructDVec3:
1146 case glslang::EOpConstructDVec4:
1147 case glslang::EOpConstructBool:
1148 case glslang::EOpConstructBVec2:
1149 case glslang::EOpConstructBVec3:
1150 case glslang::EOpConstructBVec4:
1151 case glslang::EOpConstructInt:
1152 case glslang::EOpConstructIVec2:
1153 case glslang::EOpConstructIVec3:
1154 case glslang::EOpConstructIVec4:
1155 case glslang::EOpConstructUint:
1156 case glslang::EOpConstructUVec2:
1157 case glslang::EOpConstructUVec3:
1158 case glslang::EOpConstructUVec4:
1159 case glslang::EOpConstructStruct:
1160 {
1161 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001162 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001163 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1164 spv::Id constructed;
1165 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1166 std::vector<spv::Id> constituents;
1167 for (int c = 0; c < (int)arguments.size(); ++c)
1168 constituents.push_back(arguments[c]);
1169 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001170 } else if (isMatrix)
1171 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1172 else
1173 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001174
1175 builder.clearAccessChain();
1176 builder.setAccessChainRValue(constructed);
1177
1178 return false;
1179 }
1180
1181 // These six are component-wise compares with component-wise results.
1182 // Forward on to createBinaryOperation(), requesting a vector result.
1183 case glslang::EOpLessThan:
1184 case glslang::EOpGreaterThan:
1185 case glslang::EOpLessThanEqual:
1186 case glslang::EOpGreaterThanEqual:
1187 case glslang::EOpVectorEqual:
1188 case glslang::EOpVectorNotEqual:
1189 {
1190 // Map the operation to a binary
1191 binOp = node->getOp();
1192 reduceComparison = false;
1193 switch (node->getOp()) {
1194 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1195 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1196 default: binOp = node->getOp(); break;
1197 }
1198
1199 break;
1200 }
1201 case glslang::EOpMul:
1202 // compontent-wise matrix multiply
1203 binOp = glslang::EOpMul;
1204 break;
1205 case glslang::EOpOuterProduct:
1206 // two vectors multiplied to make a matrix
1207 binOp = glslang::EOpOuterProduct;
1208 break;
1209 case glslang::EOpDot:
1210 {
1211 // for scalar dot product, use multiply
1212 glslang::TIntermSequence& glslangOperands = node->getSequence();
1213 if (! glslangOperands[0]->getAsTyped()->isVector())
1214 binOp = glslang::EOpMul;
1215 break;
1216 }
1217 case glslang::EOpMod:
1218 // when an aggregate, this is the floating-point mod built-in function,
1219 // which can be emitted by the one in createBinaryOperation()
1220 binOp = glslang::EOpMod;
1221 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001222 case glslang::EOpEmitVertex:
1223 case glslang::EOpEndPrimitive:
1224 case glslang::EOpBarrier:
1225 case glslang::EOpMemoryBarrier:
1226 case glslang::EOpMemoryBarrierAtomicCounter:
1227 case glslang::EOpMemoryBarrierBuffer:
1228 case glslang::EOpMemoryBarrierImage:
1229 case glslang::EOpMemoryBarrierShared:
1230 case glslang::EOpGroupMemoryBarrier:
1231 noReturnValue = true;
1232 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1233 break;
1234
John Kessenich426394d2015-07-23 10:22:48 -06001235 case glslang::EOpAtomicAdd:
1236 case glslang::EOpAtomicMin:
1237 case glslang::EOpAtomicMax:
1238 case glslang::EOpAtomicAnd:
1239 case glslang::EOpAtomicOr:
1240 case glslang::EOpAtomicXor:
1241 case glslang::EOpAtomicExchange:
1242 case glslang::EOpAtomicCompSwap:
1243 atomic = true;
1244 break;
1245
John Kessenich140f3df2015-06-26 16:58:36 -06001246 default:
1247 break;
1248 }
1249
1250 //
1251 // See if it maps to a regular operation.
1252 //
John Kessenich140f3df2015-06-26 16:58:36 -06001253 if (binOp != glslang::EOpNull) {
1254 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1255 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1256 assert(left && right);
1257
1258 builder.clearAccessChain();
1259 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001260 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001261
1262 builder.clearAccessChain();
1263 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001264 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001265
1266 result = createBinaryOperation(binOp, precision,
1267 convertGlslangToSpvType(node->getType()), leftId, rightId,
1268 left->getType().getBasicType(), reduceComparison);
1269
1270 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001271 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001272 builder.clearAccessChain();
1273 builder.setAccessChainRValue(result);
1274
1275 return false;
1276 }
1277
John Kessenich426394d2015-07-23 10:22:48 -06001278 //
1279 // Create the list of operands.
1280 //
John Kessenich140f3df2015-06-26 16:58:36 -06001281 glslang::TIntermSequence& glslangOperands = node->getSequence();
1282 std::vector<spv::Id> operands;
1283 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1284 builder.clearAccessChain();
1285 glslangOperands[arg]->traverse(this);
1286
1287 // special case l-value operands; there are just a few
1288 bool lvalue = false;
1289 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001290 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001291 case glslang::EOpModf:
1292 if (arg == 1)
1293 lvalue = true;
1294 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001295 case glslang::EOpInterpolateAtSample:
1296 case glslang::EOpInterpolateAtOffset:
1297 if (arg == 0)
1298 lvalue = true;
1299 break;
Rex Xud4782c12015-09-06 16:30:11 +08001300 case glslang::EOpAtomicAdd:
1301 case glslang::EOpAtomicMin:
1302 case glslang::EOpAtomicMax:
1303 case glslang::EOpAtomicAnd:
1304 case glslang::EOpAtomicOr:
1305 case glslang::EOpAtomicXor:
1306 case glslang::EOpAtomicExchange:
1307 case glslang::EOpAtomicCompSwap:
1308 if (arg == 0)
1309 lvalue = true;
1310 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001311 case glslang::EOpAddCarry:
1312 case glslang::EOpSubBorrow:
1313 if (arg == 2)
1314 lvalue = true;
1315 break;
1316 case glslang::EOpUMulExtended:
1317 case glslang::EOpIMulExtended:
1318 if (arg >= 2)
1319 lvalue = true;
1320 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001321 default:
1322 break;
1323 }
1324 if (lvalue)
1325 operands.push_back(builder.accessChainGetLValue());
1326 else
John Kessenich32cfd492016-02-02 12:37:46 -07001327 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001328 }
John Kessenich426394d2015-07-23 10:22:48 -06001329
1330 if (atomic) {
1331 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001332 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001333 } else {
1334 // Pass through to generic operations.
1335 switch (glslangOperands.size()) {
1336 case 0:
1337 result = createNoArgOperation(node->getOp());
1338 break;
1339 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001340 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001341 break;
1342 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001343 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001344 break;
1345 }
John Kessenich140f3df2015-06-26 16:58:36 -06001346 }
1347
1348 if (noReturnValue)
1349 return false;
1350
1351 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001352 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001353 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001354 } else {
1355 builder.clearAccessChain();
1356 builder.setAccessChainRValue(result);
1357 return false;
1358 }
1359}
1360
1361bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1362{
1363 // This path handles both if-then-else and ?:
1364 // The if-then-else has a node type of void, while
1365 // ?: has a non-void node type
1366 spv::Id result = 0;
1367 if (node->getBasicType() != glslang::EbtVoid) {
1368 // don't handle this as just on-the-fly temporaries, because there will be two names
1369 // and better to leave SSA to later passes
1370 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1371 }
1372
1373 // emit the condition before doing anything with selection
1374 node->getCondition()->traverse(this);
1375
1376 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001377 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001378
1379 if (node->getTrueBlock()) {
1380 // emit the "then" statement
1381 node->getTrueBlock()->traverse(this);
1382 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001383 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001384 }
1385
1386 if (node->getFalseBlock()) {
1387 ifBuilder.makeBeginElse();
1388 // emit the "else" statement
1389 node->getFalseBlock()->traverse(this);
1390 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001391 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001392 }
1393
1394 ifBuilder.makeEndIf();
1395
1396 if (result) {
1397 // GLSL only has r-values as the result of a :?, but
1398 // if we have an l-value, that can be more efficient if it will
1399 // become the base of a complex r-value expression, because the
1400 // next layer copies r-values into memory to use the access-chain mechanism
1401 builder.clearAccessChain();
1402 builder.setAccessChainLValue(result);
1403 }
1404
1405 return false;
1406}
1407
1408bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1409{
1410 // emit and get the condition before doing anything with switch
1411 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001412 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001413
1414 // browse the children to sort out code segments
1415 int defaultSegment = -1;
1416 std::vector<TIntermNode*> codeSegments;
1417 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1418 std::vector<int> caseValues;
1419 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1420 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1421 TIntermNode* child = *c;
1422 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001423 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001424 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001425 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001426 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1427 } else
1428 codeSegments.push_back(child);
1429 }
1430
1431 // handle the case where the last code segment is missing, due to no code
1432 // statements between the last case and the end of the switch statement
1433 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1434 (int)codeSegments.size() == defaultSegment)
1435 codeSegments.push_back(nullptr);
1436
1437 // make the switch statement
1438 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001439 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001440
1441 // emit all the code in the segments
1442 breakForLoop.push(false);
1443 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1444 builder.nextSwitchSegment(segmentBlocks, s);
1445 if (codeSegments[s])
1446 codeSegments[s]->traverse(this);
1447 else
1448 builder.addSwitchBreak();
1449 }
1450 breakForLoop.pop();
1451
1452 builder.endSwitch(segmentBlocks);
1453
1454 return false;
1455}
1456
1457void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1458{
1459 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001460 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001461
1462 builder.clearAccessChain();
1463 builder.setAccessChainRValue(constant);
1464}
1465
1466bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1467{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001468 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001469 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001470 // Spec requires back edges to target header blocks, and every header block
1471 // must dominate its merge block. Make a header block first to ensure these
1472 // conditions are met. By definition, it will contain OpLoopMerge, followed
1473 // by a block-ending branch. But we don't want to put any other body/test
1474 // instructions in it, since the body/test may have arbitrary instructions,
1475 // including merges of its own.
1476 builder.setBuildPoint(&blocks.head);
1477 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001478 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001479 spv::Block& test = builder.makeNewBlock();
1480 builder.createBranch(&test);
1481
1482 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001483 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001484 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001485 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001486 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1487
1488 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001489 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001490 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001491 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001492 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001493 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001494
1495 builder.setBuildPoint(&blocks.continue_target);
1496 if (node->getTerminal())
1497 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001498 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001499 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001500 builder.createBranch(&blocks.body);
1501
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001502 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001503 builder.setBuildPoint(&blocks.body);
1504 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001505 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001506 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001507 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001508
1509 builder.setBuildPoint(&blocks.continue_target);
1510 if (node->getTerminal())
1511 node->getTerminal()->traverse(this);
1512 if (node->getTest()) {
1513 node->getTest()->traverse(this);
1514 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001515 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001516 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001517 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001518 // TODO: unless there was a break/return/discard instruction
1519 // somewhere in the body, this is an infinite loop, so we should
1520 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001521 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001522 }
John Kessenich140f3df2015-06-26 16:58:36 -06001523 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001524 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001525 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001526 return false;
1527}
1528
1529bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1530{
1531 if (node->getExpression())
1532 node->getExpression()->traverse(this);
1533
1534 switch (node->getFlowOp()) {
1535 case glslang::EOpKill:
1536 builder.makeDiscard();
1537 break;
1538 case glslang::EOpBreak:
1539 if (breakForLoop.top())
1540 builder.createLoopExit();
1541 else
1542 builder.addSwitchBreak();
1543 break;
1544 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001545 builder.createLoopContinue();
1546 break;
1547 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001548 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001549 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001550 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001551 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001552
1553 builder.clearAccessChain();
1554 break;
1555
1556 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001557 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001558 break;
1559 }
1560
1561 return false;
1562}
1563
1564spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1565{
1566 // First, steer off constants, which are not SPIR-V variables, but
1567 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001568 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001569 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001570 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001571 }
1572
1573 // Now, handle actual variables
1574 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1575 spv::Id spvType = convertGlslangToSpvType(node->getType());
1576
1577 const char* name = node->getName().c_str();
1578 if (glslang::IsAnonymous(name))
1579 name = "";
1580
1581 return builder.createVariable(storageClass, spvType, name);
1582}
1583
1584// Return type Id of the sampled type.
1585spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1586{
1587 switch (sampler.type) {
1588 case glslang::EbtFloat: return builder.makeFloatType(32);
1589 case glslang::EbtInt: return builder.makeIntType(32);
1590 case glslang::EbtUint: return builder.makeUintType(32);
1591 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001592 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001593 return builder.makeFloatType(32);
1594 }
1595}
1596
John Kessenich3ac051e2015-12-20 11:29:16 -07001597// Convert from a glslang type to an SPV type, by calling into a
1598// recursive version of this function. This establishes the inherited
1599// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001600spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1601{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001602 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001603}
1604
1605// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001606// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001607spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001608{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001609 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001610
1611 switch (type.getBasicType()) {
1612 case glslang::EbtVoid:
1613 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001614 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001615 break;
1616 case glslang::EbtFloat:
1617 spvType = builder.makeFloatType(32);
1618 break;
1619 case glslang::EbtDouble:
1620 spvType = builder.makeFloatType(64);
1621 break;
1622 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001623 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1624 // a 32-bit int where non-0 means true.
1625 if (explicitLayout != glslang::ElpNone)
1626 spvType = builder.makeUintType(32);
1627 else
1628 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001629 break;
1630 case glslang::EbtInt:
1631 spvType = builder.makeIntType(32);
1632 break;
1633 case glslang::EbtUint:
1634 spvType = builder.makeUintType(32);
1635 break;
John Kessenich426394d2015-07-23 10:22:48 -06001636 case glslang::EbtAtomicUint:
1637 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1638 spvType = builder.makeUintType(32);
1639 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001640 case glslang::EbtSampler:
1641 {
1642 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001643 // an image is present, make its type
1644 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1645 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001646 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001647 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001648 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001649 }
John Kessenich140f3df2015-06-26 16:58:36 -06001650 break;
1651 case glslang::EbtStruct:
1652 case glslang::EbtBlock:
1653 {
1654 // If we've seen this struct type, return it
1655 const glslang::TTypeList* glslangStruct = type.getStruct();
1656 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001657
1658 // Try to share structs for different layouts, but not yet for other
1659 // kinds of qualification (primarily not yet including interpolant qualification).
1660 if (! HasNonLayoutQualifiers(qualifier))
1661 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1662 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001663 break;
1664
1665 // else, we haven't seen it...
1666
1667 // Create a vector of struct types for SPIR-V to consume
1668 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1669 if (type.getBasicType() == glslang::EbtBlock)
1670 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001671 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001672 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1673 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1674 if (glslangType.hiddenMember()) {
1675 ++memberDelta;
1676 if (type.getBasicType() == glslang::EbtBlock)
1677 memberRemapper[glslangStruct][i] = -1;
1678 } else {
1679 if (type.getBasicType() == glslang::EbtBlock)
1680 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001681 // modify just this child's view of the qualifier
1682 glslang::TQualifier subQualifier = glslangType.getQualifier();
1683 InheritQualifiers(subQualifier, qualifier);
John Kessenich7b9fa252016-01-21 18:56:57 -07001684 if (qualifier.hasLocation()) {
1685 subQualifier.layoutLocation += locationOffset;
1686 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1687 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001688 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001689 }
1690 }
1691
1692 // Make the SPIR-V type
1693 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001694 if (! HasNonLayoutQualifiers(qualifier))
1695 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001696
1697 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001698 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001699 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001700 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1701 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1702 int member = i;
1703 if (type.getBasicType() == glslang::EbtBlock)
1704 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001705
John Kesseniche0b6cad2015-12-24 10:30:13 -07001706 // modify just this child's view of the qualifier
1707 glslang::TQualifier subQualifier = glslangType.getQualifier();
1708 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001709
John Kessenich140f3df2015-06-26 16:58:36 -06001710 // using -1 above to indicate a hidden member
1711 if (member >= 0) {
1712 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001713 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001714 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001715 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1716 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich7b9fa252016-01-21 18:56:57 -07001717 if (qualifier.hasLocation()) {
1718 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, qualifier.layoutLocation + locationOffset);
1719 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1720 }
John Kessenich140f3df2015-06-26 16:58:36 -06001721 if (glslangType.getQualifier().hasComponent())
1722 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1723 if (glslangType.getQualifier().hasXfbOffset())
1724 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001725 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001726 // figure out what to do with offset, which is accumulating
1727 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001728 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001729 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001730 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001731 offset = nextOffset;
1732 }
John Kessenich140f3df2015-06-26 16:58:36 -06001733
John Kessenichf85e8062015-12-19 13:57:10 -07001734 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001735 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001736
John Kessenich140f3df2015-06-26 16:58:36 -06001737 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001738 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1739 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001740 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001741 }
1742 }
1743
1744 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001745 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001746 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001747 if (type.getQualifier().hasStream()) {
1748 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001749 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001750 }
John Kessenich140f3df2015-06-26 16:58:36 -06001751 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001752 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001753 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001754 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001755 if (type.getQualifier().hasXfbBuffer())
1756 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1757 }
1758 }
1759 break;
1760 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001761 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001762 break;
1763 }
1764
1765 if (type.isMatrix())
1766 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1767 else {
1768 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1769 if (type.getVectorSize() > 1)
1770 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1771 }
1772
1773 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001774 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1775
John Kessenichc9a80832015-09-12 12:17:44 -06001776 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001777 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001778 // We need to decorate array strides for types needing explicit layout, except blocks.
1779 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001780 // Use a dummy glslang type for querying internal strides of
1781 // arrays of arrays, but using just a one-dimensional array.
1782 glslang::TType simpleArrayType(type, 0); // deference type of the array
1783 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1784 simpleArrayType.getArraySizes().dereference();
1785
1786 // Will compute the higher-order strides here, rather than making a whole
1787 // pile of types and doing repetitive recursion on their contents.
1788 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1789 }
John Kessenichf8842e52016-01-04 19:22:56 -07001790
1791 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001792 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1793 int size = type.getArraySizes()->getDimSize(dim);
1794 assert(size > 0);
1795 spvType = builder.makeArrayType(spvType, size, stride);
1796 if (stride > 0)
1797 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1798 stride *= size;
1799 }
1800 } else {
1801 // single-dimensional array, and don't yet have stride
1802
John Kessenichf8842e52016-01-04 19:22:56 -07001803 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001804 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1805 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001806 }
John Kessenich31ed4832015-09-09 17:51:38 -06001807
John Kessenichc9a80832015-09-12 12:17:44 -06001808 // Do the outer dimension, which might not be known for a runtime-sized array
1809 if (type.isRuntimeSizedArray()) {
1810 spvType = builder.makeRuntimeArray(spvType);
1811 } else {
1812 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001813 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001814 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001815 if (stride > 0)
1816 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001817 }
1818
1819 return spvType;
1820}
1821
John Kessenich103bef92016-02-08 21:38:15 -07001822// Wrap the builder's accessChainLoad to:
1823// - localize handling of RelaxedPrecision
1824// - use the SPIR-V inferred type instead of another conversion of the glslang type
1825// (avoids unnecessary work and possible type punning for structures)
1826// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001827spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1828{
John Kessenich103bef92016-02-08 21:38:15 -07001829 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1830 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1831
1832 // Need to convert to abstract types when necessary
1833 if (builder.isScalarType(nominalTypeId) && type.getBasicType() == glslang::EbtBool && nominalTypeId != builder.makeBoolType())
1834 loadedId = builder.createBinOp(spv::OpINotEqual, builder.makeBoolType(), loadedId, builder.makeUintConstant(0));
1835
1836 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001837}
1838
John Kessenichf85e8062015-12-19 13:57:10 -07001839// Decide whether or not this type should be
1840// decorated with offsets and strides, and if so
1841// whether std140 or std430 rules should be applied.
1842glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001843{
John Kessenichf85e8062015-12-19 13:57:10 -07001844 // has to be a block
1845 if (type.getBasicType() != glslang::EbtBlock)
1846 return glslang::ElpNone;
1847
1848 // has to be a uniform or buffer block
1849 if (type.getQualifier().storage != glslang::EvqUniform &&
1850 type.getQualifier().storage != glslang::EvqBuffer)
1851 return glslang::ElpNone;
1852
1853 // return the layout to use
1854 switch (type.getQualifier().layoutPacking) {
1855 case glslang::ElpStd140:
1856 case glslang::ElpStd430:
1857 return type.getQualifier().layoutPacking;
1858 default:
1859 return glslang::ElpNone;
1860 }
John Kessenich31ed4832015-09-09 17:51:38 -06001861}
1862
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001863// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001864int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001865{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001866 int size;
John Kessenich49987892015-12-29 17:11:44 -07001867 int stride;
1868 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001869
1870 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001871}
1872
John Kessenich49987892015-12-29 17:11:44 -07001873// 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 -07001874// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001875int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001876{
John Kessenich49987892015-12-29 17:11:44 -07001877 glslang::TType elementType;
1878 elementType.shallowCopy(matrixType);
1879 elementType.clearArraySizes();
1880
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001881 int size;
John Kessenich49987892015-12-29 17:11:44 -07001882 int stride;
1883 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1884
1885 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001886}
1887
John Kessenich5e4b1242015-08-06 22:53:06 -06001888// Given a member type of a struct, realign the current offset for it, and compute
1889// the next (not yet aligned) offset for the next member, which will get aligned
1890// on the next call.
1891// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1892// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1893// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001894void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001895 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001896{
1897 // this will get a positive value when deemed necessary
1898 nextOffset = -1;
1899
John Kessenich5e4b1242015-08-06 22:53:06 -06001900 // override anything in currentOffset with user-set offset
1901 if (memberType.getQualifier().hasOffset())
1902 currentOffset = memberType.getQualifier().layoutOffset;
1903
1904 // It could be that current linker usage in glslang updated all the layoutOffset,
1905 // in which case the following code does not matter. But, that's not quite right
1906 // once cross-compilation unit GLSL validation is done, as the original user
1907 // settings are needed in layoutOffset, and then the following will come into play.
1908
John Kessenichf85e8062015-12-19 13:57:10 -07001909 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001910 if (! memberType.getQualifier().hasOffset())
1911 currentOffset = -1;
1912
1913 return;
1914 }
1915
John Kessenichf85e8062015-12-19 13:57:10 -07001916 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001917 if (currentOffset < 0)
1918 currentOffset = 0;
1919
1920 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1921 // but possibly not yet correctly aligned.
1922
1923 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001924 int dummyStride;
1925 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001926 glslang::RoundToPow2(currentOffset, memberAlignment);
1927 nextOffset = currentOffset + memberSize;
1928}
1929
John Kessenich140f3df2015-06-26 16:58:36 -06001930bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1931{
1932 return node->getName() == "main(";
1933}
1934
1935// Make all the functions, skeletally, without actually visiting their bodies.
1936void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1937{
1938 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1939 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1940 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1941 continue;
1942
1943 // We're on a user function. Set up the basic interface for the function now,
1944 // so that it's available to call.
1945 // Translating the body will happen later.
1946 //
1947 // Typically (except for a "const in" parameter), an address will be passed to the
1948 // function. What it is an address of varies:
1949 //
1950 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1951 // so that write needs to be to a copy, hence the address of a copy works.
1952 //
1953 // - "const in" parameters can just be the r-value, as no writes need occur.
1954 //
1955 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1956 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1957
1958 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07001959 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06001960 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1961
1962 for (int p = 0; p < (int)parameters.size(); ++p) {
1963 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1964 spv::Id typeId = convertGlslangToSpvType(paramType);
1965 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1966 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1967 else
1968 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07001969 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06001970 paramTypes.push_back(typeId);
1971 }
1972
1973 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07001974 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
1975 convertGlslangToSpvType(glslFunction->getType()),
1976 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06001977
1978 // Track function to emit/call later
1979 functionMap[glslFunction->getName().c_str()] = function;
1980
1981 // Set the parameter id's
1982 for (int p = 0; p < (int)parameters.size(); ++p) {
1983 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1984 // give a name too
1985 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1986 }
1987 }
1988}
1989
1990// Process all the initializers, while skipping the functions and link objects
1991void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1992{
1993 builder.setBuildPoint(shaderEntry->getLastBlock());
1994 for (int i = 0; i < (int)initializers.size(); ++i) {
1995 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1996 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1997
1998 // We're on a top-level node that's not a function. Treat as an initializer, whose
1999 // code goes into the beginning of main.
2000 initializer->traverse(this);
2001 }
2002 }
2003}
2004
2005// Process all the functions, while skipping initializers.
2006void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2007{
2008 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2009 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2010 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2011 node->traverse(this);
2012 }
2013}
2014
2015void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2016{
2017 // SPIR-V functions should already be in the functionMap from the prepass
2018 // that called makeFunctions().
2019 spv::Function* function = functionMap[node->getName().c_str()];
2020 spv::Block* functionBlock = function->getEntryBlock();
2021 builder.setBuildPoint(functionBlock);
2022}
2023
Rex Xu04db3f52015-09-16 11:44:02 +08002024void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002025{
Rex Xufc618912015-09-09 16:42:49 +08002026 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002027
2028 glslang::TSampler sampler = {};
2029 bool cubeCompare = false;
2030 if (node.isTexture()) {
2031 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2032 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2033 }
2034
John Kessenich140f3df2015-06-26 16:58:36 -06002035 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2036 builder.clearAccessChain();
2037 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002038
2039 // Special case l-value operands
2040 bool lvalue = false;
2041 switch (node.getOp()) {
2042 case glslang::EOpImageAtomicAdd:
2043 case glslang::EOpImageAtomicMin:
2044 case glslang::EOpImageAtomicMax:
2045 case glslang::EOpImageAtomicAnd:
2046 case glslang::EOpImageAtomicOr:
2047 case glslang::EOpImageAtomicXor:
2048 case glslang::EOpImageAtomicExchange:
2049 case glslang::EOpImageAtomicCompSwap:
2050 if (i == 0)
2051 lvalue = true;
2052 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002053 case glslang::EOpSparseTexture:
2054 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2055 lvalue = true;
2056 break;
2057 case glslang::EOpSparseTextureClamp:
2058 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2059 lvalue = true;
2060 break;
2061 case glslang::EOpSparseTextureLod:
2062 case glslang::EOpSparseTextureOffset:
2063 if (i == 3)
2064 lvalue = true;
2065 break;
2066 case glslang::EOpSparseTextureFetch:
2067 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2068 lvalue = true;
2069 break;
2070 case glslang::EOpSparseTextureFetchOffset:
2071 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2072 lvalue = true;
2073 break;
2074 case glslang::EOpSparseTextureLodOffset:
2075 case glslang::EOpSparseTextureGrad:
2076 case glslang::EOpSparseTextureOffsetClamp:
2077 if (i == 4)
2078 lvalue = true;
2079 break;
2080 case glslang::EOpSparseTextureGradOffset:
2081 case glslang::EOpSparseTextureGradClamp:
2082 if (i == 5)
2083 lvalue = true;
2084 break;
2085 case glslang::EOpSparseTextureGradOffsetClamp:
2086 if (i == 6)
2087 lvalue = true;
2088 break;
2089 case glslang::EOpSparseTextureGather:
2090 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2091 lvalue = true;
2092 break;
2093 case glslang::EOpSparseTextureGatherOffset:
2094 case glslang::EOpSparseTextureGatherOffsets:
2095 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2096 lvalue = true;
2097 break;
Rex Xufc618912015-09-09 16:42:49 +08002098 default:
2099 break;
2100 }
2101
Rex Xu6b86d492015-09-16 17:48:22 +08002102 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002103 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002104 else
John Kessenich32cfd492016-02-02 12:37:46 -07002105 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002106 }
2107}
2108
John Kessenichfc51d282015-08-19 13:34:18 -06002109void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002110{
John Kessenichfc51d282015-08-19 13:34:18 -06002111 builder.clearAccessChain();
2112 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002113 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002114}
John Kessenich140f3df2015-06-26 16:58:36 -06002115
John Kessenichfc51d282015-08-19 13:34:18 -06002116spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2117{
Rex Xufc618912015-09-09 16:42:49 +08002118 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002119 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002120 }
2121
John Kessenichfc51d282015-08-19 13:34:18 -06002122 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002123 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2124 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2125 std::vector<spv::Id> arguments;
2126 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002127 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002128 else
2129 translateArguments(*node->getAsUnaryNode(), arguments);
2130 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2131
2132 spv::Builder::TextureParameters params = { };
2133 params.sampler = arguments[0];
2134
Rex Xu04db3f52015-09-16 11:44:02 +08002135 glslang::TCrackedTextureOp cracked;
2136 node->crackTexture(sampler, cracked);
2137
John Kessenichfc51d282015-08-19 13:34:18 -06002138 // Check for queries
2139 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002140 // a sampled image needs to have the image extracted first
2141 if (builder.isSampledImage(params.sampler))
2142 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002143 switch (node->getOp()) {
2144 case glslang::EOpImageQuerySize:
2145 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002146 if (arguments.size() > 1) {
2147 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002148 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002149 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002150 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002151 case glslang::EOpImageQuerySamples:
2152 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002153 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002154 case glslang::EOpTextureQueryLod:
2155 params.coords = arguments[1];
2156 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2157 case glslang::EOpTextureQueryLevels:
2158 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002159 case glslang::EOpSparseTexelsResident:
2160 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002161 default:
2162 assert(0);
2163 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002164 }
John Kessenich140f3df2015-06-26 16:58:36 -06002165 }
2166
Rex Xufc618912015-09-09 16:42:49 +08002167 // Check for image functions other than queries
2168 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002169 std::vector<spv::Id> operands;
2170 auto opIt = arguments.begin();
2171 operands.push_back(*(opIt++));
2172 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002173 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002174 if (sampler.ms) {
2175 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002176 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002177 }
John Kessenich56bab042015-09-16 10:54:31 -06002178 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002179 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2180 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002181 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002182 if (sampler.ms) {
2183 operands.push_back(*(opIt + 1));
2184 operands.push_back(spv::ImageOperandsSampleMask);
2185 operands.push_back(*opIt);
2186 } else
2187 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002188 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002189 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2190 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002191 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002192 } else if (node->isSparseImage()) {
2193 spv::MissingFunctionality("sparse image functions");
2194 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002195 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002196 // Process image atomic operations
2197
2198 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2199 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002200 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002201
Rex Xufc618912015-09-09 16:42:49 +08002202 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002203 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002204
2205 std::vector<spv::Id> operands;
2206 operands.push_back(pointer);
2207 for (; opIt != arguments.end(); ++opIt)
2208 operands.push_back(*opIt);
2209
Rex Xu04db3f52015-09-16 11:44:02 +08002210 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002211 }
2212 }
2213
2214 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002215 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002216 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2217
John Kessenichfc51d282015-08-19 13:34:18 -06002218 // check for bias argument
2219 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002220 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002221 int nonBiasArgCount = 2;
2222 if (cracked.offset)
2223 ++nonBiasArgCount;
2224 if (cracked.grad)
2225 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002226 if (cracked.lodClamp)
2227 ++nonBiasArgCount;
2228 if (sparse)
2229 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002230
2231 if ((int)arguments.size() > nonBiasArgCount)
2232 bias = true;
2233 }
2234
John Kessenichfc51d282015-08-19 13:34:18 -06002235 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002236
John Kessenichfc51d282015-08-19 13:34:18 -06002237 params.coords = arguments[1];
2238 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002239 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002240
2241 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002242 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002243 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002244 ++extraArgs;
2245 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002246 params.Dref = arguments[2];
2247 ++extraArgs;
2248 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002249 std::vector<spv::Id> indexes;
2250 int comp;
2251 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002252 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002253 else
2254 comp = builder.getNumComponents(params.coords) - 1;
2255 indexes.push_back(comp);
2256 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2257 }
2258 if (cracked.lod) {
2259 params.lod = arguments[2];
2260 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002261 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2262 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2263 noImplicitLod = true;
2264 }
2265 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002266 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002267 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002268 }
2269 if (cracked.grad) {
2270 params.gradX = arguments[2 + extraArgs];
2271 params.gradY = arguments[3 + extraArgs];
2272 extraArgs += 2;
2273 }
John Kessenich55e7d112015-11-15 21:33:39 -07002274 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002275 params.offset = arguments[2 + extraArgs];
2276 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002277 } else if (cracked.offsets) {
2278 params.offsets = arguments[2 + extraArgs];
2279 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002280 }
Rex Xu48edadf2015-12-31 16:11:41 +08002281 if (cracked.lodClamp) {
2282 params.lodClamp = arguments[2 + extraArgs];
2283 ++extraArgs;
2284 }
2285 if (sparse) {
2286 params.texelOut = arguments[2 + extraArgs];
2287 ++extraArgs;
2288 }
John Kessenichfc51d282015-08-19 13:34:18 -06002289 if (bias) {
2290 params.bias = arguments[2 + extraArgs];
2291 ++extraArgs;
2292 }
John Kessenich55e7d112015-11-15 21:33:39 -07002293 if (cracked.gather && ! sampler.shadow) {
2294 // default component is 0, if missing, otherwise an argument
2295 if (2 + extraArgs < (int)arguments.size()) {
2296 params.comp = arguments[2 + extraArgs];
2297 ++extraArgs;
2298 } else {
2299 params.comp = builder.makeIntConstant(0);
2300 }
2301 }
John Kessenichfc51d282015-08-19 13:34:18 -06002302
John Kessenich019f08f2016-02-15 15:40:42 -07002303 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002304}
2305
2306spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2307{
2308 // Grab the function's pointer from the previously created function
2309 spv::Function* function = functionMap[node->getName().c_str()];
2310 if (! function)
2311 return 0;
2312
2313 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2314 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2315
2316 // See comments in makeFunctions() for details about the semantics for parameter passing.
2317 //
2318 // These imply we need a four step process:
2319 // 1. Evaluate the arguments
2320 // 2. Allocate and make copies of in, out, and inout arguments
2321 // 3. Make the call
2322 // 4. Copy back the results
2323
2324 // 1. Evaluate the arguments
2325 std::vector<spv::Builder::AccessChain> lValues;
2326 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002327 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002328 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2329 // build l-value
2330 builder.clearAccessChain();
2331 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002332 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002333 // keep outputs as l-values, evaluate input-only as r-values
2334 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2335 // save l-value
2336 lValues.push_back(builder.getAccessChain());
2337 } else {
2338 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002339 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002340 }
2341 }
2342
2343 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2344 // copy the original into that space.
2345 //
2346 // Also, build up the list of actual arguments to pass in for the call
2347 int lValueCount = 0;
2348 int rValueCount = 0;
2349 std::vector<spv::Id> spvArgs;
2350 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2351 spv::Id arg;
2352 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2353 // need space to hold the copy
2354 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2355 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2356 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2357 // need to copy the input into output space
2358 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002359 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002360 builder.createStore(copy, arg);
2361 }
2362 ++lValueCount;
2363 } else {
2364 arg = rValues[rValueCount];
2365 ++rValueCount;
2366 }
2367 spvArgs.push_back(arg);
2368 }
2369
2370 // 3. Make the call.
2371 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002372 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002373
2374 // 4. Copy back out an "out" arguments.
2375 lValueCount = 0;
2376 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2377 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2378 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2379 spv::Id copy = builder.createLoad(spvArgs[a]);
2380 builder.setAccessChain(lValues[lValueCount]);
2381 builder.accessChainStore(copy);
2382 }
2383 ++lValueCount;
2384 }
2385 }
2386
2387 return result;
2388}
2389
2390// Translate AST operation to SPV operation, already having SPV-based operands/types.
2391spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2392 spv::Id typeId, spv::Id left, spv::Id right,
2393 glslang::TBasicType typeProxy, bool reduceComparison)
2394{
2395 bool isUnsigned = typeProxy == glslang::EbtUint;
2396 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2397
2398 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002399 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002400 bool comparison = false;
2401
2402 switch (op) {
2403 case glslang::EOpAdd:
2404 case glslang::EOpAddAssign:
2405 if (isFloat)
2406 binOp = spv::OpFAdd;
2407 else
2408 binOp = spv::OpIAdd;
2409 break;
2410 case glslang::EOpSub:
2411 case glslang::EOpSubAssign:
2412 if (isFloat)
2413 binOp = spv::OpFSub;
2414 else
2415 binOp = spv::OpISub;
2416 break;
2417 case glslang::EOpMul:
2418 case glslang::EOpMulAssign:
2419 if (isFloat)
2420 binOp = spv::OpFMul;
2421 else
2422 binOp = spv::OpIMul;
2423 break;
2424 case glslang::EOpVectorTimesScalar:
2425 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002426 if (isFloat) {
2427 if (builder.isVector(right))
2428 std::swap(left, right);
2429 assert(builder.isScalar(right));
2430 needMatchingVectors = false;
2431 binOp = spv::OpVectorTimesScalar;
2432 } else
2433 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002434 break;
2435 case glslang::EOpVectorTimesMatrix:
2436 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002437 binOp = spv::OpVectorTimesMatrix;
2438 break;
2439 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002440 binOp = spv::OpMatrixTimesVector;
2441 break;
2442 case glslang::EOpMatrixTimesScalar:
2443 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002444 binOp = spv::OpMatrixTimesScalar;
2445 break;
2446 case glslang::EOpMatrixTimesMatrix:
2447 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002448 binOp = spv::OpMatrixTimesMatrix;
2449 break;
2450 case glslang::EOpOuterProduct:
2451 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002452 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002453 break;
2454
2455 case glslang::EOpDiv:
2456 case glslang::EOpDivAssign:
2457 if (isFloat)
2458 binOp = spv::OpFDiv;
2459 else if (isUnsigned)
2460 binOp = spv::OpUDiv;
2461 else
2462 binOp = spv::OpSDiv;
2463 break;
2464 case glslang::EOpMod:
2465 case glslang::EOpModAssign:
2466 if (isFloat)
2467 binOp = spv::OpFMod;
2468 else if (isUnsigned)
2469 binOp = spv::OpUMod;
2470 else
2471 binOp = spv::OpSMod;
2472 break;
2473 case glslang::EOpRightShift:
2474 case glslang::EOpRightShiftAssign:
2475 if (isUnsigned)
2476 binOp = spv::OpShiftRightLogical;
2477 else
2478 binOp = spv::OpShiftRightArithmetic;
2479 break;
2480 case glslang::EOpLeftShift:
2481 case glslang::EOpLeftShiftAssign:
2482 binOp = spv::OpShiftLeftLogical;
2483 break;
2484 case glslang::EOpAnd:
2485 case glslang::EOpAndAssign:
2486 binOp = spv::OpBitwiseAnd;
2487 break;
2488 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002489 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002490 binOp = spv::OpLogicalAnd;
2491 break;
2492 case glslang::EOpInclusiveOr:
2493 case glslang::EOpInclusiveOrAssign:
2494 binOp = spv::OpBitwiseOr;
2495 break;
2496 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002497 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002498 binOp = spv::OpLogicalOr;
2499 break;
2500 case glslang::EOpExclusiveOr:
2501 case glslang::EOpExclusiveOrAssign:
2502 binOp = spv::OpBitwiseXor;
2503 break;
2504 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002505 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002506 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002507 break;
2508
2509 case glslang::EOpLessThan:
2510 case glslang::EOpGreaterThan:
2511 case glslang::EOpLessThanEqual:
2512 case glslang::EOpGreaterThanEqual:
2513 case glslang::EOpEqual:
2514 case glslang::EOpNotEqual:
2515 case glslang::EOpVectorEqual:
2516 case glslang::EOpVectorNotEqual:
2517 comparison = true;
2518 break;
2519 default:
2520 break;
2521 }
2522
John Kessenich7c1aa102015-10-15 13:29:11 -06002523 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002524 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002525 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002526 if (builder.isMatrix(left) || builder.isMatrix(right))
2527 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002528
2529 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002530 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002531 builder.promoteScalar(precision, left, right);
2532
John Kessenich32cfd492016-02-02 12:37:46 -07002533 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002534 }
2535
2536 if (! comparison)
2537 return 0;
2538
John Kessenich7c1aa102015-10-15 13:29:11 -06002539 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002540
2541 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2542 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2543
John Kessenich22118352015-12-21 20:54:09 -07002544 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002545 }
2546
2547 switch (op) {
2548 case glslang::EOpLessThan:
2549 if (isFloat)
2550 binOp = spv::OpFOrdLessThan;
2551 else if (isUnsigned)
2552 binOp = spv::OpULessThan;
2553 else
2554 binOp = spv::OpSLessThan;
2555 break;
2556 case glslang::EOpGreaterThan:
2557 if (isFloat)
2558 binOp = spv::OpFOrdGreaterThan;
2559 else if (isUnsigned)
2560 binOp = spv::OpUGreaterThan;
2561 else
2562 binOp = spv::OpSGreaterThan;
2563 break;
2564 case glslang::EOpLessThanEqual:
2565 if (isFloat)
2566 binOp = spv::OpFOrdLessThanEqual;
2567 else if (isUnsigned)
2568 binOp = spv::OpULessThanEqual;
2569 else
2570 binOp = spv::OpSLessThanEqual;
2571 break;
2572 case glslang::EOpGreaterThanEqual:
2573 if (isFloat)
2574 binOp = spv::OpFOrdGreaterThanEqual;
2575 else if (isUnsigned)
2576 binOp = spv::OpUGreaterThanEqual;
2577 else
2578 binOp = spv::OpSGreaterThanEqual;
2579 break;
2580 case glslang::EOpEqual:
2581 case glslang::EOpVectorEqual:
2582 if (isFloat)
2583 binOp = spv::OpFOrdEqual;
2584 else
2585 binOp = spv::OpIEqual;
2586 break;
2587 case glslang::EOpNotEqual:
2588 case glslang::EOpVectorNotEqual:
2589 if (isFloat)
2590 binOp = spv::OpFOrdNotEqual;
2591 else
2592 binOp = spv::OpINotEqual;
2593 break;
2594 default:
2595 break;
2596 }
2597
John Kessenich32cfd492016-02-02 12:37:46 -07002598 if (binOp != spv::OpNop)
2599 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002600
2601 return 0;
2602}
2603
John Kessenich04bb8a02015-12-12 12:28:14 -07002604//
2605// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2606// These can be any of:
2607//
2608// matrix * scalar
2609// scalar * matrix
2610// matrix * matrix linear algebraic
2611// matrix * vector
2612// vector * matrix
2613// matrix * matrix componentwise
2614// matrix op matrix op in {+, -, /}
2615// matrix op scalar op in {+, -, /}
2616// scalar op matrix op in {+, -, /}
2617//
2618spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2619{
2620 bool firstClass = true;
2621
2622 // First, handle first-class matrix operations (* and matrix/scalar)
2623 switch (op) {
2624 case spv::OpFDiv:
2625 if (builder.isMatrix(left) && builder.isScalar(right)) {
2626 // turn matrix / scalar into a multiply...
2627 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2628 op = spv::OpMatrixTimesScalar;
2629 } else
2630 firstClass = false;
2631 break;
2632 case spv::OpMatrixTimesScalar:
2633 if (builder.isMatrix(right))
2634 std::swap(left, right);
2635 assert(builder.isScalar(right));
2636 break;
2637 case spv::OpVectorTimesMatrix:
2638 assert(builder.isVector(left));
2639 assert(builder.isMatrix(right));
2640 break;
2641 case spv::OpMatrixTimesVector:
2642 assert(builder.isMatrix(left));
2643 assert(builder.isVector(right));
2644 break;
2645 case spv::OpMatrixTimesMatrix:
2646 assert(builder.isMatrix(left));
2647 assert(builder.isMatrix(right));
2648 break;
2649 default:
2650 firstClass = false;
2651 break;
2652 }
2653
John Kessenich32cfd492016-02-02 12:37:46 -07002654 if (firstClass)
2655 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002656
2657 // Handle component-wise +, -, *, and / for all combinations of type.
2658 // The result type of all of them is the same type as the (a) matrix operand.
2659 // The algorithm is to:
2660 // - break the matrix(es) into vectors
2661 // - smear any scalar to a vector
2662 // - do vector operations
2663 // - make a matrix out the vector results
2664 switch (op) {
2665 case spv::OpFAdd:
2666 case spv::OpFSub:
2667 case spv::OpFDiv:
2668 case spv::OpFMul:
2669 {
2670 // one time set up...
2671 bool leftMat = builder.isMatrix(left);
2672 bool rightMat = builder.isMatrix(right);
2673 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2674 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2675 spv::Id scalarType = builder.getScalarTypeId(typeId);
2676 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2677 std::vector<spv::Id> results;
2678 spv::Id smearVec = spv::NoResult;
2679 if (builder.isScalar(left))
2680 smearVec = builder.smearScalar(precision, left, vecType);
2681 else if (builder.isScalar(right))
2682 smearVec = builder.smearScalar(precision, right, vecType);
2683
2684 // do each vector op
2685 for (unsigned int c = 0; c < numCols; ++c) {
2686 std::vector<unsigned int> indexes;
2687 indexes.push_back(c);
2688 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2689 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2690 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2691 builder.setPrecision(results.back(), precision);
2692 }
2693
2694 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002695 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002696 }
2697 default:
2698 assert(0);
2699 return spv::NoResult;
2700 }
2701}
2702
Rex Xu04db3f52015-09-16 11:44:02 +08002703spv::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 -06002704{
2705 spv::Op unaryOp = spv::OpNop;
2706 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002707 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002708 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002709
2710 switch (op) {
2711 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002712 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002713 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002714 if (builder.isMatrixType(typeId))
2715 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2716 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002717 unaryOp = spv::OpSNegate;
2718 break;
2719
2720 case glslang::EOpLogicalNot:
2721 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002722 unaryOp = spv::OpLogicalNot;
2723 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002724 case glslang::EOpBitwiseNot:
2725 unaryOp = spv::OpNot;
2726 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002727
John Kessenich140f3df2015-06-26 16:58:36 -06002728 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002729 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002730 break;
2731 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002732 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002733 break;
2734 case glslang::EOpTranspose:
2735 unaryOp = spv::OpTranspose;
2736 break;
2737
2738 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002739 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002740 break;
2741 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002742 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002743 break;
2744 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002745 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002746 break;
2747 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002748 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002749 break;
2750 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002751 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002752 break;
2753 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002754 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002755 break;
2756 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002757 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002758 break;
2759 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002760 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002761 break;
2762
2763 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002764 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002765 break;
2766 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002767 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002768 break;
2769 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002770 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002771 break;
2772 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002773 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002774 break;
2775 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002776 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002777 break;
2778 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002779 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002780 break;
2781
2782 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002783 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002784 break;
2785 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002786 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002787 break;
2788
2789 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002790 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002791 break;
2792 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002793 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002794 break;
2795 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002796 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002797 break;
2798 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002799 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002800 break;
2801 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002802 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002803 break;
2804 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002805 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002806 break;
2807
2808 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002809 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002810 break;
2811 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002812 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002813 break;
2814 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002815 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002816 break;
2817 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002818 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002819 break;
2820 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002821 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002822 break;
2823 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002824 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002825 break;
2826
2827 case glslang::EOpIsNan:
2828 unaryOp = spv::OpIsNan;
2829 break;
2830 case glslang::EOpIsInf:
2831 unaryOp = spv::OpIsInf;
2832 break;
2833
Rex Xucbc426e2015-12-15 16:03:10 +08002834 case glslang::EOpFloatBitsToInt:
2835 case glslang::EOpFloatBitsToUint:
2836 case glslang::EOpIntBitsToFloat:
2837 case glslang::EOpUintBitsToFloat:
2838 unaryOp = spv::OpBitcast;
2839 break;
2840
John Kessenich140f3df2015-06-26 16:58:36 -06002841 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002842 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002843 break;
2844 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002845 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002846 break;
2847 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002848 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002849 break;
2850 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002851 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002852 break;
2853 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002854 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002855 break;
2856 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002857 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002858 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002859 case glslang::EOpPackSnorm4x8:
2860 libCall = spv::GLSLstd450PackSnorm4x8;
2861 break;
2862 case glslang::EOpUnpackSnorm4x8:
2863 libCall = spv::GLSLstd450UnpackSnorm4x8;
2864 break;
2865 case glslang::EOpPackUnorm4x8:
2866 libCall = spv::GLSLstd450PackUnorm4x8;
2867 break;
2868 case glslang::EOpUnpackUnorm4x8:
2869 libCall = spv::GLSLstd450UnpackUnorm4x8;
2870 break;
2871 case glslang::EOpPackDouble2x32:
2872 libCall = spv::GLSLstd450PackDouble2x32;
2873 break;
2874 case glslang::EOpUnpackDouble2x32:
2875 libCall = spv::GLSLstd450UnpackDouble2x32;
2876 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002877
2878 case glslang::EOpDPdx:
2879 unaryOp = spv::OpDPdx;
2880 break;
2881 case glslang::EOpDPdy:
2882 unaryOp = spv::OpDPdy;
2883 break;
2884 case glslang::EOpFwidth:
2885 unaryOp = spv::OpFwidth;
2886 break;
2887 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07002888 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002889 unaryOp = spv::OpDPdxFine;
2890 break;
2891 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07002892 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002893 unaryOp = spv::OpDPdyFine;
2894 break;
2895 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07002896 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002897 unaryOp = spv::OpFwidthFine;
2898 break;
2899 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002900 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002901 unaryOp = spv::OpDPdxCoarse;
2902 break;
2903 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002904 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002905 unaryOp = spv::OpDPdyCoarse;
2906 break;
2907 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002908 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002909 unaryOp = spv::OpFwidthCoarse;
2910 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002911 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07002912 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08002913 libCall = spv::GLSLstd450InterpolateAtCentroid;
2914 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002915 case glslang::EOpAny:
2916 unaryOp = spv::OpAny;
2917 break;
2918 case glslang::EOpAll:
2919 unaryOp = spv::OpAll;
2920 break;
2921
2922 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002923 if (isFloat)
2924 libCall = spv::GLSLstd450FAbs;
2925 else
2926 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002927 break;
2928 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002929 if (isFloat)
2930 libCall = spv::GLSLstd450FSign;
2931 else
2932 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002933 break;
2934
John Kessenichfc51d282015-08-19 13:34:18 -06002935 case glslang::EOpAtomicCounterIncrement:
2936 case glslang::EOpAtomicCounterDecrement:
2937 case glslang::EOpAtomicCounter:
2938 {
2939 // Handle all of the atomics in one place, in createAtomicOperation()
2940 std::vector<spv::Id> operands;
2941 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002942 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002943 }
2944
John Kessenichfc51d282015-08-19 13:34:18 -06002945 case glslang::EOpBitFieldReverse:
2946 unaryOp = spv::OpBitReverse;
2947 break;
2948 case glslang::EOpBitCount:
2949 unaryOp = spv::OpBitCount;
2950 break;
2951 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002952 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002953 break;
2954 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002955 if (isUnsigned)
2956 libCall = spv::GLSLstd450FindUMsb;
2957 else
2958 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002959 break;
2960
John Kessenich140f3df2015-06-26 16:58:36 -06002961 default:
2962 return 0;
2963 }
2964
2965 spv::Id id;
2966 if (libCall >= 0) {
2967 std::vector<spv::Id> args;
2968 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07002969 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06002970 } else
2971 id = builder.createUnaryOp(unaryOp, typeId, operand);
2972
John Kessenich32cfd492016-02-02 12:37:46 -07002973 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002974}
2975
John Kessenich7a53f762016-01-20 11:19:27 -07002976// Create a unary operation on a matrix
2977spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
2978{
2979 // Handle unary operations vector by vector.
2980 // The result type is the same type as the original type.
2981 // The algorithm is to:
2982 // - break the matrix into vectors
2983 // - apply the operation to each vector
2984 // - make a matrix out the vector results
2985
2986 // get the types sorted out
2987 int numCols = builder.getNumColumns(operand);
2988 int numRows = builder.getNumRows(operand);
2989 spv::Id scalarType = builder.getScalarTypeId(typeId);
2990 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2991 std::vector<spv::Id> results;
2992
2993 // do each vector op
2994 for (int c = 0; c < numCols; ++c) {
2995 std::vector<unsigned int> indexes;
2996 indexes.push_back(c);
2997 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
2998 results.push_back(builder.createUnaryOp(op, vecType, vec));
2999 builder.setPrecision(results.back(), precision);
3000 }
3001
3002 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003003 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003004}
3005
John Kessenich140f3df2015-06-26 16:58:36 -06003006spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3007{
3008 spv::Op convOp = spv::OpNop;
3009 spv::Id zero = 0;
3010 spv::Id one = 0;
3011
3012 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3013
3014 switch (op) {
3015 case glslang::EOpConvIntToBool:
3016 case glslang::EOpConvUintToBool:
3017 zero = builder.makeUintConstant(0);
3018 zero = makeSmearedConstant(zero, vectorSize);
3019 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3020
3021 case glslang::EOpConvFloatToBool:
3022 zero = builder.makeFloatConstant(0.0F);
3023 zero = makeSmearedConstant(zero, vectorSize);
3024 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3025
3026 case glslang::EOpConvDoubleToBool:
3027 zero = builder.makeDoubleConstant(0.0);
3028 zero = makeSmearedConstant(zero, vectorSize);
3029 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3030
3031 case glslang::EOpConvBoolToFloat:
3032 convOp = spv::OpSelect;
3033 zero = builder.makeFloatConstant(0.0);
3034 one = builder.makeFloatConstant(1.0);
3035 break;
3036 case glslang::EOpConvBoolToDouble:
3037 convOp = spv::OpSelect;
3038 zero = builder.makeDoubleConstant(0.0);
3039 one = builder.makeDoubleConstant(1.0);
3040 break;
3041 case glslang::EOpConvBoolToInt:
3042 zero = builder.makeIntConstant(0);
3043 one = builder.makeIntConstant(1);
3044 convOp = spv::OpSelect;
3045 break;
3046 case glslang::EOpConvBoolToUint:
3047 zero = builder.makeUintConstant(0);
3048 one = builder.makeUintConstant(1);
3049 convOp = spv::OpSelect;
3050 break;
3051
3052 case glslang::EOpConvIntToFloat:
3053 case glslang::EOpConvIntToDouble:
3054 convOp = spv::OpConvertSToF;
3055 break;
3056
3057 case glslang::EOpConvUintToFloat:
3058 case glslang::EOpConvUintToDouble:
3059 convOp = spv::OpConvertUToF;
3060 break;
3061
3062 case glslang::EOpConvDoubleToFloat:
3063 case glslang::EOpConvFloatToDouble:
3064 convOp = spv::OpFConvert;
3065 break;
3066
3067 case glslang::EOpConvFloatToInt:
3068 case glslang::EOpConvDoubleToInt:
3069 convOp = spv::OpConvertFToS;
3070 break;
3071
3072 case glslang::EOpConvUintToInt:
3073 case glslang::EOpConvIntToUint:
3074 convOp = spv::OpBitcast;
3075 break;
3076
3077 case glslang::EOpConvFloatToUint:
3078 case glslang::EOpConvDoubleToUint:
3079 convOp = spv::OpConvertFToU;
3080 break;
3081 default:
3082 break;
3083 }
3084
3085 spv::Id result = 0;
3086 if (convOp == spv::OpNop)
3087 return result;
3088
3089 if (convOp == spv::OpSelect) {
3090 zero = makeSmearedConstant(zero, vectorSize);
3091 one = makeSmearedConstant(one, vectorSize);
3092 result = builder.createTriOp(convOp, destType, operand, one, zero);
3093 } else
3094 result = builder.createUnaryOp(convOp, destType, operand);
3095
John Kessenich32cfd492016-02-02 12:37:46 -07003096 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003097}
3098
3099spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3100{
3101 if (vectorSize == 0)
3102 return constant;
3103
3104 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3105 std::vector<spv::Id> components;
3106 for (int c = 0; c < vectorSize; ++c)
3107 components.push_back(constant);
3108 return builder.makeCompositeConstant(vectorTypeId, components);
3109}
3110
John Kessenich426394d2015-07-23 10:22:48 -06003111// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08003112spv::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 -06003113{
3114 spv::Op opCode = spv::OpNop;
3115
3116 switch (op) {
3117 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003118 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003119 opCode = spv::OpAtomicIAdd;
3120 break;
3121 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003122 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003123 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003124 break;
3125 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003126 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003127 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003128 break;
3129 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003130 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003131 opCode = spv::OpAtomicAnd;
3132 break;
3133 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003134 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003135 opCode = spv::OpAtomicOr;
3136 break;
3137 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003138 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003139 opCode = spv::OpAtomicXor;
3140 break;
3141 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003142 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003143 opCode = spv::OpAtomicExchange;
3144 break;
3145 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003146 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003147 opCode = spv::OpAtomicCompareExchange;
3148 break;
3149 case glslang::EOpAtomicCounterIncrement:
3150 opCode = spv::OpAtomicIIncrement;
3151 break;
3152 case glslang::EOpAtomicCounterDecrement:
3153 opCode = spv::OpAtomicIDecrement;
3154 break;
3155 case glslang::EOpAtomicCounter:
3156 opCode = spv::OpAtomicLoad;
3157 break;
3158 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003159 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003160 break;
3161 }
3162
3163 // Sort out the operands
3164 // - mapping from glslang -> SPV
3165 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003166 // - compare-exchange swaps the value and comparator
3167 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003168 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3169 auto opIt = operands.begin(); // walk the glslang operands
3170 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003171 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3172 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3173 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003174 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3175 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003176 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003177 spvAtomicOperands.push_back(*(opIt + 1));
3178 spvAtomicOperands.push_back(*opIt);
3179 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003180 }
John Kessenich426394d2015-07-23 10:22:48 -06003181
John Kessenich3e60a6f2015-09-14 22:45:16 -06003182 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003183 for (; opIt != operands.end(); ++opIt)
3184 spvAtomicOperands.push_back(*opIt);
3185
3186 return builder.createOp(opCode, typeId, spvAtomicOperands);
3187}
3188
John Kessenich5e4b1242015-08-06 22:53:06 -06003189spv::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 -06003190{
John Kessenich5e4b1242015-08-06 22:53:06 -06003191 bool isUnsigned = typeProxy == glslang::EbtUint;
3192 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3193
John Kessenich140f3df2015-06-26 16:58:36 -06003194 spv::Op opCode = spv::OpNop;
3195 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003196 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003197 spv::Id typeId0 = 0;
3198 if (consumedOperands > 0)
3199 typeId0 = builder.getTypeId(operands[0]);
3200 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003201
3202 switch (op) {
3203 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003204 if (isFloat)
3205 libCall = spv::GLSLstd450FMin;
3206 else if (isUnsigned)
3207 libCall = spv::GLSLstd450UMin;
3208 else
3209 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003210 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003211 break;
3212 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003213 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003214 break;
3215 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003216 if (isFloat)
3217 libCall = spv::GLSLstd450FMax;
3218 else if (isUnsigned)
3219 libCall = spv::GLSLstd450UMax;
3220 else
3221 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003222 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003223 break;
3224 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003225 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003226 break;
3227 case glslang::EOpDot:
3228 opCode = spv::OpDot;
3229 break;
3230 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003231 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003232 break;
3233
3234 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003235 if (isFloat)
3236 libCall = spv::GLSLstd450FClamp;
3237 else if (isUnsigned)
3238 libCall = spv::GLSLstd450UClamp;
3239 else
3240 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003241 builder.promoteScalar(precision, operands.front(), operands[1]);
3242 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003243 break;
3244 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003245 if (isFloat)
3246 libCall = spv::GLSLstd450FMix;
3247 else
3248 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003249 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003250 break;
3251 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003252 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003253 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003254 break;
3255 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003256 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003257 builder.promoteScalar(precision, operands[0], operands[2]);
3258 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003259 break;
3260
3261 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003262 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003263 break;
3264 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003265 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003266 break;
3267 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003268 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003269 break;
3270 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003271 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003272 break;
3273 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003274 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003275 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003276 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003277 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003278 libCall = spv::GLSLstd450InterpolateAtSample;
3279 break;
3280 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003281 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003282 libCall = spv::GLSLstd450InterpolateAtOffset;
3283 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003284 case glslang::EOpAddCarry:
3285 opCode = spv::OpIAddCarry;
3286 typeId = builder.makeStructResultType(typeId0, typeId0);
3287 consumedOperands = 2;
3288 break;
3289 case glslang::EOpSubBorrow:
3290 opCode = spv::OpISubBorrow;
3291 typeId = builder.makeStructResultType(typeId0, typeId0);
3292 consumedOperands = 2;
3293 break;
3294 case glslang::EOpUMulExtended:
3295 opCode = spv::OpUMulExtended;
3296 typeId = builder.makeStructResultType(typeId0, typeId0);
3297 consumedOperands = 2;
3298 break;
3299 case glslang::EOpIMulExtended:
3300 opCode = spv::OpSMulExtended;
3301 typeId = builder.makeStructResultType(typeId0, typeId0);
3302 consumedOperands = 2;
3303 break;
3304 case glslang::EOpBitfieldExtract:
3305 if (isUnsigned)
3306 opCode = spv::OpBitFieldUExtract;
3307 else
3308 opCode = spv::OpBitFieldSExtract;
3309 break;
3310 case glslang::EOpBitfieldInsert:
3311 opCode = spv::OpBitFieldInsert;
3312 break;
3313
3314 case glslang::EOpFma:
3315 libCall = spv::GLSLstd450Fma;
3316 break;
3317 case glslang::EOpFrexp:
3318 libCall = spv::GLSLstd450FrexpStruct;
3319 if (builder.getNumComponents(operands[0]) == 1)
3320 frexpIntType = builder.makeIntegerType(32, true);
3321 else
3322 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3323 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3324 consumedOperands = 1;
3325 break;
3326 case glslang::EOpLdexp:
3327 libCall = spv::GLSLstd450Ldexp;
3328 break;
3329
John Kessenich140f3df2015-06-26 16:58:36 -06003330 default:
3331 return 0;
3332 }
3333
3334 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003335 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003336 // Use an extended instruction from the standard library.
3337 // Construct the call arguments, without modifying the original operands vector.
3338 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3339 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003340 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003341 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003342 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003343 case 0:
3344 // should all be handled by visitAggregate and createNoArgOperation
3345 assert(0);
3346 return 0;
3347 case 1:
3348 // should all be handled by createUnaryOperation
3349 assert(0);
3350 return 0;
3351 case 2:
3352 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3353 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003354 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003355 // anything 3 or over doesn't have l-value operands, so all should be consumed
3356 assert(consumedOperands == operands.size());
3357 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003358 break;
3359 }
3360 }
3361
John Kessenich55e7d112015-11-15 21:33:39 -07003362 // Decode the return types that were structures
3363 switch (op) {
3364 case glslang::EOpAddCarry:
3365 case glslang::EOpSubBorrow:
3366 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3367 id = builder.createCompositeExtract(id, typeId0, 0);
3368 break;
3369 case glslang::EOpUMulExtended:
3370 case glslang::EOpIMulExtended:
3371 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3372 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3373 break;
3374 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003375 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003376 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3377 id = builder.createCompositeExtract(id, typeId0, 0);
3378 break;
3379 default:
3380 break;
3381 }
3382
John Kessenich32cfd492016-02-02 12:37:46 -07003383 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003384}
3385
3386// Intrinsics with no arguments, no return value, and no precision.
3387spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3388{
3389 // TODO: get the barrier operands correct
3390
3391 switch (op) {
3392 case glslang::EOpEmitVertex:
3393 builder.createNoResultOp(spv::OpEmitVertex);
3394 return 0;
3395 case glslang::EOpEndPrimitive:
3396 builder.createNoResultOp(spv::OpEndPrimitive);
3397 return 0;
3398 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003399 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3400 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003401 return 0;
3402 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003403 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003404 return 0;
3405 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003407 return 0;
3408 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003409 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003410 return 0;
3411 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003412 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003413 return 0;
3414 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003415 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003416 return 0;
3417 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003418 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003419 return 0;
3420 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003421 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003422 return 0;
3423 }
3424}
3425
3426spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3427{
John Kessenich2f273362015-07-18 22:34:27 -06003428 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003429 spv::Id id;
3430 if (symbolValues.end() != iter) {
3431 id = iter->second;
3432 return id;
3433 }
3434
3435 // it was not found, create it
3436 id = createSpvVariable(symbol);
3437 symbolValues[symbol->getId()] = id;
3438
3439 if (! symbol->getType().isStruct()) {
3440 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003441 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003442 if (symbol->getQualifier().hasLocation())
3443 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3444 if (symbol->getQualifier().hasIndex())
3445 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3446 if (symbol->getQualifier().hasComponent())
3447 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3448 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003449 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003450 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003451 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003452 if (symbol->getQualifier().hasXfbBuffer())
3453 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3454 if (symbol->getQualifier().hasXfbOffset())
3455 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3456 }
3457 }
3458
John Kesseniche0b6cad2015-12-24 10:30:13 -07003459 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003460 if (symbol->getQualifier().hasStream()) {
3461 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003462 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003463 }
John Kessenich140f3df2015-06-26 16:58:36 -06003464 if (symbol->getQualifier().hasSet())
3465 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3466 if (symbol->getQualifier().hasBinding())
3467 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3468 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003469 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003470 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003471 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003472 if (symbol->getQualifier().hasXfbBuffer())
3473 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3474 }
3475
3476 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003477 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003478 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003479 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003480
John Kessenich140f3df2015-06-26 16:58:36 -06003481 return id;
3482}
3483
John Kessenich55e7d112015-11-15 21:33:39 -07003484// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003485void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3486{
3487 if (dec != spv::BadValue)
3488 builder.addDecoration(id, dec);
3489}
3490
John Kessenich55e7d112015-11-15 21:33:39 -07003491// If 'dec' is valid, add a one-operand decoration to an object
3492void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3493{
3494 if (dec != spv::BadValue)
3495 builder.addDecoration(id, dec, value);
3496}
3497
3498// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003499void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3500{
3501 if (dec != spv::BadValue)
3502 builder.addMemberDecoration(id, (unsigned)member, dec);
3503}
3504
John Kessenich92187592016-02-01 13:45:25 -07003505// If 'dec' is valid, add a one-operand decoration to a struct member
3506void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3507{
3508 if (dec != spv::BadValue)
3509 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3510}
3511
John Kessenich55e7d112015-11-15 21:33:39 -07003512// Make a full tree of instructions to build a SPIR-V specialization constant,
3513// or regularly constant if possible.
3514//
3515// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3516//
3517// Recursively walk the nodes. The nodes form a tree whose leaves are
3518// regular constants, which themselves are trees that createSpvConstant()
3519// recursively walks. So, this function walks the "top" of the tree:
3520// - emit specialization constant-building instructions for specConstant
3521// - when running into a non-spec-constant, switch to createSpvConstant()
3522spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3523{
3524 assert(node.getQualifier().storage == glslang::EvqConst);
3525
3526 // hand off to the non-spec-constant path
3527 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3528 int nextConst = 0;
3529 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3530}
3531
John Kessenich140f3df2015-06-26 16:58:36 -06003532// Use 'consts' as the flattened glslang source of scalar constants to recursively
3533// build the aggregate SPIR-V constant.
3534//
3535// If there are not enough elements present in 'consts', 0 will be substituted;
3536// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3537//
John Kessenich55e7d112015-11-15 21:33:39 -07003538spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003539{
3540 // vector of constants for SPIR-V
3541 std::vector<spv::Id> spvConsts;
3542
3543 // Type is used for struct and array constants
3544 spv::Id typeId = convertGlslangToSpvType(glslangType);
3545
3546 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003547 glslang::TType elementType(glslangType, 0);
3548 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003549 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003550 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003551 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003552 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003553 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003554 } else if (glslangType.getStruct()) {
3555 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3556 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003557 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003558 } else if (glslangType.isVector()) {
3559 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3560 bool zero = nextConst >= consts.size();
3561 switch (glslangType.getBasicType()) {
3562 case glslang::EbtInt:
3563 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3564 break;
3565 case glslang::EbtUint:
3566 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3567 break;
3568 case glslang::EbtFloat:
3569 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3570 break;
3571 case glslang::EbtDouble:
3572 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3573 break;
3574 case glslang::EbtBool:
3575 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3576 break;
3577 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003578 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003579 break;
3580 }
3581 ++nextConst;
3582 }
3583 } else {
3584 // we have a non-aggregate (scalar) constant
3585 bool zero = nextConst >= consts.size();
3586 spv::Id scalar = 0;
3587 switch (glslangType.getBasicType()) {
3588 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003589 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003590 break;
3591 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003592 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003593 break;
3594 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003595 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003596 break;
3597 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003598 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003599 break;
3600 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003601 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003602 break;
3603 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003604 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003605 break;
3606 }
3607 ++nextConst;
3608 return scalar;
3609 }
3610
3611 return builder.makeCompositeConstant(typeId, spvConsts);
3612}
3613
John Kessenich7c1aa102015-10-15 13:29:11 -06003614// Return true if the node is a constant or symbol whose reading has no
3615// non-trivial observable cost or effect.
3616bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3617{
3618 // don't know what this is
3619 if (node == nullptr)
3620 return false;
3621
3622 // a constant is safe
3623 if (node->getAsConstantUnion() != nullptr)
3624 return true;
3625
3626 // not a symbol means non-trivial
3627 if (node->getAsSymbolNode() == nullptr)
3628 return false;
3629
3630 // a symbol, depends on what's being read
3631 switch (node->getType().getQualifier().storage) {
3632 case glslang::EvqTemporary:
3633 case glslang::EvqGlobal:
3634 case glslang::EvqIn:
3635 case glslang::EvqInOut:
3636 case glslang::EvqConst:
3637 case glslang::EvqConstReadOnly:
3638 case glslang::EvqUniform:
3639 return true;
3640 default:
3641 return false;
3642 }
3643}
3644
3645// A node is trivial if it is a single operation with no side effects.
3646// Error on the side of saying non-trivial.
3647// Return true if trivial.
3648bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3649{
3650 if (node == nullptr)
3651 return false;
3652
3653 // symbols and constants are trivial
3654 if (isTrivialLeaf(node))
3655 return true;
3656
3657 // otherwise, it needs to be a simple operation or one or two leaf nodes
3658
3659 // not a simple operation
3660 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3661 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3662 if (binaryNode == nullptr && unaryNode == nullptr)
3663 return false;
3664
3665 // not on leaf nodes
3666 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3667 return false;
3668
3669 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3670 return false;
3671 }
3672
3673 switch (node->getAsOperator()->getOp()) {
3674 case glslang::EOpLogicalNot:
3675 case glslang::EOpConvIntToBool:
3676 case glslang::EOpConvUintToBool:
3677 case glslang::EOpConvFloatToBool:
3678 case glslang::EOpConvDoubleToBool:
3679 case glslang::EOpEqual:
3680 case glslang::EOpNotEqual:
3681 case glslang::EOpLessThan:
3682 case glslang::EOpGreaterThan:
3683 case glslang::EOpLessThanEqual:
3684 case glslang::EOpGreaterThanEqual:
3685 case glslang::EOpIndexDirect:
3686 case glslang::EOpIndexDirectStruct:
3687 case glslang::EOpLogicalXor:
3688 case glslang::EOpAny:
3689 case glslang::EOpAll:
3690 return true;
3691 default:
3692 return false;
3693 }
3694}
3695
3696// Emit short-circuiting code, where 'right' is never evaluated unless
3697// the left side is true (for &&) or false (for ||).
3698spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3699{
3700 spv::Id boolTypeId = builder.makeBoolType();
3701
3702 // emit left operand
3703 builder.clearAccessChain();
3704 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003705 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003706
3707 // Operands to accumulate OpPhi operands
3708 std::vector<spv::Id> phiOperands;
3709 // accumulate left operand's phi information
3710 phiOperands.push_back(leftId);
3711 phiOperands.push_back(builder.getBuildPoint()->getId());
3712
3713 // Make the two kinds of operation symmetric with a "!"
3714 // || => emit "if (! left) result = right"
3715 // && => emit "if ( left) result = right"
3716 //
3717 // TODO: this runtime "not" for || could be avoided by adding functionality
3718 // to 'builder' to have an "else" without an "then"
3719 if (op == glslang::EOpLogicalOr)
3720 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3721
3722 // make an "if" based on the left value
3723 spv::Builder::If ifBuilder(leftId, builder);
3724
3725 // emit right operand as the "then" part of the "if"
3726 builder.clearAccessChain();
3727 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003728 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003729
3730 // accumulate left operand's phi information
3731 phiOperands.push_back(rightId);
3732 phiOperands.push_back(builder.getBuildPoint()->getId());
3733
3734 // finish the "if"
3735 ifBuilder.makeEndIf();
3736
3737 // phi together the two results
3738 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3739}
3740
John Kessenich140f3df2015-06-26 16:58:36 -06003741}; // end anonymous namespace
3742
3743namespace glslang {
3744
John Kessenich68d78fd2015-07-12 19:28:10 -06003745void GetSpirvVersion(std::string& version)
3746{
John Kessenich9e55f632015-07-15 10:03:39 -06003747 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003748 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003749 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003750 version = buf;
3751}
3752
John Kessenich140f3df2015-06-26 16:58:36 -06003753// Write SPIR-V out to a binary file
3754void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3755{
3756 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003757 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003758 for (int i = 0; i < (int)spirv.size(); ++i) {
3759 unsigned int word = spirv[i];
3760 out.write((const char*)&word, 4);
3761 }
3762 out.close();
3763}
3764
3765//
3766// Set up the glslang traversal
3767//
3768void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3769{
3770 TIntermNode* root = intermediate.getTreeRoot();
3771
3772 if (root == 0)
3773 return;
3774
3775 glslang::GetThreadPoolAllocator().push();
3776
3777 TGlslangToSpvTraverser it(&intermediate);
3778
3779 root->traverse(&it);
3780
3781 it.dumpSpv(spirv);
3782
3783 glslang::GetThreadPoolAllocator().pop();
3784}
3785
3786}; // end namespace glslang