blob: c3ae56ebec9d715331a7774e334dc69ec0c778f9 [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 Kessenich140f3df2015-06-26 16:58:36 -060093 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
94 spv::Id getSampledType(const glslang::TSampler&);
95 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070096 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich32cfd492016-02-02 12:37:46 -070097 spv::Id accessChainLoad(const glslang::TType& type);
John Kessenichf85e8062015-12-19 13:57:10 -070098 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -070099 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
100 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
101 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 -0600102
103 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
104 void makeFunctions(const glslang::TIntermSequence&);
105 void makeGlobalInitializers(const glslang::TIntermSequence&);
106 void visitFunctions(const glslang::TIntermSequence&);
107 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800108 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600109 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
110 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600111 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
112
113 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 -0700114 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800115 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 -0700116 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600117 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
118 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800119 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 -0600120 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 -0600121 spv::Id createNoArgOperation(glslang::TOperator op);
122 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
123 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700124 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700126 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700127 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
128 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600129 bool isTrivialLeaf(const glslang::TIntermTyped* node);
130 bool isTrivial(const glslang::TIntermTyped* node);
131 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600132
133 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700134 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600135 int sequenceDepth;
136
137 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
138 spv::Builder builder;
139 bool inMain;
140 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700141 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 -0700142 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600143 const glslang::TIntermediate* glslangIntermediate;
144 spv::Id stdBuiltins;
145
John Kessenich2f273362015-07-18 22:34:27 -0600146 std::unordered_map<int, spv::Id> symbolValues;
147 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
148 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700149 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600150 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 -0600151 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600152};
153
154//
155// Helper functions for translating glslang representations to SPIR-V enumerants.
156//
157
158// Translate glslang profile to SPIR-V source language.
159spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
160{
161 switch (profile) {
162 case ENoProfile:
163 case ECoreProfile:
164 case ECompatibilityProfile:
165 return spv::SourceLanguageGLSL;
166 case EEsProfile:
167 return spv::SourceLanguageESSL;
168 default:
169 return spv::SourceLanguageUnknown;
170 }
171}
172
173// Translate glslang language (stage) to SPIR-V execution model.
174spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
175{
176 switch (stage) {
177 case EShLangVertex: return spv::ExecutionModelVertex;
178 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
179 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
180 case EShLangGeometry: return spv::ExecutionModelGeometry;
181 case EShLangFragment: return spv::ExecutionModelFragment;
182 case EShLangCompute: return spv::ExecutionModelGLCompute;
183 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700184 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600185 return spv::ExecutionModelFragment;
186 }
187}
188
189// Translate glslang type to SPIR-V storage class.
190spv::StorageClass TranslateStorageClass(const glslang::TType& type)
191{
192 if (type.getQualifier().isPipeInput())
193 return spv::StorageClassInput;
194 else if (type.getQualifier().isPipeOutput())
195 return spv::StorageClassOutput;
196 else if (type.getQualifier().isUniformOrBuffer()) {
197 if (type.getBasicType() == glslang::EbtBlock)
198 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800199 else if (type.getBasicType() == glslang::EbtAtomicUint)
200 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600201 else
202 return spv::StorageClassUniformConstant;
203 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
204 } else {
205 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700206 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
207 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600208 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
209 case glslang::EvqTemporary: return spv::StorageClassFunction;
210 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700211 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600212 return spv::StorageClassFunction;
213 }
214 }
215}
216
217// Translate glslang sampler type to SPIR-V dimensionality.
218spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
219{
220 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700221 case glslang::Esd1D: return spv::Dim1D;
222 case glslang::Esd2D: return spv::Dim2D;
223 case glslang::Esd3D: return spv::Dim3D;
224 case glslang::EsdCube: return spv::DimCube;
225 case glslang::EsdRect: return spv::DimRect;
226 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich140f3df2015-06-26 16:58:36 -0600227 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700228 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600229 return spv::Dim2D;
230 }
231}
232
233// Translate glslang type to SPIR-V precision decorations.
234spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
235{
236 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700237 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600238 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600239 default:
240 return spv::NoPrecision;
241 }
242}
243
244// Translate glslang type to SPIR-V block decorations.
245spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
246{
247 if (type.getBasicType() == glslang::EbtBlock) {
248 switch (type.getQualifier().storage) {
249 case glslang::EvqUniform: return spv::DecorationBlock;
250 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
251 case glslang::EvqVaryingIn: return spv::DecorationBlock;
252 case glslang::EvqVaryingOut: return spv::DecorationBlock;
253 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700254 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600255 break;
256 }
257 }
258
259 return (spv::Decoration)spv::BadValue;
260}
261
262// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700263spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600264{
265 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700266 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600267 case glslang::ElmRowMajor:
268 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700269 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600270 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700271 default:
272 // opaque layouts don't need a majorness
273 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 }
275 } else {
276 switch (type.getBasicType()) {
277 default:
278 return (spv::Decoration)spv::BadValue;
279 break;
280 case glslang::EbtBlock:
281 switch (type.getQualifier().storage) {
282 case glslang::EvqUniform:
283 case glslang::EvqBuffer:
284 switch (type.getQualifier().layoutPacking) {
285 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600286 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
287 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600288 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600289 }
290 case glslang::EvqVaryingIn:
291 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700292 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600293 return (spv::Decoration)spv::BadValue;
294 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700295 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600296 return (spv::Decoration)spv::BadValue;
297 }
298 }
299 }
300}
301
302// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700303// Returns spv::Decoration(spv::BadValue) when no decoration
304// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700305spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600306{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700307 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700308 // Smooth decoration doesn't exist in SPIR-V 1.0
309 return (spv::Decoration)spv::BadValue;
310 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700311 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700312 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700313 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600314 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700315 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600316 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700317 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600318 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700319 else if (qualifier.sample) {
320 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600321 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700322 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600323 return (spv::Decoration)spv::BadValue;
324}
325
John Kessenich92187592016-02-01 13:45:25 -0700326// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700327spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600328{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700329 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600330 return spv::DecorationInvariant;
331 else
332 return (spv::Decoration)spv::BadValue;
333}
334
335// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700336spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600337{
338 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700339 case glslang::EbvPointSize:
340 switch (glslangIntermediate->getStage()) {
341 case EShLangGeometry:
342 builder.addCapability(spv::CapabilityGeometryPointSize);
343 break;
344 case EShLangTessControl:
345 case EShLangTessEvaluation:
346 builder.addCapability(spv::CapabilityTessellationPointSize);
347 break;
348 }
349 return spv::BuiltInPointSize;
350
351 case glslang::EbvClipDistance:
352 builder.addCapability(spv::CapabilityClipDistance);
353 return spv::BuiltInClipDistance;
354
355 case glslang::EbvCullDistance:
356 builder.addCapability(spv::CapabilityCullDistance);
357 return spv::BuiltInCullDistance;
358
359 case glslang::EbvViewportIndex:
360 // TODO: builder.addCapability(spv::CapabilityMultiViewport);
361 return spv::BuiltInViewportIndex;
362
John Kessenich5e801132016-02-15 11:09:46 -0700363 case glslang::EbvSampleId:
364 builder.addCapability(spv::CapabilitySampleRateShading);
365 return spv::BuiltInSampleId;
366
367 case glslang::EbvSamplePosition:
368 builder.addCapability(spv::CapabilitySampleRateShading);
369 return spv::BuiltInSamplePosition;
370
371 case glslang::EbvSampleMask:
372 builder.addCapability(spv::CapabilitySampleRateShading);
373 return spv::BuiltInSampleMask;
374
John Kessenich140f3df2015-06-26 16:58:36 -0600375 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600376 case glslang::EbvVertexId: return spv::BuiltInVertexId;
377 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenichda581a22015-10-14 14:10:30 -0600378 case glslang::EbvBaseVertex:
379 case glslang::EbvBaseInstance:
380 case glslang::EbvDrawId:
381 // TODO: Add SPIR-V builtin ID.
382 spv::MissingFunctionality("Draw parameters");
383 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600384 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
385 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
386 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600387 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
388 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
389 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
390 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
391 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
392 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
393 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600394 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
395 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
396 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
397 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
398 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
399 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
400 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
401 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
402 default: return (spv::BuiltIn)spv::BadValue;
403 }
404}
405
Rex Xufc618912015-09-09 16:42:49 +0800406// Translate glslang image layout format to SPIR-V image format.
407spv::ImageFormat TranslateImageFormat(const glslang::TType& type)
408{
409 assert(type.getBasicType() == glslang::EbtSampler);
410
411 switch (type.getQualifier().layoutFormat) {
412 case glslang::ElfNone: return spv::ImageFormatUnknown;
413 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
414 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
415 case glslang::ElfR32f: return spv::ImageFormatR32f;
416 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
417 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
418 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
419 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
420 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
421 case glslang::ElfR16f: return spv::ImageFormatR16f;
422 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
423 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
424 case glslang::ElfRg16: return spv::ImageFormatRg16;
425 case glslang::ElfRg8: return spv::ImageFormatRg8;
426 case glslang::ElfR16: return spv::ImageFormatR16;
427 case glslang::ElfR8: return spv::ImageFormatR8;
428 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
429 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
430 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
431 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
432 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
433 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
434 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
435 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
436 case glslang::ElfR32i: return spv::ImageFormatR32i;
437 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
438 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
439 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
440 case glslang::ElfR16i: return spv::ImageFormatR16i;
441 case glslang::ElfR8i: return spv::ImageFormatR8i;
442 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
443 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
444 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
445 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
446 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
447 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
448 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
449 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
450 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
451 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
452 default: return (spv::ImageFormat)spv::BadValue;
453 }
454}
455
John Kesseniche0b6cad2015-12-24 10:30:13 -0700456void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
457{
458 if (child.layoutMatrix == glslang::ElmNone)
459 child.layoutMatrix = parent.layoutMatrix;
460
461 if (parent.invariant)
462 child.invariant = true;
463 if (parent.nopersp)
464 child.nopersp = true;
465 if (parent.flat)
466 child.flat = true;
467 if (parent.centroid)
468 child.centroid = true;
469 if (parent.patch)
470 child.patch = true;
471 if (parent.sample)
472 child.sample = true;
John Kessenich7b9fa252016-01-21 18:56:57 -0700473
474 child.layoutLocation = parent.layoutLocation;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700475}
476
477bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
478{
John Kessenich7b9fa252016-01-21 18:56:57 -0700479 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700480 // - struct members can inherit from a struct declaration
481 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
482 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700483 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700484}
485
John Kessenich140f3df2015-06-26 16:58:36 -0600486//
487// Implement the TGlslangToSpvTraverser class.
488//
489
490TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
491 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700492 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600493 inMain(false), mainTerminated(false), linkageOnly(false),
494 glslangIntermediate(glslangIntermediate)
495{
496 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
497
498 builder.clearAccessChain();
499 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
500 stdBuiltins = builder.import("GLSL.std.450");
501 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
502 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700503 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600504
505 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600506 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
507 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600508 builder.addSourceExtension(it->c_str());
509
510 // Add the top-level modes for this shader.
511
John Kessenich92187592016-02-01 13:45:25 -0700512 if (glslangIntermediate->getXfbMode()) {
513 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600514 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700515 }
John Kessenich140f3df2015-06-26 16:58:36 -0600516
517 unsigned int mode;
518 switch (glslangIntermediate->getStage()) {
519 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600520 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600521 break;
522
523 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600524 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600525 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
526 break;
527
528 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600529 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600530 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700531 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
532 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
533 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600534 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600535 }
536 if (mode != spv::BadValue)
537 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
538
John Kesseniche6903322015-10-13 16:29:02 -0600539 switch (glslangIntermediate->getVertexSpacing()) {
540 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
541 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
542 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
543 default: mode = spv::BadValue; break;
544 }
545 if (mode != spv::BadValue)
546 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
547
548 switch (glslangIntermediate->getVertexOrder()) {
549 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
550 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
551 default: mode = spv::BadValue; break;
552 }
553 if (mode != spv::BadValue)
554 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
555
556 if (glslangIntermediate->getPointMode())
557 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600558 break;
559
560 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600561 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600562 switch (glslangIntermediate->getInputPrimitive()) {
563 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
564 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
565 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700566 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600567 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
568 default: mode = spv::BadValue; break;
569 }
570 if (mode != spv::BadValue)
571 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600572
John Kessenich140f3df2015-06-26 16:58:36 -0600573 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
574
575 switch (glslangIntermediate->getOutputPrimitive()) {
576 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
577 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
578 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
579 default: mode = spv::BadValue; break;
580 }
581 if (mode != spv::BadValue)
582 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
583 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
584 break;
585
586 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600587 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600588 if (glslangIntermediate->getPixelCenterInteger())
589 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600590
John Kessenich140f3df2015-06-26 16:58:36 -0600591 if (glslangIntermediate->getOriginUpperLeft())
592 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600593 else
594 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600595
596 if (glslangIntermediate->getEarlyFragmentTests())
597 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
598
599 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600600 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
601 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
602 default: mode = spv::BadValue; break;
603 }
604 if (mode != spv::BadValue)
605 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
606
607 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
608 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600609 break;
610
611 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600612 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600613 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
614 glslangIntermediate->getLocalSize(1),
615 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600616 break;
617
618 default:
619 break;
620 }
621
622}
623
John Kessenich7ba63412015-12-20 17:37:07 -0700624// Finish everything and dump
625void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
626{
627 // finish off the entry-point SPV instruction by adding the Input/Output <id>
628 for (auto it : iOSet)
629 entryPoint->addIdOperand(it);
630
631 builder.dump(out);
632}
633
John Kessenich140f3df2015-06-26 16:58:36 -0600634TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
635{
636 if (! mainTerminated) {
637 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
638 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600639 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600640 }
641}
642
643//
644// Implement the traversal functions.
645//
646// Return true from interior nodes to have the external traversal
647// continue on to children. Return false if children were
648// already processed.
649//
650
651//
652// Symbols can turn into
653// - uniform/input reads
654// - output writes
655// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
656// - something simple that degenerates into the last bullet
657//
658void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
659{
660 // getSymbolId() will set up all the IO decorations on the first call.
661 // Formal function parameters were mapped during makeFunctions().
662 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700663
664 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
665 if (builder.isPointer(id)) {
666 spv::StorageClass sc = builder.getStorageClass(id);
667 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
668 iOSet.insert(id);
669 }
670
671 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich140f3df2015-06-26 16:58:36 -0600672 if (! linkageOnly) {
673 // Prepare to generate code for the access
674
675 // L-value chains will be computed left to right. We're on the symbol now,
676 // which is the left-most part of the access chain, so now is "clear" time,
677 // followed by setting the base.
678 builder.clearAccessChain();
679
680 // For now, we consider all user variables as being in memory, so they are pointers,
681 // except for "const in" arguments to a function, which are an intermediate object.
682 // See comments in handleUserFunctionCall().
683 glslang::TStorageQualifier qualifier = symbol->getQualifier().storage;
684 if (qualifier == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end())
685 builder.setAccessChainRValue(id);
686 else
687 builder.setAccessChainLValue(id);
688 }
689}
690
691bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
692{
693 // First, handle special cases
694 switch (node->getOp()) {
695 case glslang::EOpAssign:
696 case glslang::EOpAddAssign:
697 case glslang::EOpSubAssign:
698 case glslang::EOpMulAssign:
699 case glslang::EOpVectorTimesMatrixAssign:
700 case glslang::EOpVectorTimesScalarAssign:
701 case glslang::EOpMatrixTimesScalarAssign:
702 case glslang::EOpMatrixTimesMatrixAssign:
703 case glslang::EOpDivAssign:
704 case glslang::EOpModAssign:
705 case glslang::EOpAndAssign:
706 case glslang::EOpInclusiveOrAssign:
707 case glslang::EOpExclusiveOrAssign:
708 case glslang::EOpLeftShiftAssign:
709 case glslang::EOpRightShiftAssign:
710 // A bin-op assign "a += b" means the same thing as "a = a + b"
711 // where a is evaluated before b. For a simple assignment, GLSL
712 // says to evaluate the left before the right. So, always, left
713 // node then right node.
714 {
715 // get the left l-value, save it away
716 builder.clearAccessChain();
717 node->getLeft()->traverse(this);
718 spv::Builder::AccessChain lValue = builder.getAccessChain();
719
720 // evaluate the right
721 builder.clearAccessChain();
722 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700723 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600724
725 if (node->getOp() != glslang::EOpAssign) {
726 // the left is also an r-value
727 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700728 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600729
730 // do the operation
731 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
732 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
733 node->getType().getBasicType());
734
735 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700736 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600737 }
738
739 // store the result
740 builder.setAccessChain(lValue);
741 builder.accessChainStore(rValue);
742
743 // assignments are expressions having an rValue after they are evaluated...
744 builder.clearAccessChain();
745 builder.setAccessChainRValue(rValue);
746 }
747 return false;
748 case glslang::EOpIndexDirect:
749 case glslang::EOpIndexDirectStruct:
750 {
751 // Get the left part of the access chain.
752 node->getLeft()->traverse(this);
753
754 // Add the next element in the chain
755
John Kessenich55e7d112015-11-15 21:33:39 -0700756 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600757 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
758 // This may be, e.g., an anonymous block-member selection, which generally need
759 // index remapping due to hidden members in anonymous blocks.
760 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700761 assert(remapper.size() > 0);
762 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600763 }
764
765 if (! node->getLeft()->getType().isArray() &&
766 node->getLeft()->getType().isVector() &&
767 node->getOp() == glslang::EOpIndexDirect) {
768 // This is essentially a hard-coded vector swizzle of size 1,
769 // so short circuit the access-chain stuff with a swizzle.
770 std::vector<unsigned> swizzle;
771 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600772 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600773 } else {
774 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600775 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600776 }
777 }
778 return false;
779 case glslang::EOpIndexIndirect:
780 {
781 // Structure or array or vector indirection.
782 // Will use native SPIR-V access-chain for struct and array indirection;
783 // matrices are arrays of vectors, so will also work for a matrix.
784 // Will use the access chain's 'component' for variable index into a vector.
785
786 // This adapter is building access chains left to right.
787 // Set up the access chain to the left.
788 node->getLeft()->traverse(this);
789
790 // save it so that computing the right side doesn't trash it
791 spv::Builder::AccessChain partial = builder.getAccessChain();
792
793 // compute the next index in the chain
794 builder.clearAccessChain();
795 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700796 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600797
798 // restore the saved access chain
799 builder.setAccessChain(partial);
800
801 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600802 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600803 else
John Kessenichfa668da2015-09-13 14:46:30 -0600804 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600805 }
806 return false;
807 case glslang::EOpVectorSwizzle:
808 {
809 node->getLeft()->traverse(this);
810 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
811 std::vector<unsigned> swizzle;
812 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
813 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600814 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600815 }
816 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600817 case glslang::EOpLogicalOr:
818 case glslang::EOpLogicalAnd:
819 {
820
821 // These may require short circuiting, but can sometimes be done as straight
822 // binary operations. The right operand must be short circuited if it has
823 // side effects, and should probably be if it is complex.
824 if (isTrivial(node->getRight()->getAsTyped()))
825 break; // handle below as a normal binary operation
826 // otherwise, we need to do dynamic short circuiting on the right operand
827 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
828 builder.clearAccessChain();
829 builder.setAccessChainRValue(result);
830 }
831 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600832 default:
833 break;
834 }
835
836 // Assume generic binary op...
837
John Kessenich32cfd492016-02-02 12:37:46 -0700838 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600839 builder.clearAccessChain();
840 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700841 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600842
John Kessenich32cfd492016-02-02 12:37:46 -0700843 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600844 builder.clearAccessChain();
845 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700846 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600847
John Kessenich32cfd492016-02-02 12:37:46 -0700848 // get result
849 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
850 convertGlslangToSpvType(node->getType()), left, right,
851 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600852
John Kessenich50e57562015-12-21 21:21:11 -0700853 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600854 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700855 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700856 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600857 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600858 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600859 return false;
860 }
John Kessenich140f3df2015-06-26 16:58:36 -0600861}
862
863bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
864{
John Kessenichfc51d282015-08-19 13:34:18 -0600865 spv::Id result = spv::NoResult;
866
867 // try texturing first
868 result = createImageTextureFunctionCall(node);
869 if (result != spv::NoResult) {
870 builder.clearAccessChain();
871 builder.setAccessChainRValue(result);
872
873 return false; // done with this node
874 }
875
876 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600877
878 if (node->getOp() == glslang::EOpArrayLength) {
879 // Quite special; won't want to evaluate the operand.
880
881 // Normal .length() would have been constant folded by the front-end.
882 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600883 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600884 assert(node->getOperand()->getType().isRuntimeSizedArray());
885 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
886 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600887 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
888 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600889
890 builder.clearAccessChain();
891 builder.setAccessChainRValue(length);
892
893 return false;
894 }
895
John Kessenichfc51d282015-08-19 13:34:18 -0600896 // Start by evaluating the operand
897
John Kessenich140f3df2015-06-26 16:58:36 -0600898 builder.clearAccessChain();
899 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800900
Rex Xufc618912015-09-09 16:42:49 +0800901 spv::Id operand = spv::NoResult;
902
903 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
904 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800905 node->getOp() == glslang::EOpAtomicCounter ||
906 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800907 operand = builder.accessChainGetLValue(); // Special case l-value operands
908 else
John Kessenich32cfd492016-02-02 12:37:46 -0700909 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600910
911 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
912
913 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600914 if (! result)
915 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600916
917 // if not, then possibly an operation
918 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700919 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600920
921 if (result) {
922 builder.clearAccessChain();
923 builder.setAccessChainRValue(result);
924
925 return false; // done with this node
926 }
927
928 // it must be a special case, check...
929 switch (node->getOp()) {
930 case glslang::EOpPostIncrement:
931 case glslang::EOpPostDecrement:
932 case glslang::EOpPreIncrement:
933 case glslang::EOpPreDecrement:
934 {
935 // we need the integer value "1" or the floating point "1.0" to add/subtract
936 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
937 builder.makeFloatConstant(1.0F) :
938 builder.makeIntConstant(1);
939 glslang::TOperator op;
940 if (node->getOp() == glslang::EOpPreIncrement ||
941 node->getOp() == glslang::EOpPostIncrement)
942 op = glslang::EOpAdd;
943 else
944 op = glslang::EOpSub;
945
946 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
947 convertGlslangToSpvType(node->getType()), operand, one,
948 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -0700949 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600950
951 // The result of operation is always stored, but conditionally the
952 // consumed result. The consumed result is always an r-value.
953 builder.accessChainStore(result);
954 builder.clearAccessChain();
955 if (node->getOp() == glslang::EOpPreIncrement ||
956 node->getOp() == glslang::EOpPreDecrement)
957 builder.setAccessChainRValue(result);
958 else
959 builder.setAccessChainRValue(operand);
960 }
961
962 return false;
963
964 case glslang::EOpEmitStreamVertex:
965 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
966 return false;
967 case glslang::EOpEndStreamPrimitive:
968 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
969 return false;
970
971 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700972 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -0700973 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -0600974 }
John Kessenich140f3df2015-06-26 16:58:36 -0600975}
976
977bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
978{
John Kessenichfc51d282015-08-19 13:34:18 -0600979 spv::Id result = spv::NoResult;
980
981 // try texturing
982 result = createImageTextureFunctionCall(node);
983 if (result != spv::NoResult) {
984 builder.clearAccessChain();
985 builder.setAccessChainRValue(result);
986
987 return false;
John Kessenich56bab042015-09-16 10:54:31 -0600988 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +0800989 // "imageStore" is a special case, which has no result
990 return false;
991 }
John Kessenichfc51d282015-08-19 13:34:18 -0600992
John Kessenich140f3df2015-06-26 16:58:36 -0600993 glslang::TOperator binOp = glslang::EOpNull;
994 bool reduceComparison = true;
995 bool isMatrix = false;
996 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -0600997 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -0600998
999 assert(node->getOp());
1000
1001 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1002
1003 switch (node->getOp()) {
1004 case glslang::EOpSequence:
1005 {
1006 if (preVisit)
1007 ++sequenceDepth;
1008 else
1009 --sequenceDepth;
1010
1011 if (sequenceDepth == 1) {
1012 // If this is the parent node of all the functions, we want to see them
1013 // early, so all call points have actual SPIR-V functions to reference.
1014 // In all cases, still let the traverser visit the children for us.
1015 makeFunctions(node->getAsAggregate()->getSequence());
1016
1017 // Also, we want all globals initializers to go into the entry of main(), before
1018 // anything else gets there, so visit out of order, doing them all now.
1019 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1020
1021 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1022 // so do them manually.
1023 visitFunctions(node->getAsAggregate()->getSequence());
1024
1025 return false;
1026 }
1027
1028 return true;
1029 }
1030 case glslang::EOpLinkerObjects:
1031 {
1032 if (visit == glslang::EvPreVisit)
1033 linkageOnly = true;
1034 else
1035 linkageOnly = false;
1036
1037 return true;
1038 }
1039 case glslang::EOpComma:
1040 {
1041 // processing from left to right naturally leaves the right-most
1042 // lying around in the access chain
1043 glslang::TIntermSequence& glslangOperands = node->getSequence();
1044 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1045 glslangOperands[i]->traverse(this);
1046
1047 return false;
1048 }
1049 case glslang::EOpFunction:
1050 if (visit == glslang::EvPreVisit) {
1051 if (isShaderEntrypoint(node)) {
1052 inMain = true;
1053 builder.setBuildPoint(shaderEntry->getLastBlock());
1054 } else {
1055 handleFunctionEntry(node);
1056 }
1057 } else {
1058 if (inMain)
1059 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001060 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001061 inMain = false;
1062 }
1063
1064 return true;
1065 case glslang::EOpParameters:
1066 // Parameters will have been consumed by EOpFunction processing, but not
1067 // the body, so we still visited the function node's children, making this
1068 // child redundant.
1069 return false;
1070 case glslang::EOpFunctionCall:
1071 {
1072 if (node->isUserDefined())
1073 result = handleUserFunctionCall(node);
John Kessenich55e7d112015-11-15 21:33:39 -07001074 assert(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001075 builder.clearAccessChain();
1076 builder.setAccessChainRValue(result);
1077
1078 return false;
1079 }
1080 case glslang::EOpConstructMat2x2:
1081 case glslang::EOpConstructMat2x3:
1082 case glslang::EOpConstructMat2x4:
1083 case glslang::EOpConstructMat3x2:
1084 case glslang::EOpConstructMat3x3:
1085 case glslang::EOpConstructMat3x4:
1086 case glslang::EOpConstructMat4x2:
1087 case glslang::EOpConstructMat4x3:
1088 case glslang::EOpConstructMat4x4:
1089 case glslang::EOpConstructDMat2x2:
1090 case glslang::EOpConstructDMat2x3:
1091 case glslang::EOpConstructDMat2x4:
1092 case glslang::EOpConstructDMat3x2:
1093 case glslang::EOpConstructDMat3x3:
1094 case glslang::EOpConstructDMat3x4:
1095 case glslang::EOpConstructDMat4x2:
1096 case glslang::EOpConstructDMat4x3:
1097 case glslang::EOpConstructDMat4x4:
1098 isMatrix = true;
1099 // fall through
1100 case glslang::EOpConstructFloat:
1101 case glslang::EOpConstructVec2:
1102 case glslang::EOpConstructVec3:
1103 case glslang::EOpConstructVec4:
1104 case glslang::EOpConstructDouble:
1105 case glslang::EOpConstructDVec2:
1106 case glslang::EOpConstructDVec3:
1107 case glslang::EOpConstructDVec4:
1108 case glslang::EOpConstructBool:
1109 case glslang::EOpConstructBVec2:
1110 case glslang::EOpConstructBVec3:
1111 case glslang::EOpConstructBVec4:
1112 case glslang::EOpConstructInt:
1113 case glslang::EOpConstructIVec2:
1114 case glslang::EOpConstructIVec3:
1115 case glslang::EOpConstructIVec4:
1116 case glslang::EOpConstructUint:
1117 case glslang::EOpConstructUVec2:
1118 case glslang::EOpConstructUVec3:
1119 case glslang::EOpConstructUVec4:
1120 case glslang::EOpConstructStruct:
1121 {
1122 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001123 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001124 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1125 spv::Id constructed;
1126 if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
1127 std::vector<spv::Id> constituents;
1128 for (int c = 0; c < (int)arguments.size(); ++c)
1129 constituents.push_back(arguments[c]);
1130 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001131 } else if (isMatrix)
1132 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1133 else
1134 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001135
1136 builder.clearAccessChain();
1137 builder.setAccessChainRValue(constructed);
1138
1139 return false;
1140 }
1141
1142 // These six are component-wise compares with component-wise results.
1143 // Forward on to createBinaryOperation(), requesting a vector result.
1144 case glslang::EOpLessThan:
1145 case glslang::EOpGreaterThan:
1146 case glslang::EOpLessThanEqual:
1147 case glslang::EOpGreaterThanEqual:
1148 case glslang::EOpVectorEqual:
1149 case glslang::EOpVectorNotEqual:
1150 {
1151 // Map the operation to a binary
1152 binOp = node->getOp();
1153 reduceComparison = false;
1154 switch (node->getOp()) {
1155 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1156 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1157 default: binOp = node->getOp(); break;
1158 }
1159
1160 break;
1161 }
1162 case glslang::EOpMul:
1163 // compontent-wise matrix multiply
1164 binOp = glslang::EOpMul;
1165 break;
1166 case glslang::EOpOuterProduct:
1167 // two vectors multiplied to make a matrix
1168 binOp = glslang::EOpOuterProduct;
1169 break;
1170 case glslang::EOpDot:
1171 {
1172 // for scalar dot product, use multiply
1173 glslang::TIntermSequence& glslangOperands = node->getSequence();
1174 if (! glslangOperands[0]->getAsTyped()->isVector())
1175 binOp = glslang::EOpMul;
1176 break;
1177 }
1178 case glslang::EOpMod:
1179 // when an aggregate, this is the floating-point mod built-in function,
1180 // which can be emitted by the one in createBinaryOperation()
1181 binOp = glslang::EOpMod;
1182 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001183 case glslang::EOpEmitVertex:
1184 case glslang::EOpEndPrimitive:
1185 case glslang::EOpBarrier:
1186 case glslang::EOpMemoryBarrier:
1187 case glslang::EOpMemoryBarrierAtomicCounter:
1188 case glslang::EOpMemoryBarrierBuffer:
1189 case glslang::EOpMemoryBarrierImage:
1190 case glslang::EOpMemoryBarrierShared:
1191 case glslang::EOpGroupMemoryBarrier:
1192 noReturnValue = true;
1193 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1194 break;
1195
John Kessenich426394d2015-07-23 10:22:48 -06001196 case glslang::EOpAtomicAdd:
1197 case glslang::EOpAtomicMin:
1198 case glslang::EOpAtomicMax:
1199 case glslang::EOpAtomicAnd:
1200 case glslang::EOpAtomicOr:
1201 case glslang::EOpAtomicXor:
1202 case glslang::EOpAtomicExchange:
1203 case glslang::EOpAtomicCompSwap:
1204 atomic = true;
1205 break;
1206
John Kessenich140f3df2015-06-26 16:58:36 -06001207 default:
1208 break;
1209 }
1210
1211 //
1212 // See if it maps to a regular operation.
1213 //
John Kessenich140f3df2015-06-26 16:58:36 -06001214 if (binOp != glslang::EOpNull) {
1215 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1216 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1217 assert(left && right);
1218
1219 builder.clearAccessChain();
1220 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001221 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001222
1223 builder.clearAccessChain();
1224 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001225 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001226
1227 result = createBinaryOperation(binOp, precision,
1228 convertGlslangToSpvType(node->getType()), leftId, rightId,
1229 left->getType().getBasicType(), reduceComparison);
1230
1231 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001232 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001233 builder.clearAccessChain();
1234 builder.setAccessChainRValue(result);
1235
1236 return false;
1237 }
1238
John Kessenich426394d2015-07-23 10:22:48 -06001239 //
1240 // Create the list of operands.
1241 //
John Kessenich140f3df2015-06-26 16:58:36 -06001242 glslang::TIntermSequence& glslangOperands = node->getSequence();
1243 std::vector<spv::Id> operands;
1244 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1245 builder.clearAccessChain();
1246 glslangOperands[arg]->traverse(this);
1247
1248 // special case l-value operands; there are just a few
1249 bool lvalue = false;
1250 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001251 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001252 case glslang::EOpModf:
1253 if (arg == 1)
1254 lvalue = true;
1255 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001256 case glslang::EOpInterpolateAtSample:
1257 case glslang::EOpInterpolateAtOffset:
1258 if (arg == 0)
1259 lvalue = true;
1260 break;
Rex Xud4782c12015-09-06 16:30:11 +08001261 case glslang::EOpAtomicAdd:
1262 case glslang::EOpAtomicMin:
1263 case glslang::EOpAtomicMax:
1264 case glslang::EOpAtomicAnd:
1265 case glslang::EOpAtomicOr:
1266 case glslang::EOpAtomicXor:
1267 case glslang::EOpAtomicExchange:
1268 case glslang::EOpAtomicCompSwap:
1269 if (arg == 0)
1270 lvalue = true;
1271 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001272 case glslang::EOpAddCarry:
1273 case glslang::EOpSubBorrow:
1274 if (arg == 2)
1275 lvalue = true;
1276 break;
1277 case glslang::EOpUMulExtended:
1278 case glslang::EOpIMulExtended:
1279 if (arg >= 2)
1280 lvalue = true;
1281 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001282 default:
1283 break;
1284 }
1285 if (lvalue)
1286 operands.push_back(builder.accessChainGetLValue());
1287 else
John Kessenich32cfd492016-02-02 12:37:46 -07001288 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001289 }
John Kessenich426394d2015-07-23 10:22:48 -06001290
1291 if (atomic) {
1292 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001293 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001294 } else {
1295 // Pass through to generic operations.
1296 switch (glslangOperands.size()) {
1297 case 0:
1298 result = createNoArgOperation(node->getOp());
1299 break;
1300 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001301 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001302 break;
1303 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001304 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001305 break;
1306 }
John Kessenich140f3df2015-06-26 16:58:36 -06001307 }
1308
1309 if (noReturnValue)
1310 return false;
1311
1312 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001313 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001314 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001315 } else {
1316 builder.clearAccessChain();
1317 builder.setAccessChainRValue(result);
1318 return false;
1319 }
1320}
1321
1322bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1323{
1324 // This path handles both if-then-else and ?:
1325 // The if-then-else has a node type of void, while
1326 // ?: has a non-void node type
1327 spv::Id result = 0;
1328 if (node->getBasicType() != glslang::EbtVoid) {
1329 // don't handle this as just on-the-fly temporaries, because there will be two names
1330 // and better to leave SSA to later passes
1331 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1332 }
1333
1334 // emit the condition before doing anything with selection
1335 node->getCondition()->traverse(this);
1336
1337 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001338 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001339
1340 if (node->getTrueBlock()) {
1341 // emit the "then" statement
1342 node->getTrueBlock()->traverse(this);
1343 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001344 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001345 }
1346
1347 if (node->getFalseBlock()) {
1348 ifBuilder.makeBeginElse();
1349 // emit the "else" statement
1350 node->getFalseBlock()->traverse(this);
1351 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001352 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001353 }
1354
1355 ifBuilder.makeEndIf();
1356
1357 if (result) {
1358 // GLSL only has r-values as the result of a :?, but
1359 // if we have an l-value, that can be more efficient if it will
1360 // become the base of a complex r-value expression, because the
1361 // next layer copies r-values into memory to use the access-chain mechanism
1362 builder.clearAccessChain();
1363 builder.setAccessChainLValue(result);
1364 }
1365
1366 return false;
1367}
1368
1369bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1370{
1371 // emit and get the condition before doing anything with switch
1372 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001373 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001374
1375 // browse the children to sort out code segments
1376 int defaultSegment = -1;
1377 std::vector<TIntermNode*> codeSegments;
1378 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1379 std::vector<int> caseValues;
1380 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1381 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1382 TIntermNode* child = *c;
1383 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001384 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001385 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001386 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001387 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1388 } else
1389 codeSegments.push_back(child);
1390 }
1391
1392 // handle the case where the last code segment is missing, due to no code
1393 // statements between the last case and the end of the switch statement
1394 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1395 (int)codeSegments.size() == defaultSegment)
1396 codeSegments.push_back(nullptr);
1397
1398 // make the switch statement
1399 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001400 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001401
1402 // emit all the code in the segments
1403 breakForLoop.push(false);
1404 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1405 builder.nextSwitchSegment(segmentBlocks, s);
1406 if (codeSegments[s])
1407 codeSegments[s]->traverse(this);
1408 else
1409 builder.addSwitchBreak();
1410 }
1411 breakForLoop.pop();
1412
1413 builder.endSwitch(segmentBlocks);
1414
1415 return false;
1416}
1417
1418void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1419{
1420 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001421 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001422
1423 builder.clearAccessChain();
1424 builder.setAccessChainRValue(constant);
1425}
1426
1427bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1428{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001429 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001430 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001431 // Spec requires back edges to target header blocks, and every header block
1432 // must dominate its merge block. Make a header block first to ensure these
1433 // conditions are met. By definition, it will contain OpLoopMerge, followed
1434 // by a block-ending branch. But we don't want to put any other body/test
1435 // instructions in it, since the body/test may have arbitrary instructions,
1436 // including merges of its own.
1437 builder.setBuildPoint(&blocks.head);
1438 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001439 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001440 spv::Block& test = builder.makeNewBlock();
1441 builder.createBranch(&test);
1442
1443 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001444 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001445 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001446 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001447 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1448
1449 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001450 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001451 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001452 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001453 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001454 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001455
1456 builder.setBuildPoint(&blocks.continue_target);
1457 if (node->getTerminal())
1458 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001459 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001460 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001461 builder.createBranch(&blocks.body);
1462
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001463 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001464 builder.setBuildPoint(&blocks.body);
1465 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001466 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001467 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001468 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001469
1470 builder.setBuildPoint(&blocks.continue_target);
1471 if (node->getTerminal())
1472 node->getTerminal()->traverse(this);
1473 if (node->getTest()) {
1474 node->getTest()->traverse(this);
1475 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001476 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001477 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001478 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001479 // TODO: unless there was a break/return/discard instruction
1480 // somewhere in the body, this is an infinite loop, so we should
1481 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001482 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001483 }
John Kessenich140f3df2015-06-26 16:58:36 -06001484 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001485 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001486 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001487 return false;
1488}
1489
1490bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1491{
1492 if (node->getExpression())
1493 node->getExpression()->traverse(this);
1494
1495 switch (node->getFlowOp()) {
1496 case glslang::EOpKill:
1497 builder.makeDiscard();
1498 break;
1499 case glslang::EOpBreak:
1500 if (breakForLoop.top())
1501 builder.createLoopExit();
1502 else
1503 builder.addSwitchBreak();
1504 break;
1505 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001506 builder.createLoopContinue();
1507 break;
1508 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001509 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001510 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001511 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001512 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001513
1514 builder.clearAccessChain();
1515 break;
1516
1517 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001518 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001519 break;
1520 }
1521
1522 return false;
1523}
1524
1525spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1526{
1527 // First, steer off constants, which are not SPIR-V variables, but
1528 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001529 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001530 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001531 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001532 }
1533
1534 // Now, handle actual variables
1535 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1536 spv::Id spvType = convertGlslangToSpvType(node->getType());
1537
1538 const char* name = node->getName().c_str();
1539 if (glslang::IsAnonymous(name))
1540 name = "";
1541
1542 return builder.createVariable(storageClass, spvType, name);
1543}
1544
1545// Return type Id of the sampled type.
1546spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1547{
1548 switch (sampler.type) {
1549 case glslang::EbtFloat: return builder.makeFloatType(32);
1550 case glslang::EbtInt: return builder.makeIntType(32);
1551 case glslang::EbtUint: return builder.makeUintType(32);
1552 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001553 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001554 return builder.makeFloatType(32);
1555 }
1556}
1557
John Kessenich3ac051e2015-12-20 11:29:16 -07001558// Convert from a glslang type to an SPV type, by calling into a
1559// recursive version of this function. This establishes the inherited
1560// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001561spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1562{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001563 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001564}
1565
1566// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001567// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001568spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001569{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001570 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001571
1572 switch (type.getBasicType()) {
1573 case glslang::EbtVoid:
1574 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001575 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001576 break;
1577 case glslang::EbtFloat:
1578 spvType = builder.makeFloatType(32);
1579 break;
1580 case glslang::EbtDouble:
1581 spvType = builder.makeFloatType(64);
1582 break;
1583 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001584 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1585 // a 32-bit int where non-0 means true.
1586 if (explicitLayout != glslang::ElpNone)
1587 spvType = builder.makeUintType(32);
1588 else
1589 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001590 break;
1591 case glslang::EbtInt:
1592 spvType = builder.makeIntType(32);
1593 break;
1594 case glslang::EbtUint:
1595 spvType = builder.makeUintType(32);
1596 break;
John Kessenich426394d2015-07-23 10:22:48 -06001597 case glslang::EbtAtomicUint:
1598 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1599 spvType = builder.makeUintType(32);
1600 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001601 case glslang::EbtSampler:
1602 {
1603 const glslang::TSampler& sampler = type.getSampler();
John Kesseniche0b6cad2015-12-24 10:30:13 -07001604 // an image is present, make its type
1605 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1606 sampler.image ? 2 : 1, TranslateImageFormat(type));
John Kessenich55e7d112015-11-15 21:33:39 -07001607 if (! sampler.image) {
John Kesseniche0b6cad2015-12-24 10:30:13 -07001608 spvType = builder.makeSampledImageType(spvType);
John Kessenich55e7d112015-11-15 21:33:39 -07001609 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001610 }
John Kessenich140f3df2015-06-26 16:58:36 -06001611 break;
1612 case glslang::EbtStruct:
1613 case glslang::EbtBlock:
1614 {
1615 // If we've seen this struct type, return it
1616 const glslang::TTypeList* glslangStruct = type.getStruct();
1617 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001618
1619 // Try to share structs for different layouts, but not yet for other
1620 // kinds of qualification (primarily not yet including interpolant qualification).
1621 if (! HasNonLayoutQualifiers(qualifier))
1622 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1623 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001624 break;
1625
1626 // else, we haven't seen it...
1627
1628 // Create a vector of struct types for SPIR-V to consume
1629 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1630 if (type.getBasicType() == glslang::EbtBlock)
1631 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001632 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001633 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1634 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1635 if (glslangType.hiddenMember()) {
1636 ++memberDelta;
1637 if (type.getBasicType() == glslang::EbtBlock)
1638 memberRemapper[glslangStruct][i] = -1;
1639 } else {
1640 if (type.getBasicType() == glslang::EbtBlock)
1641 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001642 // modify just this child's view of the qualifier
1643 glslang::TQualifier subQualifier = glslangType.getQualifier();
1644 InheritQualifiers(subQualifier, qualifier);
John Kessenich7b9fa252016-01-21 18:56:57 -07001645 if (qualifier.hasLocation()) {
1646 subQualifier.layoutLocation += locationOffset;
1647 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1648 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001649 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001650 }
1651 }
1652
1653 // Make the SPIR-V type
1654 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001655 if (! HasNonLayoutQualifiers(qualifier))
1656 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001657
1658 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001659 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001660 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001661 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1662 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1663 int member = i;
1664 if (type.getBasicType() == glslang::EbtBlock)
1665 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001666
John Kesseniche0b6cad2015-12-24 10:30:13 -07001667 // modify just this child's view of the qualifier
1668 glslang::TQualifier subQualifier = glslangType.getQualifier();
1669 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001670
John Kessenich140f3df2015-06-26 16:58:36 -06001671 // using -1 above to indicate a hidden member
1672 if (member >= 0) {
1673 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001674 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001675 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001676 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1677 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich7b9fa252016-01-21 18:56:57 -07001678 if (qualifier.hasLocation()) {
1679 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, qualifier.layoutLocation + locationOffset);
1680 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1681 }
John Kessenich140f3df2015-06-26 16:58:36 -06001682 if (glslangType.getQualifier().hasComponent())
1683 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1684 if (glslangType.getQualifier().hasXfbOffset())
1685 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001686 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001687 // figure out what to do with offset, which is accumulating
1688 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001689 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001690 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001691 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001692 offset = nextOffset;
1693 }
John Kessenich140f3df2015-06-26 16:58:36 -06001694
John Kessenichf85e8062015-12-19 13:57:10 -07001695 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001696 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001697
John Kessenich140f3df2015-06-26 16:58:36 -06001698 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001699 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1700 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001701 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001702 }
1703 }
1704
1705 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001706 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001707 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001708 if (type.getQualifier().hasStream()) {
1709 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001710 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001711 }
John Kessenich140f3df2015-06-26 16:58:36 -06001712 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001713 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001714 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001715 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001716 if (type.getQualifier().hasXfbBuffer())
1717 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1718 }
1719 }
1720 break;
1721 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001722 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001723 break;
1724 }
1725
1726 if (type.isMatrix())
1727 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1728 else {
1729 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1730 if (type.getVectorSize() > 1)
1731 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1732 }
1733
1734 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001735 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1736
John Kessenichc9a80832015-09-12 12:17:44 -06001737 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001738 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001739 // We need to decorate array strides for types needing explicit layout, except blocks.
1740 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001741 // Use a dummy glslang type for querying internal strides of
1742 // arrays of arrays, but using just a one-dimensional array.
1743 glslang::TType simpleArrayType(type, 0); // deference type of the array
1744 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1745 simpleArrayType.getArraySizes().dereference();
1746
1747 // Will compute the higher-order strides here, rather than making a whole
1748 // pile of types and doing repetitive recursion on their contents.
1749 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1750 }
John Kessenichf8842e52016-01-04 19:22:56 -07001751
1752 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001753 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
1754 int size = type.getArraySizes()->getDimSize(dim);
1755 assert(size > 0);
1756 spvType = builder.makeArrayType(spvType, size, stride);
1757 if (stride > 0)
1758 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
1759 stride *= size;
1760 }
1761 } else {
1762 // single-dimensional array, and don't yet have stride
1763
John Kessenichf8842e52016-01-04 19:22:56 -07001764 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001765 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1766 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001767 }
John Kessenich31ed4832015-09-09 17:51:38 -06001768
John Kessenichc9a80832015-09-12 12:17:44 -06001769 // Do the outer dimension, which might not be known for a runtime-sized array
1770 if (type.isRuntimeSizedArray()) {
1771 spvType = builder.makeRuntimeArray(spvType);
1772 } else {
1773 assert(type.getOuterArraySize() > 0);
John Kessenichc9e0a422015-12-29 21:27:24 -07001774 spvType = builder.makeArrayType(spvType, type.getOuterArraySize(), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001775 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001776 if (stride > 0)
1777 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001778 }
1779
1780 return spvType;
1781}
1782
John Kessenich103bef92016-02-08 21:38:15 -07001783// Wrap the builder's accessChainLoad to:
1784// - localize handling of RelaxedPrecision
1785// - use the SPIR-V inferred type instead of another conversion of the glslang type
1786// (avoids unnecessary work and possible type punning for structures)
1787// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001788spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1789{
John Kessenich103bef92016-02-08 21:38:15 -07001790 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1791 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1792
1793 // Need to convert to abstract types when necessary
1794 if (builder.isScalarType(nominalTypeId) && type.getBasicType() == glslang::EbtBool && nominalTypeId != builder.makeBoolType())
1795 loadedId = builder.createBinOp(spv::OpINotEqual, builder.makeBoolType(), loadedId, builder.makeUintConstant(0));
1796
1797 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001798}
1799
John Kessenichf85e8062015-12-19 13:57:10 -07001800// Decide whether or not this type should be
1801// decorated with offsets and strides, and if so
1802// whether std140 or std430 rules should be applied.
1803glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001804{
John Kessenichf85e8062015-12-19 13:57:10 -07001805 // has to be a block
1806 if (type.getBasicType() != glslang::EbtBlock)
1807 return glslang::ElpNone;
1808
1809 // has to be a uniform or buffer block
1810 if (type.getQualifier().storage != glslang::EvqUniform &&
1811 type.getQualifier().storage != glslang::EvqBuffer)
1812 return glslang::ElpNone;
1813
1814 // return the layout to use
1815 switch (type.getQualifier().layoutPacking) {
1816 case glslang::ElpStd140:
1817 case glslang::ElpStd430:
1818 return type.getQualifier().layoutPacking;
1819 default:
1820 return glslang::ElpNone;
1821 }
John Kessenich31ed4832015-09-09 17:51:38 -06001822}
1823
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001824// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001825int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001826{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001827 int size;
John Kessenich49987892015-12-29 17:11:44 -07001828 int stride;
1829 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001830
1831 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001832}
1833
John Kessenich49987892015-12-29 17:11:44 -07001834// 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 -07001835// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001836int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001837{
John Kessenich49987892015-12-29 17:11:44 -07001838 glslang::TType elementType;
1839 elementType.shallowCopy(matrixType);
1840 elementType.clearArraySizes();
1841
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001842 int size;
John Kessenich49987892015-12-29 17:11:44 -07001843 int stride;
1844 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1845
1846 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001847}
1848
John Kessenich5e4b1242015-08-06 22:53:06 -06001849// Given a member type of a struct, realign the current offset for it, and compute
1850// the next (not yet aligned) offset for the next member, which will get aligned
1851// on the next call.
1852// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1853// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1854// -1 means a non-forced member offset (no decoration needed).
John Kessenichf85e8062015-12-19 13:57:10 -07001855void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001856 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001857{
1858 // this will get a positive value when deemed necessary
1859 nextOffset = -1;
1860
John Kessenich5e4b1242015-08-06 22:53:06 -06001861 // override anything in currentOffset with user-set offset
1862 if (memberType.getQualifier().hasOffset())
1863 currentOffset = memberType.getQualifier().layoutOffset;
1864
1865 // It could be that current linker usage in glslang updated all the layoutOffset,
1866 // in which case the following code does not matter. But, that's not quite right
1867 // once cross-compilation unit GLSL validation is done, as the original user
1868 // settings are needed in layoutOffset, and then the following will come into play.
1869
John Kessenichf85e8062015-12-19 13:57:10 -07001870 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001871 if (! memberType.getQualifier().hasOffset())
1872 currentOffset = -1;
1873
1874 return;
1875 }
1876
John Kessenichf85e8062015-12-19 13:57:10 -07001877 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001878 if (currentOffset < 0)
1879 currentOffset = 0;
1880
1881 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1882 // but possibly not yet correctly aligned.
1883
1884 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001885 int dummyStride;
1886 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001887 glslang::RoundToPow2(currentOffset, memberAlignment);
1888 nextOffset = currentOffset + memberSize;
1889}
1890
John Kessenich140f3df2015-06-26 16:58:36 -06001891bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1892{
1893 return node->getName() == "main(";
1894}
1895
1896// Make all the functions, skeletally, without actually visiting their bodies.
1897void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1898{
1899 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1900 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
1901 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
1902 continue;
1903
1904 // We're on a user function. Set up the basic interface for the function now,
1905 // so that it's available to call.
1906 // Translating the body will happen later.
1907 //
1908 // Typically (except for a "const in" parameter), an address will be passed to the
1909 // function. What it is an address of varies:
1910 //
1911 // - "in" parameters not marked as "const" can be written to without modifying the argument,
1912 // so that write needs to be to a copy, hence the address of a copy works.
1913 //
1914 // - "const in" parameters can just be the r-value, as no writes need occur.
1915 //
1916 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
1917 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
1918
1919 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07001920 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06001921 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
1922
1923 for (int p = 0; p < (int)parameters.size(); ++p) {
1924 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
1925 spv::Id typeId = convertGlslangToSpvType(paramType);
1926 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
1927 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
1928 else
1929 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07001930 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06001931 paramTypes.push_back(typeId);
1932 }
1933
1934 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07001935 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
1936 convertGlslangToSpvType(glslFunction->getType()),
1937 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06001938
1939 // Track function to emit/call later
1940 functionMap[glslFunction->getName().c_str()] = function;
1941
1942 // Set the parameter id's
1943 for (int p = 0; p < (int)parameters.size(); ++p) {
1944 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
1945 // give a name too
1946 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
1947 }
1948 }
1949}
1950
1951// Process all the initializers, while skipping the functions and link objects
1952void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
1953{
1954 builder.setBuildPoint(shaderEntry->getLastBlock());
1955 for (int i = 0; i < (int)initializers.size(); ++i) {
1956 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
1957 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
1958
1959 // We're on a top-level node that's not a function. Treat as an initializer, whose
1960 // code goes into the beginning of main.
1961 initializer->traverse(this);
1962 }
1963 }
1964}
1965
1966// Process all the functions, while skipping initializers.
1967void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
1968{
1969 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1970 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
1971 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
1972 node->traverse(this);
1973 }
1974}
1975
1976void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
1977{
1978 // SPIR-V functions should already be in the functionMap from the prepass
1979 // that called makeFunctions().
1980 spv::Function* function = functionMap[node->getName().c_str()];
1981 spv::Block* functionBlock = function->getEntryBlock();
1982 builder.setBuildPoint(functionBlock);
1983}
1984
Rex Xu04db3f52015-09-16 11:44:02 +08001985void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06001986{
Rex Xufc618912015-09-09 16:42:49 +08001987 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08001988
1989 glslang::TSampler sampler = {};
1990 bool cubeCompare = false;
1991 if (node.isTexture()) {
1992 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
1993 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
1994 }
1995
John Kessenich140f3df2015-06-26 16:58:36 -06001996 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
1997 builder.clearAccessChain();
1998 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08001999
2000 // Special case l-value operands
2001 bool lvalue = false;
2002 switch (node.getOp()) {
2003 case glslang::EOpImageAtomicAdd:
2004 case glslang::EOpImageAtomicMin:
2005 case glslang::EOpImageAtomicMax:
2006 case glslang::EOpImageAtomicAnd:
2007 case glslang::EOpImageAtomicOr:
2008 case glslang::EOpImageAtomicXor:
2009 case glslang::EOpImageAtomicExchange:
2010 case glslang::EOpImageAtomicCompSwap:
2011 if (i == 0)
2012 lvalue = true;
2013 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002014 case glslang::EOpSparseTexture:
2015 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2016 lvalue = true;
2017 break;
2018 case glslang::EOpSparseTextureClamp:
2019 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2020 lvalue = true;
2021 break;
2022 case glslang::EOpSparseTextureLod:
2023 case glslang::EOpSparseTextureOffset:
2024 if (i == 3)
2025 lvalue = true;
2026 break;
2027 case glslang::EOpSparseTextureFetch:
2028 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2029 lvalue = true;
2030 break;
2031 case glslang::EOpSparseTextureFetchOffset:
2032 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2033 lvalue = true;
2034 break;
2035 case glslang::EOpSparseTextureLodOffset:
2036 case glslang::EOpSparseTextureGrad:
2037 case glslang::EOpSparseTextureOffsetClamp:
2038 if (i == 4)
2039 lvalue = true;
2040 break;
2041 case glslang::EOpSparseTextureGradOffset:
2042 case glslang::EOpSparseTextureGradClamp:
2043 if (i == 5)
2044 lvalue = true;
2045 break;
2046 case glslang::EOpSparseTextureGradOffsetClamp:
2047 if (i == 6)
2048 lvalue = true;
2049 break;
2050 case glslang::EOpSparseTextureGather:
2051 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2052 lvalue = true;
2053 break;
2054 case glslang::EOpSparseTextureGatherOffset:
2055 case glslang::EOpSparseTextureGatherOffsets:
2056 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2057 lvalue = true;
2058 break;
Rex Xufc618912015-09-09 16:42:49 +08002059 default:
2060 break;
2061 }
2062
Rex Xu6b86d492015-09-16 17:48:22 +08002063 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002064 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002065 else
John Kessenich32cfd492016-02-02 12:37:46 -07002066 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002067 }
2068}
2069
John Kessenichfc51d282015-08-19 13:34:18 -06002070void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002071{
John Kessenichfc51d282015-08-19 13:34:18 -06002072 builder.clearAccessChain();
2073 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002074 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002075}
John Kessenich140f3df2015-06-26 16:58:36 -06002076
John Kessenichfc51d282015-08-19 13:34:18 -06002077spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2078{
Rex Xufc618912015-09-09 16:42:49 +08002079 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002080 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002081 }
2082
John Kessenichfc51d282015-08-19 13:34:18 -06002083 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002084 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2085 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2086 std::vector<spv::Id> arguments;
2087 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002088 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002089 else
2090 translateArguments(*node->getAsUnaryNode(), arguments);
2091 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2092
2093 spv::Builder::TextureParameters params = { };
2094 params.sampler = arguments[0];
2095
Rex Xu04db3f52015-09-16 11:44:02 +08002096 glslang::TCrackedTextureOp cracked;
2097 node->crackTexture(sampler, cracked);
2098
John Kessenichfc51d282015-08-19 13:34:18 -06002099 // Check for queries
2100 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002101 // a sampled image needs to have the image extracted first
2102 if (builder.isSampledImage(params.sampler))
2103 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002104 switch (node->getOp()) {
2105 case glslang::EOpImageQuerySize:
2106 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002107 if (arguments.size() > 1) {
2108 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002109 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002110 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002111 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002112 case glslang::EOpImageQuerySamples:
2113 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002114 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002115 case glslang::EOpTextureQueryLod:
2116 params.coords = arguments[1];
2117 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2118 case glslang::EOpTextureQueryLevels:
2119 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002120 case glslang::EOpSparseTexelsResident:
2121 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002122 default:
2123 assert(0);
2124 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002125 }
John Kessenich140f3df2015-06-26 16:58:36 -06002126 }
2127
Rex Xufc618912015-09-09 16:42:49 +08002128 // Check for image functions other than queries
2129 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002130 std::vector<spv::Id> operands;
2131 auto opIt = arguments.begin();
2132 operands.push_back(*(opIt++));
2133 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002134 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002135 if (sampler.ms) {
2136 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002137 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002138 }
John Kessenich56bab042015-09-16 10:54:31 -06002139 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2140 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002141 if (sampler.ms) {
2142 operands.push_back(*(opIt + 1));
2143 operands.push_back(spv::ImageOperandsSampleMask);
2144 operands.push_back(*opIt);
2145 } else
2146 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002147 builder.createNoResultOp(spv::OpImageWrite, operands);
2148 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002149 } else if (node->isSparseImage()) {
2150 spv::MissingFunctionality("sparse image functions");
2151 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002152 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002153 // Process image atomic operations
2154
2155 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2156 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002157 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002158
Rex Xufc618912015-09-09 16:42:49 +08002159 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002160 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002161
2162 std::vector<spv::Id> operands;
2163 operands.push_back(pointer);
2164 for (; opIt != arguments.end(); ++opIt)
2165 operands.push_back(*opIt);
2166
Rex Xu04db3f52015-09-16 11:44:02 +08002167 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002168 }
2169 }
2170
2171 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002172 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002173 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2174
John Kessenichfc51d282015-08-19 13:34:18 -06002175 // check for bias argument
2176 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002177 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002178 int nonBiasArgCount = 2;
2179 if (cracked.offset)
2180 ++nonBiasArgCount;
2181 if (cracked.grad)
2182 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002183 if (cracked.lodClamp)
2184 ++nonBiasArgCount;
2185 if (sparse)
2186 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002187
2188 if ((int)arguments.size() > nonBiasArgCount)
2189 bias = true;
2190 }
2191
John Kessenichfc51d282015-08-19 13:34:18 -06002192 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002193
John Kessenichfc51d282015-08-19 13:34:18 -06002194 params.coords = arguments[1];
2195 int extraArgs = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07002196
2197 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002198 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002199 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002200 ++extraArgs;
2201 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002202 params.Dref = arguments[2];
2203 ++extraArgs;
2204 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002205 std::vector<spv::Id> indexes;
2206 int comp;
2207 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002208 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002209 else
2210 comp = builder.getNumComponents(params.coords) - 1;
2211 indexes.push_back(comp);
2212 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2213 }
2214 if (cracked.lod) {
2215 params.lod = arguments[2];
2216 ++extraArgs;
Rex Xu6b86d492015-09-16 17:48:22 +08002217 } else if (sampler.ms) {
2218 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002219 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002220 }
2221 if (cracked.grad) {
2222 params.gradX = arguments[2 + extraArgs];
2223 params.gradY = arguments[3 + extraArgs];
2224 extraArgs += 2;
2225 }
John Kessenich55e7d112015-11-15 21:33:39 -07002226 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002227 params.offset = arguments[2 + extraArgs];
2228 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002229 } else if (cracked.offsets) {
2230 params.offsets = arguments[2 + extraArgs];
2231 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002232 }
Rex Xu48edadf2015-12-31 16:11:41 +08002233 if (cracked.lodClamp) {
2234 params.lodClamp = arguments[2 + extraArgs];
2235 ++extraArgs;
2236 }
2237 if (sparse) {
2238 params.texelOut = arguments[2 + extraArgs];
2239 ++extraArgs;
2240 }
John Kessenichfc51d282015-08-19 13:34:18 -06002241 if (bias) {
2242 params.bias = arguments[2 + extraArgs];
2243 ++extraArgs;
2244 }
John Kessenich55e7d112015-11-15 21:33:39 -07002245 if (cracked.gather && ! sampler.shadow) {
2246 // default component is 0, if missing, otherwise an argument
2247 if (2 + extraArgs < (int)arguments.size()) {
2248 params.comp = arguments[2 + extraArgs];
2249 ++extraArgs;
2250 } else {
2251 params.comp = builder.makeIntConstant(0);
2252 }
2253 }
John Kessenichfc51d282015-08-19 13:34:18 -06002254
Rex Xu48edadf2015-12-31 16:11:41 +08002255 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002256}
2257
2258spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2259{
2260 // Grab the function's pointer from the previously created function
2261 spv::Function* function = functionMap[node->getName().c_str()];
2262 if (! function)
2263 return 0;
2264
2265 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2266 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2267
2268 // See comments in makeFunctions() for details about the semantics for parameter passing.
2269 //
2270 // These imply we need a four step process:
2271 // 1. Evaluate the arguments
2272 // 2. Allocate and make copies of in, out, and inout arguments
2273 // 3. Make the call
2274 // 4. Copy back the results
2275
2276 // 1. Evaluate the arguments
2277 std::vector<spv::Builder::AccessChain> lValues;
2278 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002279 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002280 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2281 // build l-value
2282 builder.clearAccessChain();
2283 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002284 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002285 // keep outputs as l-values, evaluate input-only as r-values
2286 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2287 // save l-value
2288 lValues.push_back(builder.getAccessChain());
2289 } else {
2290 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002291 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002292 }
2293 }
2294
2295 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2296 // copy the original into that space.
2297 //
2298 // Also, build up the list of actual arguments to pass in for the call
2299 int lValueCount = 0;
2300 int rValueCount = 0;
2301 std::vector<spv::Id> spvArgs;
2302 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2303 spv::Id arg;
2304 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2305 // need space to hold the copy
2306 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2307 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2308 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2309 // need to copy the input into output space
2310 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002311 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002312 builder.createStore(copy, arg);
2313 }
2314 ++lValueCount;
2315 } else {
2316 arg = rValues[rValueCount];
2317 ++rValueCount;
2318 }
2319 spvArgs.push_back(arg);
2320 }
2321
2322 // 3. Make the call.
2323 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002324 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002325
2326 // 4. Copy back out an "out" arguments.
2327 lValueCount = 0;
2328 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2329 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2330 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2331 spv::Id copy = builder.createLoad(spvArgs[a]);
2332 builder.setAccessChain(lValues[lValueCount]);
2333 builder.accessChainStore(copy);
2334 }
2335 ++lValueCount;
2336 }
2337 }
2338
2339 return result;
2340}
2341
2342// Translate AST operation to SPV operation, already having SPV-based operands/types.
2343spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2344 spv::Id typeId, spv::Id left, spv::Id right,
2345 glslang::TBasicType typeProxy, bool reduceComparison)
2346{
2347 bool isUnsigned = typeProxy == glslang::EbtUint;
2348 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2349
2350 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002351 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002352 bool comparison = false;
2353
2354 switch (op) {
2355 case glslang::EOpAdd:
2356 case glslang::EOpAddAssign:
2357 if (isFloat)
2358 binOp = spv::OpFAdd;
2359 else
2360 binOp = spv::OpIAdd;
2361 break;
2362 case glslang::EOpSub:
2363 case glslang::EOpSubAssign:
2364 if (isFloat)
2365 binOp = spv::OpFSub;
2366 else
2367 binOp = spv::OpISub;
2368 break;
2369 case glslang::EOpMul:
2370 case glslang::EOpMulAssign:
2371 if (isFloat)
2372 binOp = spv::OpFMul;
2373 else
2374 binOp = spv::OpIMul;
2375 break;
2376 case glslang::EOpVectorTimesScalar:
2377 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002378 if (isFloat) {
2379 if (builder.isVector(right))
2380 std::swap(left, right);
2381 assert(builder.isScalar(right));
2382 needMatchingVectors = false;
2383 binOp = spv::OpVectorTimesScalar;
2384 } else
2385 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002386 break;
2387 case glslang::EOpVectorTimesMatrix:
2388 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002389 binOp = spv::OpVectorTimesMatrix;
2390 break;
2391 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002392 binOp = spv::OpMatrixTimesVector;
2393 break;
2394 case glslang::EOpMatrixTimesScalar:
2395 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002396 binOp = spv::OpMatrixTimesScalar;
2397 break;
2398 case glslang::EOpMatrixTimesMatrix:
2399 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002400 binOp = spv::OpMatrixTimesMatrix;
2401 break;
2402 case glslang::EOpOuterProduct:
2403 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002404 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002405 break;
2406
2407 case glslang::EOpDiv:
2408 case glslang::EOpDivAssign:
2409 if (isFloat)
2410 binOp = spv::OpFDiv;
2411 else if (isUnsigned)
2412 binOp = spv::OpUDiv;
2413 else
2414 binOp = spv::OpSDiv;
2415 break;
2416 case glslang::EOpMod:
2417 case glslang::EOpModAssign:
2418 if (isFloat)
2419 binOp = spv::OpFMod;
2420 else if (isUnsigned)
2421 binOp = spv::OpUMod;
2422 else
2423 binOp = spv::OpSMod;
2424 break;
2425 case glslang::EOpRightShift:
2426 case glslang::EOpRightShiftAssign:
2427 if (isUnsigned)
2428 binOp = spv::OpShiftRightLogical;
2429 else
2430 binOp = spv::OpShiftRightArithmetic;
2431 break;
2432 case glslang::EOpLeftShift:
2433 case glslang::EOpLeftShiftAssign:
2434 binOp = spv::OpShiftLeftLogical;
2435 break;
2436 case glslang::EOpAnd:
2437 case glslang::EOpAndAssign:
2438 binOp = spv::OpBitwiseAnd;
2439 break;
2440 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002441 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002442 binOp = spv::OpLogicalAnd;
2443 break;
2444 case glslang::EOpInclusiveOr:
2445 case glslang::EOpInclusiveOrAssign:
2446 binOp = spv::OpBitwiseOr;
2447 break;
2448 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002449 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002450 binOp = spv::OpLogicalOr;
2451 break;
2452 case glslang::EOpExclusiveOr:
2453 case glslang::EOpExclusiveOrAssign:
2454 binOp = spv::OpBitwiseXor;
2455 break;
2456 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002457 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002458 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002459 break;
2460
2461 case glslang::EOpLessThan:
2462 case glslang::EOpGreaterThan:
2463 case glslang::EOpLessThanEqual:
2464 case glslang::EOpGreaterThanEqual:
2465 case glslang::EOpEqual:
2466 case glslang::EOpNotEqual:
2467 case glslang::EOpVectorEqual:
2468 case glslang::EOpVectorNotEqual:
2469 comparison = true;
2470 break;
2471 default:
2472 break;
2473 }
2474
John Kessenich7c1aa102015-10-15 13:29:11 -06002475 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002476 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002477 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002478 if (builder.isMatrix(left) || builder.isMatrix(right))
2479 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002480
2481 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002482 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002483 builder.promoteScalar(precision, left, right);
2484
John Kessenich32cfd492016-02-02 12:37:46 -07002485 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002486 }
2487
2488 if (! comparison)
2489 return 0;
2490
John Kessenich7c1aa102015-10-15 13:29:11 -06002491 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002492
2493 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2494 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2495
John Kessenich22118352015-12-21 20:54:09 -07002496 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002497 }
2498
2499 switch (op) {
2500 case glslang::EOpLessThan:
2501 if (isFloat)
2502 binOp = spv::OpFOrdLessThan;
2503 else if (isUnsigned)
2504 binOp = spv::OpULessThan;
2505 else
2506 binOp = spv::OpSLessThan;
2507 break;
2508 case glslang::EOpGreaterThan:
2509 if (isFloat)
2510 binOp = spv::OpFOrdGreaterThan;
2511 else if (isUnsigned)
2512 binOp = spv::OpUGreaterThan;
2513 else
2514 binOp = spv::OpSGreaterThan;
2515 break;
2516 case glslang::EOpLessThanEqual:
2517 if (isFloat)
2518 binOp = spv::OpFOrdLessThanEqual;
2519 else if (isUnsigned)
2520 binOp = spv::OpULessThanEqual;
2521 else
2522 binOp = spv::OpSLessThanEqual;
2523 break;
2524 case glslang::EOpGreaterThanEqual:
2525 if (isFloat)
2526 binOp = spv::OpFOrdGreaterThanEqual;
2527 else if (isUnsigned)
2528 binOp = spv::OpUGreaterThanEqual;
2529 else
2530 binOp = spv::OpSGreaterThanEqual;
2531 break;
2532 case glslang::EOpEqual:
2533 case glslang::EOpVectorEqual:
2534 if (isFloat)
2535 binOp = spv::OpFOrdEqual;
2536 else
2537 binOp = spv::OpIEqual;
2538 break;
2539 case glslang::EOpNotEqual:
2540 case glslang::EOpVectorNotEqual:
2541 if (isFloat)
2542 binOp = spv::OpFOrdNotEqual;
2543 else
2544 binOp = spv::OpINotEqual;
2545 break;
2546 default:
2547 break;
2548 }
2549
John Kessenich32cfd492016-02-02 12:37:46 -07002550 if (binOp != spv::OpNop)
2551 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002552
2553 return 0;
2554}
2555
John Kessenich04bb8a02015-12-12 12:28:14 -07002556//
2557// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2558// These can be any of:
2559//
2560// matrix * scalar
2561// scalar * matrix
2562// matrix * matrix linear algebraic
2563// matrix * vector
2564// vector * matrix
2565// matrix * matrix componentwise
2566// matrix op matrix op in {+, -, /}
2567// matrix op scalar op in {+, -, /}
2568// scalar op matrix op in {+, -, /}
2569//
2570spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2571{
2572 bool firstClass = true;
2573
2574 // First, handle first-class matrix operations (* and matrix/scalar)
2575 switch (op) {
2576 case spv::OpFDiv:
2577 if (builder.isMatrix(left) && builder.isScalar(right)) {
2578 // turn matrix / scalar into a multiply...
2579 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2580 op = spv::OpMatrixTimesScalar;
2581 } else
2582 firstClass = false;
2583 break;
2584 case spv::OpMatrixTimesScalar:
2585 if (builder.isMatrix(right))
2586 std::swap(left, right);
2587 assert(builder.isScalar(right));
2588 break;
2589 case spv::OpVectorTimesMatrix:
2590 assert(builder.isVector(left));
2591 assert(builder.isMatrix(right));
2592 break;
2593 case spv::OpMatrixTimesVector:
2594 assert(builder.isMatrix(left));
2595 assert(builder.isVector(right));
2596 break;
2597 case spv::OpMatrixTimesMatrix:
2598 assert(builder.isMatrix(left));
2599 assert(builder.isMatrix(right));
2600 break;
2601 default:
2602 firstClass = false;
2603 break;
2604 }
2605
John Kessenich32cfd492016-02-02 12:37:46 -07002606 if (firstClass)
2607 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002608
2609 // Handle component-wise +, -, *, and / for all combinations of type.
2610 // The result type of all of them is the same type as the (a) matrix operand.
2611 // The algorithm is to:
2612 // - break the matrix(es) into vectors
2613 // - smear any scalar to a vector
2614 // - do vector operations
2615 // - make a matrix out the vector results
2616 switch (op) {
2617 case spv::OpFAdd:
2618 case spv::OpFSub:
2619 case spv::OpFDiv:
2620 case spv::OpFMul:
2621 {
2622 // one time set up...
2623 bool leftMat = builder.isMatrix(left);
2624 bool rightMat = builder.isMatrix(right);
2625 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2626 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2627 spv::Id scalarType = builder.getScalarTypeId(typeId);
2628 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2629 std::vector<spv::Id> results;
2630 spv::Id smearVec = spv::NoResult;
2631 if (builder.isScalar(left))
2632 smearVec = builder.smearScalar(precision, left, vecType);
2633 else if (builder.isScalar(right))
2634 smearVec = builder.smearScalar(precision, right, vecType);
2635
2636 // do each vector op
2637 for (unsigned int c = 0; c < numCols; ++c) {
2638 std::vector<unsigned int> indexes;
2639 indexes.push_back(c);
2640 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2641 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2642 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2643 builder.setPrecision(results.back(), precision);
2644 }
2645
2646 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002647 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002648 }
2649 default:
2650 assert(0);
2651 return spv::NoResult;
2652 }
2653}
2654
Rex Xu04db3f52015-09-16 11:44:02 +08002655spv::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 -06002656{
2657 spv::Op unaryOp = spv::OpNop;
2658 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002659 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002660 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002661
2662 switch (op) {
2663 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002664 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002665 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002666 if (builder.isMatrixType(typeId))
2667 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2668 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002669 unaryOp = spv::OpSNegate;
2670 break;
2671
2672 case glslang::EOpLogicalNot:
2673 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002674 unaryOp = spv::OpLogicalNot;
2675 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002676 case glslang::EOpBitwiseNot:
2677 unaryOp = spv::OpNot;
2678 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002679
John Kessenich140f3df2015-06-26 16:58:36 -06002680 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002681 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002682 break;
2683 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002684 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002685 break;
2686 case glslang::EOpTranspose:
2687 unaryOp = spv::OpTranspose;
2688 break;
2689
2690 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002691 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002692 break;
2693 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002694 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002695 break;
2696 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002697 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002698 break;
2699 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002700 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002701 break;
2702 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002703 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002704 break;
2705 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002706 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002707 break;
2708 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002709 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002710 break;
2711 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002712 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002713 break;
2714
2715 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002716 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002717 break;
2718 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002719 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002720 break;
2721 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002722 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002723 break;
2724 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002725 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002726 break;
2727 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002728 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002729 break;
2730 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002731 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002732 break;
2733
2734 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002735 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002736 break;
2737 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002738 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002739 break;
2740
2741 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002742 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002743 break;
2744 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002745 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002746 break;
2747 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002748 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002749 break;
2750 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002751 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002752 break;
2753 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002754 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002755 break;
2756 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002757 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002758 break;
2759
2760 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002761 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002762 break;
2763 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002764 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002765 break;
2766 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002767 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002768 break;
2769 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002770 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002771 break;
2772 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002773 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002774 break;
2775 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002776 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002777 break;
2778
2779 case glslang::EOpIsNan:
2780 unaryOp = spv::OpIsNan;
2781 break;
2782 case glslang::EOpIsInf:
2783 unaryOp = spv::OpIsInf;
2784 break;
2785
Rex Xucbc426e2015-12-15 16:03:10 +08002786 case glslang::EOpFloatBitsToInt:
2787 case glslang::EOpFloatBitsToUint:
2788 case glslang::EOpIntBitsToFloat:
2789 case glslang::EOpUintBitsToFloat:
2790 unaryOp = spv::OpBitcast;
2791 break;
2792
John Kessenich140f3df2015-06-26 16:58:36 -06002793 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002794 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002795 break;
2796 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002797 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002798 break;
2799 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002800 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002801 break;
2802 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002803 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002804 break;
2805 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002806 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002807 break;
2808 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002809 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002810 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002811 case glslang::EOpPackSnorm4x8:
2812 libCall = spv::GLSLstd450PackSnorm4x8;
2813 break;
2814 case glslang::EOpUnpackSnorm4x8:
2815 libCall = spv::GLSLstd450UnpackSnorm4x8;
2816 break;
2817 case glslang::EOpPackUnorm4x8:
2818 libCall = spv::GLSLstd450PackUnorm4x8;
2819 break;
2820 case glslang::EOpUnpackUnorm4x8:
2821 libCall = spv::GLSLstd450UnpackUnorm4x8;
2822 break;
2823 case glslang::EOpPackDouble2x32:
2824 libCall = spv::GLSLstd450PackDouble2x32;
2825 break;
2826 case glslang::EOpUnpackDouble2x32:
2827 libCall = spv::GLSLstd450UnpackDouble2x32;
2828 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002829
2830 case glslang::EOpDPdx:
2831 unaryOp = spv::OpDPdx;
2832 break;
2833 case glslang::EOpDPdy:
2834 unaryOp = spv::OpDPdy;
2835 break;
2836 case glslang::EOpFwidth:
2837 unaryOp = spv::OpFwidth;
2838 break;
2839 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07002840 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002841 unaryOp = spv::OpDPdxFine;
2842 break;
2843 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07002844 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002845 unaryOp = spv::OpDPdyFine;
2846 break;
2847 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07002848 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002849 unaryOp = spv::OpFwidthFine;
2850 break;
2851 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002852 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002853 unaryOp = spv::OpDPdxCoarse;
2854 break;
2855 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002856 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002857 unaryOp = spv::OpDPdyCoarse;
2858 break;
2859 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002860 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002861 unaryOp = spv::OpFwidthCoarse;
2862 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002863 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07002864 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08002865 libCall = spv::GLSLstd450InterpolateAtCentroid;
2866 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002867 case glslang::EOpAny:
2868 unaryOp = spv::OpAny;
2869 break;
2870 case glslang::EOpAll:
2871 unaryOp = spv::OpAll;
2872 break;
2873
2874 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06002875 if (isFloat)
2876 libCall = spv::GLSLstd450FAbs;
2877 else
2878 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06002879 break;
2880 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06002881 if (isFloat)
2882 libCall = spv::GLSLstd450FSign;
2883 else
2884 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06002885 break;
2886
John Kessenichfc51d282015-08-19 13:34:18 -06002887 case glslang::EOpAtomicCounterIncrement:
2888 case glslang::EOpAtomicCounterDecrement:
2889 case glslang::EOpAtomicCounter:
2890 {
2891 // Handle all of the atomics in one place, in createAtomicOperation()
2892 std::vector<spv::Id> operands;
2893 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08002894 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06002895 }
2896
2897 case glslang::EOpImageLoad:
2898 unaryOp = spv::OpImageRead;
2899 break;
2900
2901 case glslang::EOpBitFieldReverse:
2902 unaryOp = spv::OpBitReverse;
2903 break;
2904 case glslang::EOpBitCount:
2905 unaryOp = spv::OpBitCount;
2906 break;
2907 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002908 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002909 break;
2910 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07002911 if (isUnsigned)
2912 libCall = spv::GLSLstd450FindUMsb;
2913 else
2914 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06002915 break;
2916
John Kessenich140f3df2015-06-26 16:58:36 -06002917 default:
2918 return 0;
2919 }
2920
2921 spv::Id id;
2922 if (libCall >= 0) {
2923 std::vector<spv::Id> args;
2924 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07002925 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06002926 } else
2927 id = builder.createUnaryOp(unaryOp, typeId, operand);
2928
John Kessenich32cfd492016-02-02 12:37:46 -07002929 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002930}
2931
John Kessenich7a53f762016-01-20 11:19:27 -07002932// Create a unary operation on a matrix
2933spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
2934{
2935 // Handle unary operations vector by vector.
2936 // The result type is the same type as the original type.
2937 // The algorithm is to:
2938 // - break the matrix into vectors
2939 // - apply the operation to each vector
2940 // - make a matrix out the vector results
2941
2942 // get the types sorted out
2943 int numCols = builder.getNumColumns(operand);
2944 int numRows = builder.getNumRows(operand);
2945 spv::Id scalarType = builder.getScalarTypeId(typeId);
2946 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2947 std::vector<spv::Id> results;
2948
2949 // do each vector op
2950 for (int c = 0; c < numCols; ++c) {
2951 std::vector<unsigned int> indexes;
2952 indexes.push_back(c);
2953 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
2954 results.push_back(builder.createUnaryOp(op, vecType, vec));
2955 builder.setPrecision(results.back(), precision);
2956 }
2957
2958 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002959 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07002960}
2961
John Kessenich140f3df2015-06-26 16:58:36 -06002962spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
2963{
2964 spv::Op convOp = spv::OpNop;
2965 spv::Id zero = 0;
2966 spv::Id one = 0;
2967
2968 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
2969
2970 switch (op) {
2971 case glslang::EOpConvIntToBool:
2972 case glslang::EOpConvUintToBool:
2973 zero = builder.makeUintConstant(0);
2974 zero = makeSmearedConstant(zero, vectorSize);
2975 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
2976
2977 case glslang::EOpConvFloatToBool:
2978 zero = builder.makeFloatConstant(0.0F);
2979 zero = makeSmearedConstant(zero, vectorSize);
2980 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2981
2982 case glslang::EOpConvDoubleToBool:
2983 zero = builder.makeDoubleConstant(0.0);
2984 zero = makeSmearedConstant(zero, vectorSize);
2985 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
2986
2987 case glslang::EOpConvBoolToFloat:
2988 convOp = spv::OpSelect;
2989 zero = builder.makeFloatConstant(0.0);
2990 one = builder.makeFloatConstant(1.0);
2991 break;
2992 case glslang::EOpConvBoolToDouble:
2993 convOp = spv::OpSelect;
2994 zero = builder.makeDoubleConstant(0.0);
2995 one = builder.makeDoubleConstant(1.0);
2996 break;
2997 case glslang::EOpConvBoolToInt:
2998 zero = builder.makeIntConstant(0);
2999 one = builder.makeIntConstant(1);
3000 convOp = spv::OpSelect;
3001 break;
3002 case glslang::EOpConvBoolToUint:
3003 zero = builder.makeUintConstant(0);
3004 one = builder.makeUintConstant(1);
3005 convOp = spv::OpSelect;
3006 break;
3007
3008 case glslang::EOpConvIntToFloat:
3009 case glslang::EOpConvIntToDouble:
3010 convOp = spv::OpConvertSToF;
3011 break;
3012
3013 case glslang::EOpConvUintToFloat:
3014 case glslang::EOpConvUintToDouble:
3015 convOp = spv::OpConvertUToF;
3016 break;
3017
3018 case glslang::EOpConvDoubleToFloat:
3019 case glslang::EOpConvFloatToDouble:
3020 convOp = spv::OpFConvert;
3021 break;
3022
3023 case glslang::EOpConvFloatToInt:
3024 case glslang::EOpConvDoubleToInt:
3025 convOp = spv::OpConvertFToS;
3026 break;
3027
3028 case glslang::EOpConvUintToInt:
3029 case glslang::EOpConvIntToUint:
3030 convOp = spv::OpBitcast;
3031 break;
3032
3033 case glslang::EOpConvFloatToUint:
3034 case glslang::EOpConvDoubleToUint:
3035 convOp = spv::OpConvertFToU;
3036 break;
3037 default:
3038 break;
3039 }
3040
3041 spv::Id result = 0;
3042 if (convOp == spv::OpNop)
3043 return result;
3044
3045 if (convOp == spv::OpSelect) {
3046 zero = makeSmearedConstant(zero, vectorSize);
3047 one = makeSmearedConstant(one, vectorSize);
3048 result = builder.createTriOp(convOp, destType, operand, one, zero);
3049 } else
3050 result = builder.createUnaryOp(convOp, destType, operand);
3051
John Kessenich32cfd492016-02-02 12:37:46 -07003052 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003053}
3054
3055spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3056{
3057 if (vectorSize == 0)
3058 return constant;
3059
3060 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3061 std::vector<spv::Id> components;
3062 for (int c = 0; c < vectorSize; ++c)
3063 components.push_back(constant);
3064 return builder.makeCompositeConstant(vectorTypeId, components);
3065}
3066
John Kessenich426394d2015-07-23 10:22:48 -06003067// For glslang ops that map to SPV atomic opCodes
Rex Xu04db3f52015-09-16 11:44:02 +08003068spv::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 -06003069{
3070 spv::Op opCode = spv::OpNop;
3071
3072 switch (op) {
3073 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003074 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003075 opCode = spv::OpAtomicIAdd;
3076 break;
3077 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003078 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003079 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003080 break;
3081 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003082 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003083 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003084 break;
3085 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003086 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003087 opCode = spv::OpAtomicAnd;
3088 break;
3089 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003090 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003091 opCode = spv::OpAtomicOr;
3092 break;
3093 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003094 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003095 opCode = spv::OpAtomicXor;
3096 break;
3097 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003098 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003099 opCode = spv::OpAtomicExchange;
3100 break;
3101 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003102 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003103 opCode = spv::OpAtomicCompareExchange;
3104 break;
3105 case glslang::EOpAtomicCounterIncrement:
3106 opCode = spv::OpAtomicIIncrement;
3107 break;
3108 case glslang::EOpAtomicCounterDecrement:
3109 opCode = spv::OpAtomicIDecrement;
3110 break;
3111 case glslang::EOpAtomicCounter:
3112 opCode = spv::OpAtomicLoad;
3113 break;
3114 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003115 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003116 break;
3117 }
3118
3119 // Sort out the operands
3120 // - mapping from glslang -> SPV
3121 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003122 // - compare-exchange swaps the value and comparator
3123 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003124 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3125 auto opIt = operands.begin(); // walk the glslang operands
3126 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003127 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3128 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3129 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003130 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3131 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003132 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003133 spvAtomicOperands.push_back(*(opIt + 1));
3134 spvAtomicOperands.push_back(*opIt);
3135 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003136 }
John Kessenich426394d2015-07-23 10:22:48 -06003137
John Kessenich3e60a6f2015-09-14 22:45:16 -06003138 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003139 for (; opIt != operands.end(); ++opIt)
3140 spvAtomicOperands.push_back(*opIt);
3141
3142 return builder.createOp(opCode, typeId, spvAtomicOperands);
3143}
3144
John Kessenich5e4b1242015-08-06 22:53:06 -06003145spv::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 -06003146{
John Kessenich5e4b1242015-08-06 22:53:06 -06003147 bool isUnsigned = typeProxy == glslang::EbtUint;
3148 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3149
John Kessenich140f3df2015-06-26 16:58:36 -06003150 spv::Op opCode = spv::OpNop;
3151 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003152 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003153 spv::Id typeId0 = 0;
3154 if (consumedOperands > 0)
3155 typeId0 = builder.getTypeId(operands[0]);
3156 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003157
3158 switch (op) {
3159 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003160 if (isFloat)
3161 libCall = spv::GLSLstd450FMin;
3162 else if (isUnsigned)
3163 libCall = spv::GLSLstd450UMin;
3164 else
3165 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003166 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003167 break;
3168 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003169 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003170 break;
3171 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003172 if (isFloat)
3173 libCall = spv::GLSLstd450FMax;
3174 else if (isUnsigned)
3175 libCall = spv::GLSLstd450UMax;
3176 else
3177 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003178 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003179 break;
3180 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003181 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003182 break;
3183 case glslang::EOpDot:
3184 opCode = spv::OpDot;
3185 break;
3186 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003187 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003188 break;
3189
3190 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003191 if (isFloat)
3192 libCall = spv::GLSLstd450FClamp;
3193 else if (isUnsigned)
3194 libCall = spv::GLSLstd450UClamp;
3195 else
3196 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003197 builder.promoteScalar(precision, operands.front(), operands[1]);
3198 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003199 break;
3200 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003201 if (isFloat)
3202 libCall = spv::GLSLstd450FMix;
3203 else
3204 libCall = spv::GLSLstd450IMix;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003205 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003206 break;
3207 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003208 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003209 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003210 break;
3211 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003212 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003213 builder.promoteScalar(precision, operands[0], operands[2]);
3214 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003215 break;
3216
3217 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003218 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003219 break;
3220 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003221 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003222 break;
3223 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003224 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003225 break;
3226 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003227 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003228 break;
3229 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003230 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003231 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003232 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003233 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003234 libCall = spv::GLSLstd450InterpolateAtSample;
3235 break;
3236 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003237 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003238 libCall = spv::GLSLstd450InterpolateAtOffset;
3239 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003240 case glslang::EOpAddCarry:
3241 opCode = spv::OpIAddCarry;
3242 typeId = builder.makeStructResultType(typeId0, typeId0);
3243 consumedOperands = 2;
3244 break;
3245 case glslang::EOpSubBorrow:
3246 opCode = spv::OpISubBorrow;
3247 typeId = builder.makeStructResultType(typeId0, typeId0);
3248 consumedOperands = 2;
3249 break;
3250 case glslang::EOpUMulExtended:
3251 opCode = spv::OpUMulExtended;
3252 typeId = builder.makeStructResultType(typeId0, typeId0);
3253 consumedOperands = 2;
3254 break;
3255 case glslang::EOpIMulExtended:
3256 opCode = spv::OpSMulExtended;
3257 typeId = builder.makeStructResultType(typeId0, typeId0);
3258 consumedOperands = 2;
3259 break;
3260 case glslang::EOpBitfieldExtract:
3261 if (isUnsigned)
3262 opCode = spv::OpBitFieldUExtract;
3263 else
3264 opCode = spv::OpBitFieldSExtract;
3265 break;
3266 case glslang::EOpBitfieldInsert:
3267 opCode = spv::OpBitFieldInsert;
3268 break;
3269
3270 case glslang::EOpFma:
3271 libCall = spv::GLSLstd450Fma;
3272 break;
3273 case glslang::EOpFrexp:
3274 libCall = spv::GLSLstd450FrexpStruct;
3275 if (builder.getNumComponents(operands[0]) == 1)
3276 frexpIntType = builder.makeIntegerType(32, true);
3277 else
3278 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3279 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3280 consumedOperands = 1;
3281 break;
3282 case glslang::EOpLdexp:
3283 libCall = spv::GLSLstd450Ldexp;
3284 break;
3285
John Kessenich140f3df2015-06-26 16:58:36 -06003286 default:
3287 return 0;
3288 }
3289
3290 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003291 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003292 // Use an extended instruction from the standard library.
3293 // Construct the call arguments, without modifying the original operands vector.
3294 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3295 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003296 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003297 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003298 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003299 case 0:
3300 // should all be handled by visitAggregate and createNoArgOperation
3301 assert(0);
3302 return 0;
3303 case 1:
3304 // should all be handled by createUnaryOperation
3305 assert(0);
3306 return 0;
3307 case 2:
3308 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3309 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003310 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003311 // anything 3 or over doesn't have l-value operands, so all should be consumed
3312 assert(consumedOperands == operands.size());
3313 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003314 break;
3315 }
3316 }
3317
John Kessenich55e7d112015-11-15 21:33:39 -07003318 // Decode the return types that were structures
3319 switch (op) {
3320 case glslang::EOpAddCarry:
3321 case glslang::EOpSubBorrow:
3322 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3323 id = builder.createCompositeExtract(id, typeId0, 0);
3324 break;
3325 case glslang::EOpUMulExtended:
3326 case glslang::EOpIMulExtended:
3327 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3328 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3329 break;
3330 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003331 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003332 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3333 id = builder.createCompositeExtract(id, typeId0, 0);
3334 break;
3335 default:
3336 break;
3337 }
3338
John Kessenich32cfd492016-02-02 12:37:46 -07003339 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003340}
3341
3342// Intrinsics with no arguments, no return value, and no precision.
3343spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3344{
3345 // TODO: get the barrier operands correct
3346
3347 switch (op) {
3348 case glslang::EOpEmitVertex:
3349 builder.createNoResultOp(spv::OpEmitVertex);
3350 return 0;
3351 case glslang::EOpEndPrimitive:
3352 builder.createNoResultOp(spv::OpEndPrimitive);
3353 return 0;
3354 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003355 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3356 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003357 return 0;
3358 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003359 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003360 return 0;
3361 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003362 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003363 return 0;
3364 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003365 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003366 return 0;
3367 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003368 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003369 return 0;
3370 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003371 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003372 return 0;
3373 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003374 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003375 return 0;
3376 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003377 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003378 return 0;
3379 }
3380}
3381
3382spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3383{
John Kessenich2f273362015-07-18 22:34:27 -06003384 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003385 spv::Id id;
3386 if (symbolValues.end() != iter) {
3387 id = iter->second;
3388 return id;
3389 }
3390
3391 // it was not found, create it
3392 id = createSpvVariable(symbol);
3393 symbolValues[symbol->getId()] = id;
3394
3395 if (! symbol->getType().isStruct()) {
3396 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003397 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich140f3df2015-06-26 16:58:36 -06003398 if (symbol->getQualifier().hasLocation())
3399 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3400 if (symbol->getQualifier().hasIndex())
3401 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3402 if (symbol->getQualifier().hasComponent())
3403 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3404 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003405 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003406 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003407 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003408 if (symbol->getQualifier().hasXfbBuffer())
3409 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3410 if (symbol->getQualifier().hasXfbOffset())
3411 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3412 }
3413 }
3414
John Kesseniche0b6cad2015-12-24 10:30:13 -07003415 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003416 if (symbol->getQualifier().hasStream()) {
3417 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003418 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003419 }
John Kessenich140f3df2015-06-26 16:58:36 -06003420 if (symbol->getQualifier().hasSet())
3421 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
3422 if (symbol->getQualifier().hasBinding())
3423 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
3424 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003425 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003426 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003427 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003428 if (symbol->getQualifier().hasXfbBuffer())
3429 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3430 }
3431
3432 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003433 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003434 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003435 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003436
John Kessenich140f3df2015-06-26 16:58:36 -06003437 return id;
3438}
3439
John Kessenich55e7d112015-11-15 21:33:39 -07003440// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003441void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3442{
3443 if (dec != spv::BadValue)
3444 builder.addDecoration(id, dec);
3445}
3446
John Kessenich55e7d112015-11-15 21:33:39 -07003447// If 'dec' is valid, add a one-operand decoration to an object
3448void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3449{
3450 if (dec != spv::BadValue)
3451 builder.addDecoration(id, dec, value);
3452}
3453
3454// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003455void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3456{
3457 if (dec != spv::BadValue)
3458 builder.addMemberDecoration(id, (unsigned)member, dec);
3459}
3460
John Kessenich92187592016-02-01 13:45:25 -07003461// If 'dec' is valid, add a one-operand decoration to a struct member
3462void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3463{
3464 if (dec != spv::BadValue)
3465 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3466}
3467
John Kessenich55e7d112015-11-15 21:33:39 -07003468// Make a full tree of instructions to build a SPIR-V specialization constant,
3469// or regularly constant if possible.
3470//
3471// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3472//
3473// Recursively walk the nodes. The nodes form a tree whose leaves are
3474// regular constants, which themselves are trees that createSpvConstant()
3475// recursively walks. So, this function walks the "top" of the tree:
3476// - emit specialization constant-building instructions for specConstant
3477// - when running into a non-spec-constant, switch to createSpvConstant()
3478spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3479{
3480 assert(node.getQualifier().storage == glslang::EvqConst);
3481
3482 // hand off to the non-spec-constant path
3483 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3484 int nextConst = 0;
3485 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(), nextConst, false);
3486}
3487
John Kessenich140f3df2015-06-26 16:58:36 -06003488// Use 'consts' as the flattened glslang source of scalar constants to recursively
3489// build the aggregate SPIR-V constant.
3490//
3491// If there are not enough elements present in 'consts', 0 will be substituted;
3492// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3493//
John Kessenich55e7d112015-11-15 21:33:39 -07003494spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003495{
3496 // vector of constants for SPIR-V
3497 std::vector<spv::Id> spvConsts;
3498
3499 // Type is used for struct and array constants
3500 spv::Id typeId = convertGlslangToSpvType(glslangType);
3501
3502 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003503 glslang::TType elementType(glslangType, 0);
3504 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003505 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003506 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003507 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003508 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003509 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003510 } else if (glslangType.getStruct()) {
3511 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3512 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003513 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003514 } else if (glslangType.isVector()) {
3515 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3516 bool zero = nextConst >= consts.size();
3517 switch (glslangType.getBasicType()) {
3518 case glslang::EbtInt:
3519 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3520 break;
3521 case glslang::EbtUint:
3522 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3523 break;
3524 case glslang::EbtFloat:
3525 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3526 break;
3527 case glslang::EbtDouble:
3528 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3529 break;
3530 case glslang::EbtBool:
3531 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3532 break;
3533 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003534 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003535 break;
3536 }
3537 ++nextConst;
3538 }
3539 } else {
3540 // we have a non-aggregate (scalar) constant
3541 bool zero = nextConst >= consts.size();
3542 spv::Id scalar = 0;
3543 switch (glslangType.getBasicType()) {
3544 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003545 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003546 break;
3547 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003548 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003549 break;
3550 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003551 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003552 break;
3553 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003554 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003555 break;
3556 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003557 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003558 break;
3559 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003560 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003561 break;
3562 }
3563 ++nextConst;
3564 return scalar;
3565 }
3566
3567 return builder.makeCompositeConstant(typeId, spvConsts);
3568}
3569
John Kessenich7c1aa102015-10-15 13:29:11 -06003570// Return true if the node is a constant or symbol whose reading has no
3571// non-trivial observable cost or effect.
3572bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3573{
3574 // don't know what this is
3575 if (node == nullptr)
3576 return false;
3577
3578 // a constant is safe
3579 if (node->getAsConstantUnion() != nullptr)
3580 return true;
3581
3582 // not a symbol means non-trivial
3583 if (node->getAsSymbolNode() == nullptr)
3584 return false;
3585
3586 // a symbol, depends on what's being read
3587 switch (node->getType().getQualifier().storage) {
3588 case glslang::EvqTemporary:
3589 case glslang::EvqGlobal:
3590 case glslang::EvqIn:
3591 case glslang::EvqInOut:
3592 case glslang::EvqConst:
3593 case glslang::EvqConstReadOnly:
3594 case glslang::EvqUniform:
3595 return true;
3596 default:
3597 return false;
3598 }
3599}
3600
3601// A node is trivial if it is a single operation with no side effects.
3602// Error on the side of saying non-trivial.
3603// Return true if trivial.
3604bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3605{
3606 if (node == nullptr)
3607 return false;
3608
3609 // symbols and constants are trivial
3610 if (isTrivialLeaf(node))
3611 return true;
3612
3613 // otherwise, it needs to be a simple operation or one or two leaf nodes
3614
3615 // not a simple operation
3616 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3617 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3618 if (binaryNode == nullptr && unaryNode == nullptr)
3619 return false;
3620
3621 // not on leaf nodes
3622 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3623 return false;
3624
3625 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3626 return false;
3627 }
3628
3629 switch (node->getAsOperator()->getOp()) {
3630 case glslang::EOpLogicalNot:
3631 case glslang::EOpConvIntToBool:
3632 case glslang::EOpConvUintToBool:
3633 case glslang::EOpConvFloatToBool:
3634 case glslang::EOpConvDoubleToBool:
3635 case glslang::EOpEqual:
3636 case glslang::EOpNotEqual:
3637 case glslang::EOpLessThan:
3638 case glslang::EOpGreaterThan:
3639 case glslang::EOpLessThanEqual:
3640 case glslang::EOpGreaterThanEqual:
3641 case glslang::EOpIndexDirect:
3642 case glslang::EOpIndexDirectStruct:
3643 case glslang::EOpLogicalXor:
3644 case glslang::EOpAny:
3645 case glslang::EOpAll:
3646 return true;
3647 default:
3648 return false;
3649 }
3650}
3651
3652// Emit short-circuiting code, where 'right' is never evaluated unless
3653// the left side is true (for &&) or false (for ||).
3654spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3655{
3656 spv::Id boolTypeId = builder.makeBoolType();
3657
3658 // emit left operand
3659 builder.clearAccessChain();
3660 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003661 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003662
3663 // Operands to accumulate OpPhi operands
3664 std::vector<spv::Id> phiOperands;
3665 // accumulate left operand's phi information
3666 phiOperands.push_back(leftId);
3667 phiOperands.push_back(builder.getBuildPoint()->getId());
3668
3669 // Make the two kinds of operation symmetric with a "!"
3670 // || => emit "if (! left) result = right"
3671 // && => emit "if ( left) result = right"
3672 //
3673 // TODO: this runtime "not" for || could be avoided by adding functionality
3674 // to 'builder' to have an "else" without an "then"
3675 if (op == glslang::EOpLogicalOr)
3676 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3677
3678 // make an "if" based on the left value
3679 spv::Builder::If ifBuilder(leftId, builder);
3680
3681 // emit right operand as the "then" part of the "if"
3682 builder.clearAccessChain();
3683 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003684 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003685
3686 // accumulate left operand's phi information
3687 phiOperands.push_back(rightId);
3688 phiOperands.push_back(builder.getBuildPoint()->getId());
3689
3690 // finish the "if"
3691 ifBuilder.makeEndIf();
3692
3693 // phi together the two results
3694 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3695}
3696
John Kessenich140f3df2015-06-26 16:58:36 -06003697}; // end anonymous namespace
3698
3699namespace glslang {
3700
John Kessenich68d78fd2015-07-12 19:28:10 -06003701void GetSpirvVersion(std::string& version)
3702{
John Kessenich9e55f632015-07-15 10:03:39 -06003703 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003704 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003705 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003706 version = buf;
3707}
3708
John Kessenich140f3df2015-06-26 16:58:36 -06003709// Write SPIR-V out to a binary file
3710void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3711{
3712 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003713 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003714 for (int i = 0; i < (int)spirv.size(); ++i) {
3715 unsigned int word = spirv[i];
3716 out.write((const char*)&word, 4);
3717 }
3718 out.close();
3719}
3720
3721//
3722// Set up the glslang traversal
3723//
3724void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3725{
3726 TIntermNode* root = intermediate.getTreeRoot();
3727
3728 if (root == 0)
3729 return;
3730
3731 glslang::GetThreadPoolAllocator().push();
3732
3733 TGlslangToSpvTraverser it(&intermediate);
3734
3735 root->traverse(&it);
3736
3737 it.dumpSpv(spirv);
3738
3739 glslang::GetThreadPoolAllocator().pop();
3740}
3741
3742}; // end namespace glslang