blob: cebc7478e29a253b14909f83a6eba677b696bfd6 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
55#include <string>
56#include <map>
57#include <list>
58#include <vector>
59#include <stack>
60#include <fstream>
61
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
69//
70// The main holder of information for translating glslang to SPIR-V.
71//
72// Derives from the AST walking base class.
73//
74class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
75public:
76 TGlslangToSpvTraverser(const glslang::TIntermediate*);
77 virtual ~TGlslangToSpvTraverser();
78
79 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
80 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
81 void visitConstantUnion(glslang::TIntermConstantUnion*);
82 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
83 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
84 void visitSymbol(glslang::TIntermSymbol* symbol);
85 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
86 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
87 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
88
John Kessenich7ba63412015-12-20 17:37:07 -070089 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060090
91protected:
John Kessenich5e801132016-02-15 11:09:46 -070092 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -070093 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -070094 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -060095 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
96 spv::Id getSampledType(const glslang::TSampler&);
97 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070098 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -070099 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700100 spv::Id accessChainLoad(const glslang::TType& type);
John Kessenichf85e8062015-12-19 13:57:10 -0700101 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700102 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
103 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
104 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 -0600105
106 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
107 void makeFunctions(const glslang::TIntermSequence&);
108 void makeGlobalInitializers(const glslang::TIntermSequence&);
109 void visitFunctions(const glslang::TIntermSequence&);
110 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800111 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600112 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
113 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
115
116 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 -0700117 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800118 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 -0700119 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600120 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
121 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800122 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 -0600123 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 -0600124 spv::Id createNoArgOperation(glslang::TOperator op);
125 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
126 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700127 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600128 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700129 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700130 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
131 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600132 bool isTrivialLeaf(const glslang::TIntermTyped* node);
133 bool isTrivial(const glslang::TIntermTyped* node);
134 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600135
136 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700137 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600138 int sequenceDepth;
139
140 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
141 spv::Builder builder;
142 bool inMain;
143 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700144 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 -0700145 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600146 const glslang::TIntermediate* glslangIntermediate;
147 spv::Id stdBuiltins;
148
John Kessenich2f273362015-07-18 22:34:27 -0600149 std::unordered_map<int, spv::Id> symbolValues;
150 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
151 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700152 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600153 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 -0600154 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600155};
156
157//
158// Helper functions for translating glslang representations to SPIR-V enumerants.
159//
160
161// Translate glslang profile to SPIR-V source language.
162spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
163{
164 switch (profile) {
165 case ENoProfile:
166 case ECoreProfile:
167 case ECompatibilityProfile:
168 return spv::SourceLanguageGLSL;
169 case EEsProfile:
170 return spv::SourceLanguageESSL;
171 default:
172 return spv::SourceLanguageUnknown;
173 }
174}
175
176// Translate glslang language (stage) to SPIR-V execution model.
177spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
178{
179 switch (stage) {
180 case EShLangVertex: return spv::ExecutionModelVertex;
181 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
182 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
183 case EShLangGeometry: return spv::ExecutionModelGeometry;
184 case EShLangFragment: return spv::ExecutionModelFragment;
185 case EShLangCompute: return spv::ExecutionModelGLCompute;
186 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700187 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600188 return spv::ExecutionModelFragment;
189 }
190}
191
192// Translate glslang type to SPIR-V storage class.
193spv::StorageClass TranslateStorageClass(const glslang::TType& type)
194{
195 if (type.getQualifier().isPipeInput())
196 return spv::StorageClassInput;
197 else if (type.getQualifier().isPipeOutput())
198 return spv::StorageClassOutput;
199 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700200 if (type.getQualifier().layoutPushConstant)
201 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 if (type.getBasicType() == glslang::EbtBlock)
203 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800204 else if (type.getBasicType() == glslang::EbtAtomicUint)
205 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600206 else
207 return spv::StorageClassUniformConstant;
208 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
209 } else {
210 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700211 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
212 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
214 case glslang::EvqTemporary: return spv::StorageClassFunction;
215 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700216 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600217 return spv::StorageClassFunction;
218 }
219 }
220}
221
222// Translate glslang sampler type to SPIR-V dimensionality.
223spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
224{
225 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700226 case glslang::Esd1D: return spv::Dim1D;
227 case glslang::Esd2D: return spv::Dim2D;
228 case glslang::Esd3D: return spv::Dim3D;
229 case glslang::EsdCube: return spv::DimCube;
230 case glslang::EsdRect: return spv::DimRect;
231 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700232 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700234 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600235 return spv::Dim2D;
236 }
237}
238
239// Translate glslang type to SPIR-V precision decorations.
240spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
241{
242 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700243 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600244 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600245 default:
246 return spv::NoPrecision;
247 }
248}
249
250// Translate glslang type to SPIR-V block decorations.
251spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
252{
253 if (type.getBasicType() == glslang::EbtBlock) {
254 switch (type.getQualifier().storage) {
255 case glslang::EvqUniform: return spv::DecorationBlock;
256 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
257 case glslang::EvqVaryingIn: return spv::DecorationBlock;
258 case glslang::EvqVaryingOut: return spv::DecorationBlock;
259 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700260 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600261 break;
262 }
263 }
264
265 return (spv::Decoration)spv::BadValue;
266}
267
Rex Xu1da878f2016-02-21 20:59:01 +0800268// Translate glslang type to SPIR-V memory decorations.
269void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
270{
271 if (qualifier.coherent)
272 memory.push_back(spv::DecorationCoherent);
273 if (qualifier.volatil)
274 memory.push_back(spv::DecorationVolatile);
275 if (qualifier.restrict)
276 memory.push_back(spv::DecorationRestrict);
277 if (qualifier.readonly)
278 memory.push_back(spv::DecorationNonWritable);
279 if (qualifier.writeonly)
280 memory.push_back(spv::DecorationNonReadable);
281}
282
John Kessenich140f3df2015-06-26 16:58:36 -0600283// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700284spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600285{
286 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700287 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600288 case glslang::ElmRowMajor:
289 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700290 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600291 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700292 default:
293 // opaque layouts don't need a majorness
294 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600295 }
296 } else {
297 switch (type.getBasicType()) {
298 default:
299 return (spv::Decoration)spv::BadValue;
300 break;
301 case glslang::EbtBlock:
302 switch (type.getQualifier().storage) {
303 case glslang::EvqUniform:
304 case glslang::EvqBuffer:
305 switch (type.getQualifier().layoutPacking) {
306 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600307 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
308 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600309 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600310 }
311 case glslang::EvqVaryingIn:
312 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700313 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600314 return (spv::Decoration)spv::BadValue;
315 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700316 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600317 return (spv::Decoration)spv::BadValue;
318 }
319 }
320 }
321}
322
323// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700324// Returns spv::Decoration(spv::BadValue) when no decoration
325// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700326spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600327{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700328 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700329 // Smooth decoration doesn't exist in SPIR-V 1.0
330 return (spv::Decoration)spv::BadValue;
331 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700332 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700333 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700334 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600335 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700336 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600337 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700338 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600339 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700340 else if (qualifier.sample) {
341 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600342 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700343 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600344 return (spv::Decoration)spv::BadValue;
345}
346
John Kessenich92187592016-02-01 13:45:25 -0700347// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700348spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600349{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700350 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600351 return spv::DecorationInvariant;
352 else
353 return (spv::Decoration)spv::BadValue;
354}
355
356// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700357spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600358{
359 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700360 case glslang::EbvPointSize:
361 switch (glslangIntermediate->getStage()) {
362 case EShLangGeometry:
363 builder.addCapability(spv::CapabilityGeometryPointSize);
364 break;
365 case EShLangTessControl:
366 case EShLangTessEvaluation:
367 builder.addCapability(spv::CapabilityTessellationPointSize);
368 break;
369 }
370 return spv::BuiltInPointSize;
371
372 case glslang::EbvClipDistance:
373 builder.addCapability(spv::CapabilityClipDistance);
374 return spv::BuiltInClipDistance;
375
376 case glslang::EbvCullDistance:
377 builder.addCapability(spv::CapabilityCullDistance);
378 return spv::BuiltInCullDistance;
379
380 case glslang::EbvViewportIndex:
381 // TODO: builder.addCapability(spv::CapabilityMultiViewport);
382 return spv::BuiltInViewportIndex;
383
John Kessenich5e801132016-02-15 11:09:46 -0700384 case glslang::EbvSampleId:
385 builder.addCapability(spv::CapabilitySampleRateShading);
386 return spv::BuiltInSampleId;
387
388 case glslang::EbvSamplePosition:
389 builder.addCapability(spv::CapabilitySampleRateShading);
390 return spv::BuiltInSamplePosition;
391
392 case glslang::EbvSampleMask:
393 builder.addCapability(spv::CapabilitySampleRateShading);
394 return spv::BuiltInSampleMask;
395
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600397 case glslang::EbvVertexId: return spv::BuiltInVertexId;
398 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700399 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
400 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600401 case glslang::EbvBaseVertex:
402 case glslang::EbvBaseInstance:
403 case glslang::EbvDrawId:
404 // TODO: Add SPIR-V builtin ID.
405 spv::MissingFunctionality("Draw parameters");
406 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
408 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
409 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600410 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
411 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
412 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
413 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
414 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
415 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
416 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600417 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
418 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
419 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
420 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
421 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
422 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
423 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
424 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
425 default: return (spv::BuiltIn)spv::BadValue;
426 }
427}
428
Rex Xufc618912015-09-09 16:42:49 +0800429// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700430spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800431{
432 assert(type.getBasicType() == glslang::EbtSampler);
433
John Kessenich5d0fa972016-02-15 11:57:00 -0700434 // Check for capabilities
435 switch (type.getQualifier().layoutFormat) {
436 case glslang::ElfRg32f:
437 case glslang::ElfRg16f:
438 case glslang::ElfR11fG11fB10f:
439 case glslang::ElfR16f:
440 case glslang::ElfRgba16:
441 case glslang::ElfRgb10A2:
442 case glslang::ElfRg16:
443 case glslang::ElfRg8:
444 case glslang::ElfR16:
445 case glslang::ElfR8:
446 case glslang::ElfRgba16Snorm:
447 case glslang::ElfRg16Snorm:
448 case glslang::ElfRg8Snorm:
449 case glslang::ElfR16Snorm:
450 case glslang::ElfR8Snorm:
451
452 case glslang::ElfRg32i:
453 case glslang::ElfRg16i:
454 case glslang::ElfRg8i:
455 case glslang::ElfR16i:
456 case glslang::ElfR8i:
457
458 case glslang::ElfRgb10a2ui:
459 case glslang::ElfRg32ui:
460 case glslang::ElfRg16ui:
461 case glslang::ElfRg8ui:
462 case glslang::ElfR16ui:
463 case glslang::ElfR8ui:
464 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
465 break;
466
467 default:
468 break;
469 }
470
471 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800472 switch (type.getQualifier().layoutFormat) {
473 case glslang::ElfNone: return spv::ImageFormatUnknown;
474 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
475 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
476 case glslang::ElfR32f: return spv::ImageFormatR32f;
477 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
478 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
479 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
480 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
481 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
482 case glslang::ElfR16f: return spv::ImageFormatR16f;
483 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
484 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
485 case glslang::ElfRg16: return spv::ImageFormatRg16;
486 case glslang::ElfRg8: return spv::ImageFormatRg8;
487 case glslang::ElfR16: return spv::ImageFormatR16;
488 case glslang::ElfR8: return spv::ImageFormatR8;
489 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
490 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
491 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
492 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
493 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
494 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
495 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
496 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
497 case glslang::ElfR32i: return spv::ImageFormatR32i;
498 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
499 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
500 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
501 case glslang::ElfR16i: return spv::ImageFormatR16i;
502 case glslang::ElfR8i: return spv::ImageFormatR8i;
503 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
504 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
505 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
506 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
507 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
508 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
509 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
510 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
511 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
512 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
513 default: return (spv::ImageFormat)spv::BadValue;
514 }
515}
516
John Kessenich6c292d32016-02-15 20:58:50 -0700517// Return whether or not the given type is something that should be tied to a
518// descriptor set.
519bool IsDescriptorResource(const glslang::TType& type)
520{
521 // uniform and buffer blocks are included
522 if (type.getBasicType() == glslang::EbtBlock)
523 return type.getQualifier().isUniformOrBuffer();
524
525 // non block...
526 // basically samplerXXX/subpass/sampler/texture are all included
527 // if they are the global-scope-class, not the function parameter
528 // (or local, if they ever exist) class.
529 if (type.getBasicType() == glslang::EbtSampler)
530 return type.getQualifier().isUniformOrBuffer();
531
532 // None of the above.
533 return false;
534}
535
John Kesseniche0b6cad2015-12-24 10:30:13 -0700536void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
537{
538 if (child.layoutMatrix == glslang::ElmNone)
539 child.layoutMatrix = parent.layoutMatrix;
540
541 if (parent.invariant)
542 child.invariant = true;
543 if (parent.nopersp)
544 child.nopersp = true;
545 if (parent.flat)
546 child.flat = true;
547 if (parent.centroid)
548 child.centroid = true;
549 if (parent.patch)
550 child.patch = true;
551 if (parent.sample)
552 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800553 if (parent.coherent)
554 child.coherent = true;
555 if (parent.volatil)
556 child.volatil = true;
557 if (parent.restrict)
558 child.restrict = true;
559 if (parent.readonly)
560 child.readonly = true;
561 if (parent.writeonly)
562 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700563}
564
565bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
566{
John Kessenich7b9fa252016-01-21 18:56:57 -0700567 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700568 // - struct members can inherit from a struct declaration
569 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
570 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700571 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700572}
573
John Kessenich140f3df2015-06-26 16:58:36 -0600574//
575// Implement the TGlslangToSpvTraverser class.
576//
577
578TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
579 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700580 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600581 inMain(false), mainTerminated(false), linkageOnly(false),
582 glslangIntermediate(glslangIntermediate)
583{
584 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
585
586 builder.clearAccessChain();
587 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
588 stdBuiltins = builder.import("GLSL.std.450");
589 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
590 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700591 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600592
593 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600594 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
595 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600596 builder.addSourceExtension(it->c_str());
597
598 // Add the top-level modes for this shader.
599
John Kessenich92187592016-02-01 13:45:25 -0700600 if (glslangIntermediate->getXfbMode()) {
601 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600602 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700603 }
John Kessenich140f3df2015-06-26 16:58:36 -0600604
605 unsigned int mode;
606 switch (glslangIntermediate->getStage()) {
607 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600608 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600609 break;
610
611 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600612 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600613 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
614 break;
615
616 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600617 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600618 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700619 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
620 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
621 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600622 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600623 }
624 if (mode != spv::BadValue)
625 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
626
John Kesseniche6903322015-10-13 16:29:02 -0600627 switch (glslangIntermediate->getVertexSpacing()) {
628 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
629 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
630 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
631 default: mode = spv::BadValue; break;
632 }
633 if (mode != spv::BadValue)
634 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
635
636 switch (glslangIntermediate->getVertexOrder()) {
637 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
638 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
639 default: mode = spv::BadValue; break;
640 }
641 if (mode != spv::BadValue)
642 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
643
644 if (glslangIntermediate->getPointMode())
645 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600646 break;
647
648 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600649 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600650 switch (glslangIntermediate->getInputPrimitive()) {
651 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
652 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
653 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700654 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600655 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
656 default: mode = spv::BadValue; break;
657 }
658 if (mode != spv::BadValue)
659 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600660
John Kessenich140f3df2015-06-26 16:58:36 -0600661 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
662
663 switch (glslangIntermediate->getOutputPrimitive()) {
664 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
665 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
666 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
667 default: mode = spv::BadValue; break;
668 }
669 if (mode != spv::BadValue)
670 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
671 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
672 break;
673
674 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600675 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600676 if (glslangIntermediate->getPixelCenterInteger())
677 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600678
John Kessenich140f3df2015-06-26 16:58:36 -0600679 if (glslangIntermediate->getOriginUpperLeft())
680 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600681 else
682 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600683
684 if (glslangIntermediate->getEarlyFragmentTests())
685 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
686
687 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600688 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
689 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
690 default: mode = spv::BadValue; break;
691 }
692 if (mode != spv::BadValue)
693 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
694
695 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
696 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600697 break;
698
699 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600700 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600701 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
702 glslangIntermediate->getLocalSize(1),
703 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600704 break;
705
706 default:
707 break;
708 }
709
710}
711
John Kessenich7ba63412015-12-20 17:37:07 -0700712// Finish everything and dump
713void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
714{
715 // finish off the entry-point SPV instruction by adding the Input/Output <id>
716 for (auto it : iOSet)
717 entryPoint->addIdOperand(it);
718
719 builder.dump(out);
720}
721
John Kessenich140f3df2015-06-26 16:58:36 -0600722TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
723{
724 if (! mainTerminated) {
725 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
726 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600727 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600728 }
729}
730
731//
732// Implement the traversal functions.
733//
734// Return true from interior nodes to have the external traversal
735// continue on to children. Return false if children were
736// already processed.
737//
738
739//
740// Symbols can turn into
741// - uniform/input reads
742// - output writes
743// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
744// - something simple that degenerates into the last bullet
745//
746void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
747{
748 // getSymbolId() will set up all the IO decorations on the first call.
749 // Formal function parameters were mapped during makeFunctions().
750 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700751
752 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
753 if (builder.isPointer(id)) {
754 spv::StorageClass sc = builder.getStorageClass(id);
755 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
756 iOSet.insert(id);
757 }
758
759 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700760 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600761 // Prepare to generate code for the access
762
763 // L-value chains will be computed left to right. We're on the symbol now,
764 // which is the left-most part of the access chain, so now is "clear" time,
765 // followed by setting the base.
766 builder.clearAccessChain();
767
768 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700769 // except for
770 // A) "const in" arguments to a function, which are an intermediate object.
771 // See comments in handleUserFunctionCall().
772 // B) Specialization constants (normal constant don't even come in as a variable),
773 // These are also pure R-values.
774 glslang::TQualifier qualifier = symbol->getQualifier();
775 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
776 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600777 builder.setAccessChainRValue(id);
778 else
779 builder.setAccessChainLValue(id);
780 }
781}
782
783bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
784{
785 // First, handle special cases
786 switch (node->getOp()) {
787 case glslang::EOpAssign:
788 case glslang::EOpAddAssign:
789 case glslang::EOpSubAssign:
790 case glslang::EOpMulAssign:
791 case glslang::EOpVectorTimesMatrixAssign:
792 case glslang::EOpVectorTimesScalarAssign:
793 case glslang::EOpMatrixTimesScalarAssign:
794 case glslang::EOpMatrixTimesMatrixAssign:
795 case glslang::EOpDivAssign:
796 case glslang::EOpModAssign:
797 case glslang::EOpAndAssign:
798 case glslang::EOpInclusiveOrAssign:
799 case glslang::EOpExclusiveOrAssign:
800 case glslang::EOpLeftShiftAssign:
801 case glslang::EOpRightShiftAssign:
802 // A bin-op assign "a += b" means the same thing as "a = a + b"
803 // where a is evaluated before b. For a simple assignment, GLSL
804 // says to evaluate the left before the right. So, always, left
805 // node then right node.
806 {
807 // get the left l-value, save it away
808 builder.clearAccessChain();
809 node->getLeft()->traverse(this);
810 spv::Builder::AccessChain lValue = builder.getAccessChain();
811
812 // evaluate the right
813 builder.clearAccessChain();
814 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700815 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600816
817 if (node->getOp() != glslang::EOpAssign) {
818 // the left is also an r-value
819 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700820 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600821
822 // do the operation
823 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
824 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
825 node->getType().getBasicType());
826
827 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700828 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600829 }
830
831 // store the result
832 builder.setAccessChain(lValue);
833 builder.accessChainStore(rValue);
834
835 // assignments are expressions having an rValue after they are evaluated...
836 builder.clearAccessChain();
837 builder.setAccessChainRValue(rValue);
838 }
839 return false;
840 case glslang::EOpIndexDirect:
841 case glslang::EOpIndexDirectStruct:
842 {
843 // Get the left part of the access chain.
844 node->getLeft()->traverse(this);
845
846 // Add the next element in the chain
847
John Kessenich55e7d112015-11-15 21:33:39 -0700848 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600849 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
850 // This may be, e.g., an anonymous block-member selection, which generally need
851 // index remapping due to hidden members in anonymous blocks.
852 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700853 assert(remapper.size() > 0);
854 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600855 }
856
857 if (! node->getLeft()->getType().isArray() &&
858 node->getLeft()->getType().isVector() &&
859 node->getOp() == glslang::EOpIndexDirect) {
860 // This is essentially a hard-coded vector swizzle of size 1,
861 // so short circuit the access-chain stuff with a swizzle.
862 std::vector<unsigned> swizzle;
863 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600864 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600865 } else {
866 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600867 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600868 }
869 }
870 return false;
871 case glslang::EOpIndexIndirect:
872 {
873 // Structure or array or vector indirection.
874 // Will use native SPIR-V access-chain for struct and array indirection;
875 // matrices are arrays of vectors, so will also work for a matrix.
876 // Will use the access chain's 'component' for variable index into a vector.
877
878 // This adapter is building access chains left to right.
879 // Set up the access chain to the left.
880 node->getLeft()->traverse(this);
881
882 // save it so that computing the right side doesn't trash it
883 spv::Builder::AccessChain partial = builder.getAccessChain();
884
885 // compute the next index in the chain
886 builder.clearAccessChain();
887 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700888 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600889
890 // restore the saved access chain
891 builder.setAccessChain(partial);
892
893 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600894 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600895 else
John Kessenichfa668da2015-09-13 14:46:30 -0600896 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600897 }
898 return false;
899 case glslang::EOpVectorSwizzle:
900 {
901 node->getLeft()->traverse(this);
902 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
903 std::vector<unsigned> swizzle;
904 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
905 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600906 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600907 }
908 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600909 case glslang::EOpLogicalOr:
910 case glslang::EOpLogicalAnd:
911 {
912
913 // These may require short circuiting, but can sometimes be done as straight
914 // binary operations. The right operand must be short circuited if it has
915 // side effects, and should probably be if it is complex.
916 if (isTrivial(node->getRight()->getAsTyped()))
917 break; // handle below as a normal binary operation
918 // otherwise, we need to do dynamic short circuiting on the right operand
919 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
920 builder.clearAccessChain();
921 builder.setAccessChainRValue(result);
922 }
923 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600924 default:
925 break;
926 }
927
928 // Assume generic binary op...
929
John Kessenich32cfd492016-02-02 12:37:46 -0700930 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600931 builder.clearAccessChain();
932 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700933 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600934
John Kessenich32cfd492016-02-02 12:37:46 -0700935 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600936 builder.clearAccessChain();
937 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700938 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600939
John Kessenich32cfd492016-02-02 12:37:46 -0700940 // get result
941 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
942 convertGlslangToSpvType(node->getType()), left, right,
943 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600944
John Kessenich50e57562015-12-21 21:21:11 -0700945 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600946 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700947 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700948 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600949 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600950 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600951 return false;
952 }
John Kessenich140f3df2015-06-26 16:58:36 -0600953}
954
955bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
956{
John Kessenichfc51d282015-08-19 13:34:18 -0600957 spv::Id result = spv::NoResult;
958
959 // try texturing first
960 result = createImageTextureFunctionCall(node);
961 if (result != spv::NoResult) {
962 builder.clearAccessChain();
963 builder.setAccessChainRValue(result);
964
965 return false; // done with this node
966 }
967
968 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600969
970 if (node->getOp() == glslang::EOpArrayLength) {
971 // Quite special; won't want to evaluate the operand.
972
973 // Normal .length() would have been constant folded by the front-end.
974 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600975 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600976 assert(node->getOperand()->getType().isRuntimeSizedArray());
977 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
978 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600979 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
980 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600981
982 builder.clearAccessChain();
983 builder.setAccessChainRValue(length);
984
985 return false;
986 }
987
John Kessenichfc51d282015-08-19 13:34:18 -0600988 // Start by evaluating the operand
989
John Kessenich140f3df2015-06-26 16:58:36 -0600990 builder.clearAccessChain();
991 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800992
Rex Xufc618912015-09-09 16:42:49 +0800993 spv::Id operand = spv::NoResult;
994
995 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
996 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800997 node->getOp() == glslang::EOpAtomicCounter ||
998 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800999 operand = builder.accessChainGetLValue(); // Special case l-value operands
1000 else
John Kessenich32cfd492016-02-02 12:37:46 -07001001 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001002
1003 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1004
1005 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001006 if (! result)
1007 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001008
1009 // if not, then possibly an operation
1010 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001011 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001012
1013 if (result) {
1014 builder.clearAccessChain();
1015 builder.setAccessChainRValue(result);
1016
1017 return false; // done with this node
1018 }
1019
1020 // it must be a special case, check...
1021 switch (node->getOp()) {
1022 case glslang::EOpPostIncrement:
1023 case glslang::EOpPostDecrement:
1024 case glslang::EOpPreIncrement:
1025 case glslang::EOpPreDecrement:
1026 {
1027 // we need the integer value "1" or the floating point "1.0" to add/subtract
1028 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1029 builder.makeFloatConstant(1.0F) :
1030 builder.makeIntConstant(1);
1031 glslang::TOperator op;
1032 if (node->getOp() == glslang::EOpPreIncrement ||
1033 node->getOp() == glslang::EOpPostIncrement)
1034 op = glslang::EOpAdd;
1035 else
1036 op = glslang::EOpSub;
1037
1038 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1039 convertGlslangToSpvType(node->getType()), operand, one,
1040 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001041 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001042
1043 // The result of operation is always stored, but conditionally the
1044 // consumed result. The consumed result is always an r-value.
1045 builder.accessChainStore(result);
1046 builder.clearAccessChain();
1047 if (node->getOp() == glslang::EOpPreIncrement ||
1048 node->getOp() == glslang::EOpPreDecrement)
1049 builder.setAccessChainRValue(result);
1050 else
1051 builder.setAccessChainRValue(operand);
1052 }
1053
1054 return false;
1055
1056 case glslang::EOpEmitStreamVertex:
1057 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1058 return false;
1059 case glslang::EOpEndStreamPrimitive:
1060 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1061 return false;
1062
1063 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001064 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001065 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001066 }
John Kessenich140f3df2015-06-26 16:58:36 -06001067}
1068
1069bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1070{
John Kessenichfc51d282015-08-19 13:34:18 -06001071 spv::Id result = spv::NoResult;
1072
1073 // try texturing
1074 result = createImageTextureFunctionCall(node);
1075 if (result != spv::NoResult) {
1076 builder.clearAccessChain();
1077 builder.setAccessChainRValue(result);
1078
1079 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001080 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001081 // "imageStore" is a special case, which has no result
1082 return false;
1083 }
John Kessenichfc51d282015-08-19 13:34:18 -06001084
John Kessenich140f3df2015-06-26 16:58:36 -06001085 glslang::TOperator binOp = glslang::EOpNull;
1086 bool reduceComparison = true;
1087 bool isMatrix = false;
1088 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001089 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001090
1091 assert(node->getOp());
1092
1093 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1094
1095 switch (node->getOp()) {
1096 case glslang::EOpSequence:
1097 {
1098 if (preVisit)
1099 ++sequenceDepth;
1100 else
1101 --sequenceDepth;
1102
1103 if (sequenceDepth == 1) {
1104 // If this is the parent node of all the functions, we want to see them
1105 // early, so all call points have actual SPIR-V functions to reference.
1106 // In all cases, still let the traverser visit the children for us.
1107 makeFunctions(node->getAsAggregate()->getSequence());
1108
1109 // Also, we want all globals initializers to go into the entry of main(), before
1110 // anything else gets there, so visit out of order, doing them all now.
1111 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1112
1113 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1114 // so do them manually.
1115 visitFunctions(node->getAsAggregate()->getSequence());
1116
1117 return false;
1118 }
1119
1120 return true;
1121 }
1122 case glslang::EOpLinkerObjects:
1123 {
1124 if (visit == glslang::EvPreVisit)
1125 linkageOnly = true;
1126 else
1127 linkageOnly = false;
1128
1129 return true;
1130 }
1131 case glslang::EOpComma:
1132 {
1133 // processing from left to right naturally leaves the right-most
1134 // lying around in the access chain
1135 glslang::TIntermSequence& glslangOperands = node->getSequence();
1136 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1137 glslangOperands[i]->traverse(this);
1138
1139 return false;
1140 }
1141 case glslang::EOpFunction:
1142 if (visit == glslang::EvPreVisit) {
1143 if (isShaderEntrypoint(node)) {
1144 inMain = true;
1145 builder.setBuildPoint(shaderEntry->getLastBlock());
1146 } else {
1147 handleFunctionEntry(node);
1148 }
1149 } else {
1150 if (inMain)
1151 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001152 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001153 inMain = false;
1154 }
1155
1156 return true;
1157 case glslang::EOpParameters:
1158 // Parameters will have been consumed by EOpFunction processing, but not
1159 // the body, so we still visited the function node's children, making this
1160 // child redundant.
1161 return false;
1162 case glslang::EOpFunctionCall:
1163 {
1164 if (node->isUserDefined())
1165 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001166 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1167 if (result) {
1168 builder.clearAccessChain();
1169 builder.setAccessChainRValue(result);
1170 } else
1171 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001172
1173 return false;
1174 }
1175 case glslang::EOpConstructMat2x2:
1176 case glslang::EOpConstructMat2x3:
1177 case glslang::EOpConstructMat2x4:
1178 case glslang::EOpConstructMat3x2:
1179 case glslang::EOpConstructMat3x3:
1180 case glslang::EOpConstructMat3x4:
1181 case glslang::EOpConstructMat4x2:
1182 case glslang::EOpConstructMat4x3:
1183 case glslang::EOpConstructMat4x4:
1184 case glslang::EOpConstructDMat2x2:
1185 case glslang::EOpConstructDMat2x3:
1186 case glslang::EOpConstructDMat2x4:
1187 case glslang::EOpConstructDMat3x2:
1188 case glslang::EOpConstructDMat3x3:
1189 case glslang::EOpConstructDMat3x4:
1190 case glslang::EOpConstructDMat4x2:
1191 case glslang::EOpConstructDMat4x3:
1192 case glslang::EOpConstructDMat4x4:
1193 isMatrix = true;
1194 // fall through
1195 case glslang::EOpConstructFloat:
1196 case glslang::EOpConstructVec2:
1197 case glslang::EOpConstructVec3:
1198 case glslang::EOpConstructVec4:
1199 case glslang::EOpConstructDouble:
1200 case glslang::EOpConstructDVec2:
1201 case glslang::EOpConstructDVec3:
1202 case glslang::EOpConstructDVec4:
1203 case glslang::EOpConstructBool:
1204 case glslang::EOpConstructBVec2:
1205 case glslang::EOpConstructBVec3:
1206 case glslang::EOpConstructBVec4:
1207 case glslang::EOpConstructInt:
1208 case glslang::EOpConstructIVec2:
1209 case glslang::EOpConstructIVec3:
1210 case glslang::EOpConstructIVec4:
1211 case glslang::EOpConstructUint:
1212 case glslang::EOpConstructUVec2:
1213 case glslang::EOpConstructUVec3:
1214 case glslang::EOpConstructUVec4:
1215 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001216 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001217 {
1218 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001219 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001220 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1221 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001222 if (node->getOp() == glslang::EOpConstructTextureSampler)
1223 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1224 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001225 std::vector<spv::Id> constituents;
1226 for (int c = 0; c < (int)arguments.size(); ++c)
1227 constituents.push_back(arguments[c]);
1228 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001229 } else if (isMatrix)
1230 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1231 else
1232 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001233
1234 builder.clearAccessChain();
1235 builder.setAccessChainRValue(constructed);
1236
1237 return false;
1238 }
1239
1240 // These six are component-wise compares with component-wise results.
1241 // Forward on to createBinaryOperation(), requesting a vector result.
1242 case glslang::EOpLessThan:
1243 case glslang::EOpGreaterThan:
1244 case glslang::EOpLessThanEqual:
1245 case glslang::EOpGreaterThanEqual:
1246 case glslang::EOpVectorEqual:
1247 case glslang::EOpVectorNotEqual:
1248 {
1249 // Map the operation to a binary
1250 binOp = node->getOp();
1251 reduceComparison = false;
1252 switch (node->getOp()) {
1253 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1254 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1255 default: binOp = node->getOp(); break;
1256 }
1257
1258 break;
1259 }
1260 case glslang::EOpMul:
1261 // compontent-wise matrix multiply
1262 binOp = glslang::EOpMul;
1263 break;
1264 case glslang::EOpOuterProduct:
1265 // two vectors multiplied to make a matrix
1266 binOp = glslang::EOpOuterProduct;
1267 break;
1268 case glslang::EOpDot:
1269 {
1270 // for scalar dot product, use multiply
1271 glslang::TIntermSequence& glslangOperands = node->getSequence();
1272 if (! glslangOperands[0]->getAsTyped()->isVector())
1273 binOp = glslang::EOpMul;
1274 break;
1275 }
1276 case glslang::EOpMod:
1277 // when an aggregate, this is the floating-point mod built-in function,
1278 // which can be emitted by the one in createBinaryOperation()
1279 binOp = glslang::EOpMod;
1280 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001281 case glslang::EOpEmitVertex:
1282 case glslang::EOpEndPrimitive:
1283 case glslang::EOpBarrier:
1284 case glslang::EOpMemoryBarrier:
1285 case glslang::EOpMemoryBarrierAtomicCounter:
1286 case glslang::EOpMemoryBarrierBuffer:
1287 case glslang::EOpMemoryBarrierImage:
1288 case glslang::EOpMemoryBarrierShared:
1289 case glslang::EOpGroupMemoryBarrier:
1290 noReturnValue = true;
1291 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1292 break;
1293
John Kessenich426394d2015-07-23 10:22:48 -06001294 case glslang::EOpAtomicAdd:
1295 case glslang::EOpAtomicMin:
1296 case glslang::EOpAtomicMax:
1297 case glslang::EOpAtomicAnd:
1298 case glslang::EOpAtomicOr:
1299 case glslang::EOpAtomicXor:
1300 case glslang::EOpAtomicExchange:
1301 case glslang::EOpAtomicCompSwap:
1302 atomic = true;
1303 break;
1304
John Kessenich140f3df2015-06-26 16:58:36 -06001305 default:
1306 break;
1307 }
1308
1309 //
1310 // See if it maps to a regular operation.
1311 //
John Kessenich140f3df2015-06-26 16:58:36 -06001312 if (binOp != glslang::EOpNull) {
1313 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1314 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1315 assert(left && right);
1316
1317 builder.clearAccessChain();
1318 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001319 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001320
1321 builder.clearAccessChain();
1322 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001323 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001324
1325 result = createBinaryOperation(binOp, precision,
1326 convertGlslangToSpvType(node->getType()), leftId, rightId,
1327 left->getType().getBasicType(), reduceComparison);
1328
1329 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001330 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001331 builder.clearAccessChain();
1332 builder.setAccessChainRValue(result);
1333
1334 return false;
1335 }
1336
John Kessenich426394d2015-07-23 10:22:48 -06001337 //
1338 // Create the list of operands.
1339 //
John Kessenich140f3df2015-06-26 16:58:36 -06001340 glslang::TIntermSequence& glslangOperands = node->getSequence();
1341 std::vector<spv::Id> operands;
1342 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1343 builder.clearAccessChain();
1344 glslangOperands[arg]->traverse(this);
1345
1346 // special case l-value operands; there are just a few
1347 bool lvalue = false;
1348 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001349 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001350 case glslang::EOpModf:
1351 if (arg == 1)
1352 lvalue = true;
1353 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001354 case glslang::EOpInterpolateAtSample:
1355 case glslang::EOpInterpolateAtOffset:
1356 if (arg == 0)
1357 lvalue = true;
1358 break;
Rex Xud4782c12015-09-06 16:30:11 +08001359 case glslang::EOpAtomicAdd:
1360 case glslang::EOpAtomicMin:
1361 case glslang::EOpAtomicMax:
1362 case glslang::EOpAtomicAnd:
1363 case glslang::EOpAtomicOr:
1364 case glslang::EOpAtomicXor:
1365 case glslang::EOpAtomicExchange:
1366 case glslang::EOpAtomicCompSwap:
1367 if (arg == 0)
1368 lvalue = true;
1369 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001370 case glslang::EOpAddCarry:
1371 case glslang::EOpSubBorrow:
1372 if (arg == 2)
1373 lvalue = true;
1374 break;
1375 case glslang::EOpUMulExtended:
1376 case glslang::EOpIMulExtended:
1377 if (arg >= 2)
1378 lvalue = true;
1379 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001380 default:
1381 break;
1382 }
1383 if (lvalue)
1384 operands.push_back(builder.accessChainGetLValue());
1385 else
John Kessenich32cfd492016-02-02 12:37:46 -07001386 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001387 }
John Kessenich426394d2015-07-23 10:22:48 -06001388
1389 if (atomic) {
1390 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001391 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001392 } else {
1393 // Pass through to generic operations.
1394 switch (glslangOperands.size()) {
1395 case 0:
1396 result = createNoArgOperation(node->getOp());
1397 break;
1398 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001399 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001400 break;
1401 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001402 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001403 break;
1404 }
John Kessenich140f3df2015-06-26 16:58:36 -06001405 }
1406
1407 if (noReturnValue)
1408 return false;
1409
1410 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001411 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001412 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001413 } else {
1414 builder.clearAccessChain();
1415 builder.setAccessChainRValue(result);
1416 return false;
1417 }
1418}
1419
1420bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1421{
1422 // This path handles both if-then-else and ?:
1423 // The if-then-else has a node type of void, while
1424 // ?: has a non-void node type
1425 spv::Id result = 0;
1426 if (node->getBasicType() != glslang::EbtVoid) {
1427 // don't handle this as just on-the-fly temporaries, because there will be two names
1428 // and better to leave SSA to later passes
1429 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1430 }
1431
1432 // emit the condition before doing anything with selection
1433 node->getCondition()->traverse(this);
1434
1435 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001436 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001437
1438 if (node->getTrueBlock()) {
1439 // emit the "then" statement
1440 node->getTrueBlock()->traverse(this);
1441 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001442 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001443 }
1444
1445 if (node->getFalseBlock()) {
1446 ifBuilder.makeBeginElse();
1447 // emit the "else" statement
1448 node->getFalseBlock()->traverse(this);
1449 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001450 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001451 }
1452
1453 ifBuilder.makeEndIf();
1454
1455 if (result) {
1456 // GLSL only has r-values as the result of a :?, but
1457 // if we have an l-value, that can be more efficient if it will
1458 // become the base of a complex r-value expression, because the
1459 // next layer copies r-values into memory to use the access-chain mechanism
1460 builder.clearAccessChain();
1461 builder.setAccessChainLValue(result);
1462 }
1463
1464 return false;
1465}
1466
1467bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1468{
1469 // emit and get the condition before doing anything with switch
1470 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001471 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001472
1473 // browse the children to sort out code segments
1474 int defaultSegment = -1;
1475 std::vector<TIntermNode*> codeSegments;
1476 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1477 std::vector<int> caseValues;
1478 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1479 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1480 TIntermNode* child = *c;
1481 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001482 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001483 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001484 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001485 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1486 } else
1487 codeSegments.push_back(child);
1488 }
1489
1490 // handle the case where the last code segment is missing, due to no code
1491 // statements between the last case and the end of the switch statement
1492 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1493 (int)codeSegments.size() == defaultSegment)
1494 codeSegments.push_back(nullptr);
1495
1496 // make the switch statement
1497 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001498 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001499
1500 // emit all the code in the segments
1501 breakForLoop.push(false);
1502 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1503 builder.nextSwitchSegment(segmentBlocks, s);
1504 if (codeSegments[s])
1505 codeSegments[s]->traverse(this);
1506 else
1507 builder.addSwitchBreak();
1508 }
1509 breakForLoop.pop();
1510
1511 builder.endSwitch(segmentBlocks);
1512
1513 return false;
1514}
1515
1516void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1517{
1518 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001519 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001520
1521 builder.clearAccessChain();
1522 builder.setAccessChainRValue(constant);
1523}
1524
1525bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1526{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001527 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001528 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001529 // Spec requires back edges to target header blocks, and every header block
1530 // must dominate its merge block. Make a header block first to ensure these
1531 // conditions are met. By definition, it will contain OpLoopMerge, followed
1532 // by a block-ending branch. But we don't want to put any other body/test
1533 // instructions in it, since the body/test may have arbitrary instructions,
1534 // including merges of its own.
1535 builder.setBuildPoint(&blocks.head);
1536 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001537 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001538 spv::Block& test = builder.makeNewBlock();
1539 builder.createBranch(&test);
1540
1541 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001542 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001543 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001544 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001545 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1546
1547 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001548 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001549 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001550 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001551 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001552 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001553
1554 builder.setBuildPoint(&blocks.continue_target);
1555 if (node->getTerminal())
1556 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001557 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001558 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001559 builder.createBranch(&blocks.body);
1560
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001561 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001562 builder.setBuildPoint(&blocks.body);
1563 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001564 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001565 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001566 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001567
1568 builder.setBuildPoint(&blocks.continue_target);
1569 if (node->getTerminal())
1570 node->getTerminal()->traverse(this);
1571 if (node->getTest()) {
1572 node->getTest()->traverse(this);
1573 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001574 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001575 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001576 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001577 // TODO: unless there was a break/return/discard instruction
1578 // somewhere in the body, this is an infinite loop, so we should
1579 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001580 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001581 }
John Kessenich140f3df2015-06-26 16:58:36 -06001582 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001583 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001584 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001585 return false;
1586}
1587
1588bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1589{
1590 if (node->getExpression())
1591 node->getExpression()->traverse(this);
1592
1593 switch (node->getFlowOp()) {
1594 case glslang::EOpKill:
1595 builder.makeDiscard();
1596 break;
1597 case glslang::EOpBreak:
1598 if (breakForLoop.top())
1599 builder.createLoopExit();
1600 else
1601 builder.addSwitchBreak();
1602 break;
1603 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001604 builder.createLoopContinue();
1605 break;
1606 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001607 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001608 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001609 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001610 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001611
1612 builder.clearAccessChain();
1613 break;
1614
1615 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001616 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001617 break;
1618 }
1619
1620 return false;
1621}
1622
1623spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1624{
1625 // First, steer off constants, which are not SPIR-V variables, but
1626 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001627 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001628 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001629 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001630 }
1631
1632 // Now, handle actual variables
1633 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1634 spv::Id spvType = convertGlslangToSpvType(node->getType());
1635
1636 const char* name = node->getName().c_str();
1637 if (glslang::IsAnonymous(name))
1638 name = "";
1639
1640 return builder.createVariable(storageClass, spvType, name);
1641}
1642
1643// Return type Id of the sampled type.
1644spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1645{
1646 switch (sampler.type) {
1647 case glslang::EbtFloat: return builder.makeFloatType(32);
1648 case glslang::EbtInt: return builder.makeIntType(32);
1649 case glslang::EbtUint: return builder.makeUintType(32);
1650 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001651 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001652 return builder.makeFloatType(32);
1653 }
1654}
1655
John Kessenich3ac051e2015-12-20 11:29:16 -07001656// Convert from a glslang type to an SPV type, by calling into a
1657// recursive version of this function. This establishes the inherited
1658// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001659spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1660{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001661 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001662}
1663
1664// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001665// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001666spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001667{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001668 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001669
1670 switch (type.getBasicType()) {
1671 case glslang::EbtVoid:
1672 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001673 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001674 break;
1675 case glslang::EbtFloat:
1676 spvType = builder.makeFloatType(32);
1677 break;
1678 case glslang::EbtDouble:
1679 spvType = builder.makeFloatType(64);
1680 break;
1681 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001682 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1683 // a 32-bit int where non-0 means true.
1684 if (explicitLayout != glslang::ElpNone)
1685 spvType = builder.makeUintType(32);
1686 else
1687 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001688 break;
1689 case glslang::EbtInt:
1690 spvType = builder.makeIntType(32);
1691 break;
1692 case glslang::EbtUint:
1693 spvType = builder.makeUintType(32);
1694 break;
John Kessenich426394d2015-07-23 10:22:48 -06001695 case glslang::EbtAtomicUint:
1696 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1697 spvType = builder.makeUintType(32);
1698 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001699 case glslang::EbtSampler:
1700 {
1701 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001702 if (sampler.sampler) {
1703 // pure sampler
1704 spvType = builder.makeSamplerType();
1705 } else {
1706 // an image is present, make its type
1707 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1708 sampler.image ? 2 : 1, TranslateImageFormat(type));
1709 if (sampler.combined) {
1710 // already has both image and sampler, make the combined type
1711 spvType = builder.makeSampledImageType(spvType);
1712 }
John Kessenich55e7d112015-11-15 21:33:39 -07001713 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001714 }
John Kessenich140f3df2015-06-26 16:58:36 -06001715 break;
1716 case glslang::EbtStruct:
1717 case glslang::EbtBlock:
1718 {
1719 // If we've seen this struct type, return it
1720 const glslang::TTypeList* glslangStruct = type.getStruct();
1721 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001722
1723 // Try to share structs for different layouts, but not yet for other
1724 // kinds of qualification (primarily not yet including interpolant qualification).
1725 if (! HasNonLayoutQualifiers(qualifier))
1726 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1727 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001728 break;
1729
1730 // else, we haven't seen it...
1731
1732 // Create a vector of struct types for SPIR-V to consume
1733 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1734 if (type.getBasicType() == glslang::EbtBlock)
1735 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001736 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001737 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1738 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1739 if (glslangType.hiddenMember()) {
1740 ++memberDelta;
1741 if (type.getBasicType() == glslang::EbtBlock)
1742 memberRemapper[glslangStruct][i] = -1;
1743 } else {
1744 if (type.getBasicType() == glslang::EbtBlock)
1745 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001746 // modify just this child's view of the qualifier
1747 glslang::TQualifier subQualifier = glslangType.getQualifier();
1748 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001749
1750 // manually inherit location; it's more complex
1751 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1752 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1753 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001754 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001755
1756 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001757 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001758 }
1759 }
1760
1761 // Make the SPIR-V type
1762 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001763 if (! HasNonLayoutQualifiers(qualifier))
1764 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001765
1766 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001767 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001768 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001769 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1770 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1771 int member = i;
1772 if (type.getBasicType() == glslang::EbtBlock)
1773 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001774
John Kesseniche0b6cad2015-12-24 10:30:13 -07001775 // modify just this child's view of the qualifier
1776 glslang::TQualifier subQualifier = glslangType.getQualifier();
1777 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001778
John Kessenich140f3df2015-06-26 16:58:36 -06001779 // using -1 above to indicate a hidden member
1780 if (member >= 0) {
1781 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001782 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001783 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001784 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1785 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001786
Rex Xu1da878f2016-02-21 20:59:01 +08001787 if (qualifier.storage == glslang::EvqBuffer) {
1788 std::vector<spv::Decoration> memory;
1789 TranslateMemoryDecoration(subQualifier, memory);
1790 for (unsigned int i = 0; i < memory.size(); ++i)
1791 addMemberDecoration(spvType, member, memory[i]);
1792 }
1793
John Kessenich09677482016-02-19 12:21:50 -07001794 // compute location decoration; tricky based on whether inheritance is at play
1795 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1796 // probably move to the linker stage of the front end proper, and just have the
1797 // answer sitting already distributed throughout the individual member locations.
1798 int location = -1; // will only decorate if present or inherited
1799 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1800 location = subQualifier.layoutLocation;
1801 else if (qualifier.hasLocation()) // inheritance
1802 location = qualifier.layoutLocation + locationOffset;
1803 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001804 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001805 if (location >= 0)
1806 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1807
1808 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001809 if (glslangType.getQualifier().hasComponent())
1810 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1811 if (glslangType.getQualifier().hasXfbOffset())
1812 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001813 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001814 // figure out what to do with offset, which is accumulating
1815 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001816 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001817 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001818 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001819 offset = nextOffset;
1820 }
John Kessenich140f3df2015-06-26 16:58:36 -06001821
John Kessenichf85e8062015-12-19 13:57:10 -07001822 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001823 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001824
John Kessenich140f3df2015-06-26 16:58:36 -06001825 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001826 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1827 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001828 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001829 }
1830 }
1831
1832 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001833 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001834 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001835 if (type.getQualifier().hasStream()) {
1836 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001837 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001838 }
John Kessenich140f3df2015-06-26 16:58:36 -06001839 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001840 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001841 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001842 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001843 if (type.getQualifier().hasXfbBuffer())
1844 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1845 }
1846 }
1847 break;
1848 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001849 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001850 break;
1851 }
1852
1853 if (type.isMatrix())
1854 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1855 else {
1856 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1857 if (type.getVectorSize() > 1)
1858 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1859 }
1860
1861 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001862 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1863
John Kessenichc9a80832015-09-12 12:17:44 -06001864 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001865 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001866 // We need to decorate array strides for types needing explicit layout, except blocks.
1867 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001868 // Use a dummy glslang type for querying internal strides of
1869 // arrays of arrays, but using just a one-dimensional array.
1870 glslang::TType simpleArrayType(type, 0); // deference type of the array
1871 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1872 simpleArrayType.getArraySizes().dereference();
1873
1874 // Will compute the higher-order strides here, rather than making a whole
1875 // pile of types and doing repetitive recursion on their contents.
1876 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1877 }
John Kessenichf8842e52016-01-04 19:22:56 -07001878
1879 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001880 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001881 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001882 if (stride > 0)
1883 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001884 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001885 }
1886 } else {
1887 // single-dimensional array, and don't yet have stride
1888
John Kessenichf8842e52016-01-04 19:22:56 -07001889 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001890 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1891 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001892 }
John Kessenich31ed4832015-09-09 17:51:38 -06001893
John Kessenichc9a80832015-09-12 12:17:44 -06001894 // Do the outer dimension, which might not be known for a runtime-sized array
1895 if (type.isRuntimeSizedArray()) {
1896 spvType = builder.makeRuntimeArray(spvType);
1897 } else {
1898 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001899 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001900 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001901 if (stride > 0)
1902 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001903 }
1904
1905 return spvType;
1906}
1907
John Kessenich6c292d32016-02-15 20:58:50 -07001908// Turn the expression forming the array size into an id.
1909// This is not quite trivial, because of specialization constants.
1910// Sometimes, a raw constant is turned into an Id, and sometimes
1911// a specialization constant expression is.
1912spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1913{
1914 // First, see if this is sized with a node, meaning a specialization constant:
1915 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1916 if (specNode != nullptr) {
1917 builder.clearAccessChain();
1918 specNode->traverse(this);
1919 return accessChainLoad(specNode->getAsTyped()->getType());
1920 }
1921
1922 // Otherwise, need a compile-time (front end) size, get it:
1923 int size = arraySizes.getDimSize(dim);
1924 assert(size > 0);
1925 return builder.makeUintConstant(size);
1926}
1927
John Kessenich103bef92016-02-08 21:38:15 -07001928// Wrap the builder's accessChainLoad to:
1929// - localize handling of RelaxedPrecision
1930// - use the SPIR-V inferred type instead of another conversion of the glslang type
1931// (avoids unnecessary work and possible type punning for structures)
1932// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001933spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1934{
John Kessenich103bef92016-02-08 21:38:15 -07001935 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1936 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1937
1938 // Need to convert to abstract types when necessary
1939 if (builder.isScalarType(nominalTypeId) && type.getBasicType() == glslang::EbtBool && nominalTypeId != builder.makeBoolType())
1940 loadedId = builder.createBinOp(spv::OpINotEqual, builder.makeBoolType(), loadedId, builder.makeUintConstant(0));
1941
1942 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001943}
1944
John Kessenichf85e8062015-12-19 13:57:10 -07001945// Decide whether or not this type should be
1946// decorated with offsets and strides, and if so
1947// whether std140 or std430 rules should be applied.
1948glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001949{
John Kessenichf85e8062015-12-19 13:57:10 -07001950 // has to be a block
1951 if (type.getBasicType() != glslang::EbtBlock)
1952 return glslang::ElpNone;
1953
1954 // has to be a uniform or buffer block
1955 if (type.getQualifier().storage != glslang::EvqUniform &&
1956 type.getQualifier().storage != glslang::EvqBuffer)
1957 return glslang::ElpNone;
1958
1959 // return the layout to use
1960 switch (type.getQualifier().layoutPacking) {
1961 case glslang::ElpStd140:
1962 case glslang::ElpStd430:
1963 return type.getQualifier().layoutPacking;
1964 default:
1965 return glslang::ElpNone;
1966 }
John Kessenich31ed4832015-09-09 17:51:38 -06001967}
1968
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001969// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001970int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001971{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001972 int size;
John Kessenich49987892015-12-29 17:11:44 -07001973 int stride;
1974 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001975
1976 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001977}
1978
John Kessenich49987892015-12-29 17:11:44 -07001979// 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 -07001980// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001981int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001982{
John Kessenich49987892015-12-29 17:11:44 -07001983 glslang::TType elementType;
1984 elementType.shallowCopy(matrixType);
1985 elementType.clearArraySizes();
1986
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001987 int size;
John Kessenich49987892015-12-29 17:11:44 -07001988 int stride;
1989 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1990
1991 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001992}
1993
John Kessenich5e4b1242015-08-06 22:53:06 -06001994// Given a member type of a struct, realign the current offset for it, and compute
1995// the next (not yet aligned) offset for the next member, which will get aligned
1996// on the next call.
1997// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1998// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1999// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002000void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002001 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002002{
2003 // this will get a positive value when deemed necessary
2004 nextOffset = -1;
2005
John Kessenich5e4b1242015-08-06 22:53:06 -06002006 // override anything in currentOffset with user-set offset
2007 if (memberType.getQualifier().hasOffset())
2008 currentOffset = memberType.getQualifier().layoutOffset;
2009
2010 // It could be that current linker usage in glslang updated all the layoutOffset,
2011 // in which case the following code does not matter. But, that's not quite right
2012 // once cross-compilation unit GLSL validation is done, as the original user
2013 // settings are needed in layoutOffset, and then the following will come into play.
2014
John Kessenichf85e8062015-12-19 13:57:10 -07002015 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002016 if (! memberType.getQualifier().hasOffset())
2017 currentOffset = -1;
2018
2019 return;
2020 }
2021
John Kessenichf85e8062015-12-19 13:57:10 -07002022 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002023 if (currentOffset < 0)
2024 currentOffset = 0;
2025
2026 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2027 // but possibly not yet correctly aligned.
2028
2029 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002030 int dummyStride;
2031 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002032 glslang::RoundToPow2(currentOffset, memberAlignment);
2033 nextOffset = currentOffset + memberSize;
2034}
2035
John Kessenich140f3df2015-06-26 16:58:36 -06002036bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2037{
2038 return node->getName() == "main(";
2039}
2040
2041// Make all the functions, skeletally, without actually visiting their bodies.
2042void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2043{
2044 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2045 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2046 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2047 continue;
2048
2049 // We're on a user function. Set up the basic interface for the function now,
2050 // so that it's available to call.
2051 // Translating the body will happen later.
2052 //
2053 // Typically (except for a "const in" parameter), an address will be passed to the
2054 // function. What it is an address of varies:
2055 //
2056 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2057 // so that write needs to be to a copy, hence the address of a copy works.
2058 //
2059 // - "const in" parameters can just be the r-value, as no writes need occur.
2060 //
2061 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2062 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2063
2064 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002065 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002066 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2067
2068 for (int p = 0; p < (int)parameters.size(); ++p) {
2069 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2070 spv::Id typeId = convertGlslangToSpvType(paramType);
2071 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2072 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2073 else
2074 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002075 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002076 paramTypes.push_back(typeId);
2077 }
2078
2079 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002080 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2081 convertGlslangToSpvType(glslFunction->getType()),
2082 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002083
2084 // Track function to emit/call later
2085 functionMap[glslFunction->getName().c_str()] = function;
2086
2087 // Set the parameter id's
2088 for (int p = 0; p < (int)parameters.size(); ++p) {
2089 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2090 // give a name too
2091 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2092 }
2093 }
2094}
2095
2096// Process all the initializers, while skipping the functions and link objects
2097void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2098{
2099 builder.setBuildPoint(shaderEntry->getLastBlock());
2100 for (int i = 0; i < (int)initializers.size(); ++i) {
2101 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2102 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2103
2104 // We're on a top-level node that's not a function. Treat as an initializer, whose
2105 // code goes into the beginning of main.
2106 initializer->traverse(this);
2107 }
2108 }
2109}
2110
2111// Process all the functions, while skipping initializers.
2112void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2113{
2114 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2115 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2116 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2117 node->traverse(this);
2118 }
2119}
2120
2121void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2122{
2123 // SPIR-V functions should already be in the functionMap from the prepass
2124 // that called makeFunctions().
2125 spv::Function* function = functionMap[node->getName().c_str()];
2126 spv::Block* functionBlock = function->getEntryBlock();
2127 builder.setBuildPoint(functionBlock);
2128}
2129
Rex Xu04db3f52015-09-16 11:44:02 +08002130void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002131{
Rex Xufc618912015-09-09 16:42:49 +08002132 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002133
2134 glslang::TSampler sampler = {};
2135 bool cubeCompare = false;
2136 if (node.isTexture()) {
2137 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2138 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2139 }
2140
John Kessenich140f3df2015-06-26 16:58:36 -06002141 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2142 builder.clearAccessChain();
2143 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002144
2145 // Special case l-value operands
2146 bool lvalue = false;
2147 switch (node.getOp()) {
2148 case glslang::EOpImageAtomicAdd:
2149 case glslang::EOpImageAtomicMin:
2150 case glslang::EOpImageAtomicMax:
2151 case glslang::EOpImageAtomicAnd:
2152 case glslang::EOpImageAtomicOr:
2153 case glslang::EOpImageAtomicXor:
2154 case glslang::EOpImageAtomicExchange:
2155 case glslang::EOpImageAtomicCompSwap:
2156 if (i == 0)
2157 lvalue = true;
2158 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002159 case glslang::EOpSparseTexture:
2160 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2161 lvalue = true;
2162 break;
2163 case glslang::EOpSparseTextureClamp:
2164 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2165 lvalue = true;
2166 break;
2167 case glslang::EOpSparseTextureLod:
2168 case glslang::EOpSparseTextureOffset:
2169 if (i == 3)
2170 lvalue = true;
2171 break;
2172 case glslang::EOpSparseTextureFetch:
2173 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2174 lvalue = true;
2175 break;
2176 case glslang::EOpSparseTextureFetchOffset:
2177 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2178 lvalue = true;
2179 break;
2180 case glslang::EOpSparseTextureLodOffset:
2181 case glslang::EOpSparseTextureGrad:
2182 case glslang::EOpSparseTextureOffsetClamp:
2183 if (i == 4)
2184 lvalue = true;
2185 break;
2186 case glslang::EOpSparseTextureGradOffset:
2187 case glslang::EOpSparseTextureGradClamp:
2188 if (i == 5)
2189 lvalue = true;
2190 break;
2191 case glslang::EOpSparseTextureGradOffsetClamp:
2192 if (i == 6)
2193 lvalue = true;
2194 break;
2195 case glslang::EOpSparseTextureGather:
2196 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2197 lvalue = true;
2198 break;
2199 case glslang::EOpSparseTextureGatherOffset:
2200 case glslang::EOpSparseTextureGatherOffsets:
2201 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2202 lvalue = true;
2203 break;
Rex Xufc618912015-09-09 16:42:49 +08002204 default:
2205 break;
2206 }
2207
Rex Xu6b86d492015-09-16 17:48:22 +08002208 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002209 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002210 else
John Kessenich32cfd492016-02-02 12:37:46 -07002211 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002212 }
2213}
2214
John Kessenichfc51d282015-08-19 13:34:18 -06002215void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002216{
John Kessenichfc51d282015-08-19 13:34:18 -06002217 builder.clearAccessChain();
2218 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002219 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002220}
John Kessenich140f3df2015-06-26 16:58:36 -06002221
John Kessenichfc51d282015-08-19 13:34:18 -06002222spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2223{
Rex Xufc618912015-09-09 16:42:49 +08002224 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002225 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002226 }
2227
John Kessenichfc51d282015-08-19 13:34:18 -06002228 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002229 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2230 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2231 std::vector<spv::Id> arguments;
2232 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002233 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002234 else
2235 translateArguments(*node->getAsUnaryNode(), arguments);
2236 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2237
2238 spv::Builder::TextureParameters params = { };
2239 params.sampler = arguments[0];
2240
Rex Xu04db3f52015-09-16 11:44:02 +08002241 glslang::TCrackedTextureOp cracked;
2242 node->crackTexture(sampler, cracked);
2243
John Kessenichfc51d282015-08-19 13:34:18 -06002244 // Check for queries
2245 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002246 // a sampled image needs to have the image extracted first
2247 if (builder.isSampledImage(params.sampler))
2248 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002249 switch (node->getOp()) {
2250 case glslang::EOpImageQuerySize:
2251 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002252 if (arguments.size() > 1) {
2253 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002254 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002255 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002256 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002257 case glslang::EOpImageQuerySamples:
2258 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002259 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002260 case glslang::EOpTextureQueryLod:
2261 params.coords = arguments[1];
2262 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2263 case glslang::EOpTextureQueryLevels:
2264 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002265 case glslang::EOpSparseTexelsResident:
2266 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002267 default:
2268 assert(0);
2269 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002270 }
John Kessenich140f3df2015-06-26 16:58:36 -06002271 }
2272
Rex Xufc618912015-09-09 16:42:49 +08002273 // Check for image functions other than queries
2274 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002275 std::vector<spv::Id> operands;
2276 auto opIt = arguments.begin();
2277 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002278
2279 // Handle subpass operations
2280 // TODO: GLSL should change to have the "MS" only on the type rather than the
2281 // built-in function.
2282 if (cracked.subpass) {
2283 // add on the (0,0) coordinate
2284 spv::Id zero = builder.makeIntConstant(0);
2285 std::vector<spv::Id> comps;
2286 comps.push_back(zero);
2287 comps.push_back(zero);
2288 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2289 if (sampler.ms) {
2290 operands.push_back(spv::ImageOperandsSampleMask);
2291 operands.push_back(*(opIt++));
2292 }
2293 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2294 }
2295
John Kessenich56bab042015-09-16 10:54:31 -06002296 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002297 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002298 if (sampler.ms) {
2299 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002300 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002301 }
John Kessenich56bab042015-09-16 10:54:31 -06002302 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002303 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2304 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002305 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002306 if (sampler.ms) {
2307 operands.push_back(*(opIt + 1));
2308 operands.push_back(spv::ImageOperandsSampleMask);
2309 operands.push_back(*opIt);
2310 } else
2311 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002312 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002313 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2314 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002315 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002316 } else if (node->isSparseImage()) {
2317 spv::MissingFunctionality("sparse image functions");
2318 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002319 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002320 // Process image atomic operations
2321
2322 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2323 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002324 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002325
Rex Xufc618912015-09-09 16:42:49 +08002326 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002327 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002328
2329 std::vector<spv::Id> operands;
2330 operands.push_back(pointer);
2331 for (; opIt != arguments.end(); ++opIt)
2332 operands.push_back(*opIt);
2333
Rex Xu04db3f52015-09-16 11:44:02 +08002334 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002335 }
2336 }
2337
2338 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002339 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002340 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2341
John Kessenichfc51d282015-08-19 13:34:18 -06002342 // check for bias argument
2343 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002344 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002345 int nonBiasArgCount = 2;
2346 if (cracked.offset)
2347 ++nonBiasArgCount;
2348 if (cracked.grad)
2349 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002350 if (cracked.lodClamp)
2351 ++nonBiasArgCount;
2352 if (sparse)
2353 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002354
2355 if ((int)arguments.size() > nonBiasArgCount)
2356 bias = true;
2357 }
2358
John Kessenichfc51d282015-08-19 13:34:18 -06002359 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002360
John Kessenichfc51d282015-08-19 13:34:18 -06002361 params.coords = arguments[1];
2362 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002363 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002364
2365 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002366 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002367 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002368 ++extraArgs;
2369 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002370 params.Dref = arguments[2];
2371 ++extraArgs;
2372 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002373 std::vector<spv::Id> indexes;
2374 int comp;
2375 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002376 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002377 else
2378 comp = builder.getNumComponents(params.coords) - 1;
2379 indexes.push_back(comp);
2380 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2381 }
2382 if (cracked.lod) {
2383 params.lod = arguments[2];
2384 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002385 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2386 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2387 noImplicitLod = true;
2388 }
2389 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002390 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002391 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002392 }
2393 if (cracked.grad) {
2394 params.gradX = arguments[2 + extraArgs];
2395 params.gradY = arguments[3 + extraArgs];
2396 extraArgs += 2;
2397 }
John Kessenich55e7d112015-11-15 21:33:39 -07002398 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002399 params.offset = arguments[2 + extraArgs];
2400 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002401 } else if (cracked.offsets) {
2402 params.offsets = arguments[2 + extraArgs];
2403 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002404 }
Rex Xu48edadf2015-12-31 16:11:41 +08002405 if (cracked.lodClamp) {
2406 params.lodClamp = arguments[2 + extraArgs];
2407 ++extraArgs;
2408 }
2409 if (sparse) {
2410 params.texelOut = arguments[2 + extraArgs];
2411 ++extraArgs;
2412 }
John Kessenichfc51d282015-08-19 13:34:18 -06002413 if (bias) {
2414 params.bias = arguments[2 + extraArgs];
2415 ++extraArgs;
2416 }
John Kessenich55e7d112015-11-15 21:33:39 -07002417 if (cracked.gather && ! sampler.shadow) {
2418 // default component is 0, if missing, otherwise an argument
2419 if (2 + extraArgs < (int)arguments.size()) {
2420 params.comp = arguments[2 + extraArgs];
2421 ++extraArgs;
2422 } else {
2423 params.comp = builder.makeIntConstant(0);
2424 }
2425 }
John Kessenichfc51d282015-08-19 13:34:18 -06002426
John Kessenich019f08f2016-02-15 15:40:42 -07002427 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002428}
2429
2430spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2431{
2432 // Grab the function's pointer from the previously created function
2433 spv::Function* function = functionMap[node->getName().c_str()];
2434 if (! function)
2435 return 0;
2436
2437 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2438 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2439
2440 // See comments in makeFunctions() for details about the semantics for parameter passing.
2441 //
2442 // These imply we need a four step process:
2443 // 1. Evaluate the arguments
2444 // 2. Allocate and make copies of in, out, and inout arguments
2445 // 3. Make the call
2446 // 4. Copy back the results
2447
2448 // 1. Evaluate the arguments
2449 std::vector<spv::Builder::AccessChain> lValues;
2450 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002451 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002452 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2453 // build l-value
2454 builder.clearAccessChain();
2455 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002456 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002457 // keep outputs as l-values, evaluate input-only as r-values
2458 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2459 // save l-value
2460 lValues.push_back(builder.getAccessChain());
2461 } else {
2462 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002463 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002464 }
2465 }
2466
2467 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2468 // copy the original into that space.
2469 //
2470 // Also, build up the list of actual arguments to pass in for the call
2471 int lValueCount = 0;
2472 int rValueCount = 0;
2473 std::vector<spv::Id> spvArgs;
2474 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2475 spv::Id arg;
2476 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2477 // need space to hold the copy
2478 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2479 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2480 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2481 // need to copy the input into output space
2482 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002483 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002484 builder.createStore(copy, arg);
2485 }
2486 ++lValueCount;
2487 } else {
2488 arg = rValues[rValueCount];
2489 ++rValueCount;
2490 }
2491 spvArgs.push_back(arg);
2492 }
2493
2494 // 3. Make the call.
2495 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002496 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002497
2498 // 4. Copy back out an "out" arguments.
2499 lValueCount = 0;
2500 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2501 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2502 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2503 spv::Id copy = builder.createLoad(spvArgs[a]);
2504 builder.setAccessChain(lValues[lValueCount]);
2505 builder.accessChainStore(copy);
2506 }
2507 ++lValueCount;
2508 }
2509 }
2510
2511 return result;
2512}
2513
2514// Translate AST operation to SPV operation, already having SPV-based operands/types.
2515spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2516 spv::Id typeId, spv::Id left, spv::Id right,
2517 glslang::TBasicType typeProxy, bool reduceComparison)
2518{
2519 bool isUnsigned = typeProxy == glslang::EbtUint;
2520 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2521
2522 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002523 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002524 bool comparison = false;
2525
2526 switch (op) {
2527 case glslang::EOpAdd:
2528 case glslang::EOpAddAssign:
2529 if (isFloat)
2530 binOp = spv::OpFAdd;
2531 else
2532 binOp = spv::OpIAdd;
2533 break;
2534 case glslang::EOpSub:
2535 case glslang::EOpSubAssign:
2536 if (isFloat)
2537 binOp = spv::OpFSub;
2538 else
2539 binOp = spv::OpISub;
2540 break;
2541 case glslang::EOpMul:
2542 case glslang::EOpMulAssign:
2543 if (isFloat)
2544 binOp = spv::OpFMul;
2545 else
2546 binOp = spv::OpIMul;
2547 break;
2548 case glslang::EOpVectorTimesScalar:
2549 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002550 if (isFloat) {
2551 if (builder.isVector(right))
2552 std::swap(left, right);
2553 assert(builder.isScalar(right));
2554 needMatchingVectors = false;
2555 binOp = spv::OpVectorTimesScalar;
2556 } else
2557 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002558 break;
2559 case glslang::EOpVectorTimesMatrix:
2560 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002561 binOp = spv::OpVectorTimesMatrix;
2562 break;
2563 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002564 binOp = spv::OpMatrixTimesVector;
2565 break;
2566 case glslang::EOpMatrixTimesScalar:
2567 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002568 binOp = spv::OpMatrixTimesScalar;
2569 break;
2570 case glslang::EOpMatrixTimesMatrix:
2571 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002572 binOp = spv::OpMatrixTimesMatrix;
2573 break;
2574 case glslang::EOpOuterProduct:
2575 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002576 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002577 break;
2578
2579 case glslang::EOpDiv:
2580 case glslang::EOpDivAssign:
2581 if (isFloat)
2582 binOp = spv::OpFDiv;
2583 else if (isUnsigned)
2584 binOp = spv::OpUDiv;
2585 else
2586 binOp = spv::OpSDiv;
2587 break;
2588 case glslang::EOpMod:
2589 case glslang::EOpModAssign:
2590 if (isFloat)
2591 binOp = spv::OpFMod;
2592 else if (isUnsigned)
2593 binOp = spv::OpUMod;
2594 else
2595 binOp = spv::OpSMod;
2596 break;
2597 case glslang::EOpRightShift:
2598 case glslang::EOpRightShiftAssign:
2599 if (isUnsigned)
2600 binOp = spv::OpShiftRightLogical;
2601 else
2602 binOp = spv::OpShiftRightArithmetic;
2603 break;
2604 case glslang::EOpLeftShift:
2605 case glslang::EOpLeftShiftAssign:
2606 binOp = spv::OpShiftLeftLogical;
2607 break;
2608 case glslang::EOpAnd:
2609 case glslang::EOpAndAssign:
2610 binOp = spv::OpBitwiseAnd;
2611 break;
2612 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002613 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002614 binOp = spv::OpLogicalAnd;
2615 break;
2616 case glslang::EOpInclusiveOr:
2617 case glslang::EOpInclusiveOrAssign:
2618 binOp = spv::OpBitwiseOr;
2619 break;
2620 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002621 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002622 binOp = spv::OpLogicalOr;
2623 break;
2624 case glslang::EOpExclusiveOr:
2625 case glslang::EOpExclusiveOrAssign:
2626 binOp = spv::OpBitwiseXor;
2627 break;
2628 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002629 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002630 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002631 break;
2632
2633 case glslang::EOpLessThan:
2634 case glslang::EOpGreaterThan:
2635 case glslang::EOpLessThanEqual:
2636 case glslang::EOpGreaterThanEqual:
2637 case glslang::EOpEqual:
2638 case glslang::EOpNotEqual:
2639 case glslang::EOpVectorEqual:
2640 case glslang::EOpVectorNotEqual:
2641 comparison = true;
2642 break;
2643 default:
2644 break;
2645 }
2646
John Kessenich7c1aa102015-10-15 13:29:11 -06002647 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002648 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002649 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002650 if (builder.isMatrix(left) || builder.isMatrix(right))
2651 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002652
2653 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002654 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002655 builder.promoteScalar(precision, left, right);
2656
John Kessenich32cfd492016-02-02 12:37:46 -07002657 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002658 }
2659
2660 if (! comparison)
2661 return 0;
2662
John Kessenich7c1aa102015-10-15 13:29:11 -06002663 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002664
2665 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2666 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2667
John Kessenich22118352015-12-21 20:54:09 -07002668 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002669 }
2670
2671 switch (op) {
2672 case glslang::EOpLessThan:
2673 if (isFloat)
2674 binOp = spv::OpFOrdLessThan;
2675 else if (isUnsigned)
2676 binOp = spv::OpULessThan;
2677 else
2678 binOp = spv::OpSLessThan;
2679 break;
2680 case glslang::EOpGreaterThan:
2681 if (isFloat)
2682 binOp = spv::OpFOrdGreaterThan;
2683 else if (isUnsigned)
2684 binOp = spv::OpUGreaterThan;
2685 else
2686 binOp = spv::OpSGreaterThan;
2687 break;
2688 case glslang::EOpLessThanEqual:
2689 if (isFloat)
2690 binOp = spv::OpFOrdLessThanEqual;
2691 else if (isUnsigned)
2692 binOp = spv::OpULessThanEqual;
2693 else
2694 binOp = spv::OpSLessThanEqual;
2695 break;
2696 case glslang::EOpGreaterThanEqual:
2697 if (isFloat)
2698 binOp = spv::OpFOrdGreaterThanEqual;
2699 else if (isUnsigned)
2700 binOp = spv::OpUGreaterThanEqual;
2701 else
2702 binOp = spv::OpSGreaterThanEqual;
2703 break;
2704 case glslang::EOpEqual:
2705 case glslang::EOpVectorEqual:
2706 if (isFloat)
2707 binOp = spv::OpFOrdEqual;
2708 else
2709 binOp = spv::OpIEqual;
2710 break;
2711 case glslang::EOpNotEqual:
2712 case glslang::EOpVectorNotEqual:
2713 if (isFloat)
2714 binOp = spv::OpFOrdNotEqual;
2715 else
2716 binOp = spv::OpINotEqual;
2717 break;
2718 default:
2719 break;
2720 }
2721
John Kessenich32cfd492016-02-02 12:37:46 -07002722 if (binOp != spv::OpNop)
2723 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002724
2725 return 0;
2726}
2727
John Kessenich04bb8a02015-12-12 12:28:14 -07002728//
2729// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2730// These can be any of:
2731//
2732// matrix * scalar
2733// scalar * matrix
2734// matrix * matrix linear algebraic
2735// matrix * vector
2736// vector * matrix
2737// matrix * matrix componentwise
2738// matrix op matrix op in {+, -, /}
2739// matrix op scalar op in {+, -, /}
2740// scalar op matrix op in {+, -, /}
2741//
2742spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2743{
2744 bool firstClass = true;
2745
2746 // First, handle first-class matrix operations (* and matrix/scalar)
2747 switch (op) {
2748 case spv::OpFDiv:
2749 if (builder.isMatrix(left) && builder.isScalar(right)) {
2750 // turn matrix / scalar into a multiply...
2751 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2752 op = spv::OpMatrixTimesScalar;
2753 } else
2754 firstClass = false;
2755 break;
2756 case spv::OpMatrixTimesScalar:
2757 if (builder.isMatrix(right))
2758 std::swap(left, right);
2759 assert(builder.isScalar(right));
2760 break;
2761 case spv::OpVectorTimesMatrix:
2762 assert(builder.isVector(left));
2763 assert(builder.isMatrix(right));
2764 break;
2765 case spv::OpMatrixTimesVector:
2766 assert(builder.isMatrix(left));
2767 assert(builder.isVector(right));
2768 break;
2769 case spv::OpMatrixTimesMatrix:
2770 assert(builder.isMatrix(left));
2771 assert(builder.isMatrix(right));
2772 break;
2773 default:
2774 firstClass = false;
2775 break;
2776 }
2777
John Kessenich32cfd492016-02-02 12:37:46 -07002778 if (firstClass)
2779 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002780
2781 // Handle component-wise +, -, *, and / for all combinations of type.
2782 // The result type of all of them is the same type as the (a) matrix operand.
2783 // The algorithm is to:
2784 // - break the matrix(es) into vectors
2785 // - smear any scalar to a vector
2786 // - do vector operations
2787 // - make a matrix out the vector results
2788 switch (op) {
2789 case spv::OpFAdd:
2790 case spv::OpFSub:
2791 case spv::OpFDiv:
2792 case spv::OpFMul:
2793 {
2794 // one time set up...
2795 bool leftMat = builder.isMatrix(left);
2796 bool rightMat = builder.isMatrix(right);
2797 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2798 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2799 spv::Id scalarType = builder.getScalarTypeId(typeId);
2800 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2801 std::vector<spv::Id> results;
2802 spv::Id smearVec = spv::NoResult;
2803 if (builder.isScalar(left))
2804 smearVec = builder.smearScalar(precision, left, vecType);
2805 else if (builder.isScalar(right))
2806 smearVec = builder.smearScalar(precision, right, vecType);
2807
2808 // do each vector op
2809 for (unsigned int c = 0; c < numCols; ++c) {
2810 std::vector<unsigned int> indexes;
2811 indexes.push_back(c);
2812 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2813 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2814 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2815 builder.setPrecision(results.back(), precision);
2816 }
2817
2818 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002819 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002820 }
2821 default:
2822 assert(0);
2823 return spv::NoResult;
2824 }
2825}
2826
Rex Xu04db3f52015-09-16 11:44:02 +08002827spv::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 -06002828{
2829 spv::Op unaryOp = spv::OpNop;
2830 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002831 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002832 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002833
2834 switch (op) {
2835 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002836 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002837 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002838 if (builder.isMatrixType(typeId))
2839 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2840 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002841 unaryOp = spv::OpSNegate;
2842 break;
2843
2844 case glslang::EOpLogicalNot:
2845 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002846 unaryOp = spv::OpLogicalNot;
2847 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002848 case glslang::EOpBitwiseNot:
2849 unaryOp = spv::OpNot;
2850 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002851
John Kessenich140f3df2015-06-26 16:58:36 -06002852 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002853 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002854 break;
2855 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002856 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002857 break;
2858 case glslang::EOpTranspose:
2859 unaryOp = spv::OpTranspose;
2860 break;
2861
2862 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002863 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002864 break;
2865 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002866 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002867 break;
2868 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002869 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002870 break;
2871 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002872 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002873 break;
2874 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002875 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002876 break;
2877 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002878 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002879 break;
2880 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002881 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002882 break;
2883 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002884 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002885 break;
2886
2887 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002888 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002889 break;
2890 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002891 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002892 break;
2893 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002894 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002895 break;
2896 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002897 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002898 break;
2899 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002900 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002901 break;
2902 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002903 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002904 break;
2905
2906 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002907 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002908 break;
2909 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002910 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002911 break;
2912
2913 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002914 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002915 break;
2916 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002917 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002918 break;
2919 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002920 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002921 break;
2922 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002923 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002924 break;
2925 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002926 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002927 break;
2928 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002929 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002930 break;
2931
2932 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002933 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002934 break;
2935 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002936 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002937 break;
2938 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002939 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002940 break;
2941 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002942 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002943 break;
2944 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002945 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002946 break;
2947 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002948 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002949 break;
2950
2951 case glslang::EOpIsNan:
2952 unaryOp = spv::OpIsNan;
2953 break;
2954 case glslang::EOpIsInf:
2955 unaryOp = spv::OpIsInf;
2956 break;
2957
Rex Xucbc426e2015-12-15 16:03:10 +08002958 case glslang::EOpFloatBitsToInt:
2959 case glslang::EOpFloatBitsToUint:
2960 case glslang::EOpIntBitsToFloat:
2961 case glslang::EOpUintBitsToFloat:
2962 unaryOp = spv::OpBitcast;
2963 break;
2964
John Kessenich140f3df2015-06-26 16:58:36 -06002965 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002966 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002967 break;
2968 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002969 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002970 break;
2971 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002972 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002973 break;
2974 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002975 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002976 break;
2977 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002978 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002979 break;
2980 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002981 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002982 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002983 case glslang::EOpPackSnorm4x8:
2984 libCall = spv::GLSLstd450PackSnorm4x8;
2985 break;
2986 case glslang::EOpUnpackSnorm4x8:
2987 libCall = spv::GLSLstd450UnpackSnorm4x8;
2988 break;
2989 case glslang::EOpPackUnorm4x8:
2990 libCall = spv::GLSLstd450PackUnorm4x8;
2991 break;
2992 case glslang::EOpUnpackUnorm4x8:
2993 libCall = spv::GLSLstd450UnpackUnorm4x8;
2994 break;
2995 case glslang::EOpPackDouble2x32:
2996 libCall = spv::GLSLstd450PackDouble2x32;
2997 break;
2998 case glslang::EOpUnpackDouble2x32:
2999 libCall = spv::GLSLstd450UnpackDouble2x32;
3000 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003001
3002 case glslang::EOpDPdx:
3003 unaryOp = spv::OpDPdx;
3004 break;
3005 case glslang::EOpDPdy:
3006 unaryOp = spv::OpDPdy;
3007 break;
3008 case glslang::EOpFwidth:
3009 unaryOp = spv::OpFwidth;
3010 break;
3011 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003012 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003013 unaryOp = spv::OpDPdxFine;
3014 break;
3015 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003016 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003017 unaryOp = spv::OpDPdyFine;
3018 break;
3019 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003020 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003021 unaryOp = spv::OpFwidthFine;
3022 break;
3023 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003024 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003025 unaryOp = spv::OpDPdxCoarse;
3026 break;
3027 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003028 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003029 unaryOp = spv::OpDPdyCoarse;
3030 break;
3031 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003032 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003033 unaryOp = spv::OpFwidthCoarse;
3034 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003035 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003036 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003037 libCall = spv::GLSLstd450InterpolateAtCentroid;
3038 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 case glslang::EOpAny:
3040 unaryOp = spv::OpAny;
3041 break;
3042 case glslang::EOpAll:
3043 unaryOp = spv::OpAll;
3044 break;
3045
3046 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 if (isFloat)
3048 libCall = spv::GLSLstd450FAbs;
3049 else
3050 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 break;
3052 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003053 if (isFloat)
3054 libCall = spv::GLSLstd450FSign;
3055 else
3056 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003057 break;
3058
John Kessenichfc51d282015-08-19 13:34:18 -06003059 case glslang::EOpAtomicCounterIncrement:
3060 case glslang::EOpAtomicCounterDecrement:
3061 case glslang::EOpAtomicCounter:
3062 {
3063 // Handle all of the atomics in one place, in createAtomicOperation()
3064 std::vector<spv::Id> operands;
3065 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003066 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003067 }
3068
John Kessenichfc51d282015-08-19 13:34:18 -06003069 case glslang::EOpBitFieldReverse:
3070 unaryOp = spv::OpBitReverse;
3071 break;
3072 case glslang::EOpBitCount:
3073 unaryOp = spv::OpBitCount;
3074 break;
3075 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003076 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003077 break;
3078 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003079 if (isUnsigned)
3080 libCall = spv::GLSLstd450FindUMsb;
3081 else
3082 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003083 break;
3084
John Kessenich140f3df2015-06-26 16:58:36 -06003085 default:
3086 return 0;
3087 }
3088
3089 spv::Id id;
3090 if (libCall >= 0) {
3091 std::vector<spv::Id> args;
3092 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003093 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003094 } else
3095 id = builder.createUnaryOp(unaryOp, typeId, operand);
3096
John Kessenich32cfd492016-02-02 12:37:46 -07003097 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003098}
3099
John Kessenich7a53f762016-01-20 11:19:27 -07003100// Create a unary operation on a matrix
3101spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3102{
3103 // Handle unary operations vector by vector.
3104 // The result type is the same type as the original type.
3105 // The algorithm is to:
3106 // - break the matrix into vectors
3107 // - apply the operation to each vector
3108 // - make a matrix out the vector results
3109
3110 // get the types sorted out
3111 int numCols = builder.getNumColumns(operand);
3112 int numRows = builder.getNumRows(operand);
3113 spv::Id scalarType = builder.getScalarTypeId(typeId);
3114 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3115 std::vector<spv::Id> results;
3116
3117 // do each vector op
3118 for (int c = 0; c < numCols; ++c) {
3119 std::vector<unsigned int> indexes;
3120 indexes.push_back(c);
3121 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3122 results.push_back(builder.createUnaryOp(op, vecType, vec));
3123 builder.setPrecision(results.back(), precision);
3124 }
3125
3126 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003127 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003128}
3129
John Kessenich140f3df2015-06-26 16:58:36 -06003130spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3131{
3132 spv::Op convOp = spv::OpNop;
3133 spv::Id zero = 0;
3134 spv::Id one = 0;
3135
3136 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3137
3138 switch (op) {
3139 case glslang::EOpConvIntToBool:
3140 case glslang::EOpConvUintToBool:
3141 zero = builder.makeUintConstant(0);
3142 zero = makeSmearedConstant(zero, vectorSize);
3143 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3144
3145 case glslang::EOpConvFloatToBool:
3146 zero = builder.makeFloatConstant(0.0F);
3147 zero = makeSmearedConstant(zero, vectorSize);
3148 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3149
3150 case glslang::EOpConvDoubleToBool:
3151 zero = builder.makeDoubleConstant(0.0);
3152 zero = makeSmearedConstant(zero, vectorSize);
3153 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3154
3155 case glslang::EOpConvBoolToFloat:
3156 convOp = spv::OpSelect;
3157 zero = builder.makeFloatConstant(0.0);
3158 one = builder.makeFloatConstant(1.0);
3159 break;
3160 case glslang::EOpConvBoolToDouble:
3161 convOp = spv::OpSelect;
3162 zero = builder.makeDoubleConstant(0.0);
3163 one = builder.makeDoubleConstant(1.0);
3164 break;
3165 case glslang::EOpConvBoolToInt:
3166 zero = builder.makeIntConstant(0);
3167 one = builder.makeIntConstant(1);
3168 convOp = spv::OpSelect;
3169 break;
3170 case glslang::EOpConvBoolToUint:
3171 zero = builder.makeUintConstant(0);
3172 one = builder.makeUintConstant(1);
3173 convOp = spv::OpSelect;
3174 break;
3175
3176 case glslang::EOpConvIntToFloat:
3177 case glslang::EOpConvIntToDouble:
3178 convOp = spv::OpConvertSToF;
3179 break;
3180
3181 case glslang::EOpConvUintToFloat:
3182 case glslang::EOpConvUintToDouble:
3183 convOp = spv::OpConvertUToF;
3184 break;
3185
3186 case glslang::EOpConvDoubleToFloat:
3187 case glslang::EOpConvFloatToDouble:
3188 convOp = spv::OpFConvert;
3189 break;
3190
3191 case glslang::EOpConvFloatToInt:
3192 case glslang::EOpConvDoubleToInt:
3193 convOp = spv::OpConvertFToS;
3194 break;
3195
3196 case glslang::EOpConvUintToInt:
3197 case glslang::EOpConvIntToUint:
3198 convOp = spv::OpBitcast;
3199 break;
3200
3201 case glslang::EOpConvFloatToUint:
3202 case glslang::EOpConvDoubleToUint:
3203 convOp = spv::OpConvertFToU;
3204 break;
3205 default:
3206 break;
3207 }
3208
3209 spv::Id result = 0;
3210 if (convOp == spv::OpNop)
3211 return result;
3212
3213 if (convOp == spv::OpSelect) {
3214 zero = makeSmearedConstant(zero, vectorSize);
3215 one = makeSmearedConstant(one, vectorSize);
3216 result = builder.createTriOp(convOp, destType, operand, one, zero);
3217 } else
3218 result = builder.createUnaryOp(convOp, destType, operand);
3219
John Kessenich32cfd492016-02-02 12:37:46 -07003220 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003221}
3222
3223spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3224{
3225 if (vectorSize == 0)
3226 return constant;
3227
3228 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3229 std::vector<spv::Id> components;
3230 for (int c = 0; c < vectorSize; ++c)
3231 components.push_back(constant);
3232 return builder.makeCompositeConstant(vectorTypeId, components);
3233}
3234
John Kessenich426394d2015-07-23 10:22:48 -06003235// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003236spv::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 -06003237{
3238 spv::Op opCode = spv::OpNop;
3239
3240 switch (op) {
3241 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003242 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003243 opCode = spv::OpAtomicIAdd;
3244 break;
3245 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003246 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003247 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003248 break;
3249 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003250 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003251 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003252 break;
3253 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003254 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003255 opCode = spv::OpAtomicAnd;
3256 break;
3257 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003258 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003259 opCode = spv::OpAtomicOr;
3260 break;
3261 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003262 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003263 opCode = spv::OpAtomicXor;
3264 break;
3265 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003266 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003267 opCode = spv::OpAtomicExchange;
3268 break;
3269 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003270 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003271 opCode = spv::OpAtomicCompareExchange;
3272 break;
3273 case glslang::EOpAtomicCounterIncrement:
3274 opCode = spv::OpAtomicIIncrement;
3275 break;
3276 case glslang::EOpAtomicCounterDecrement:
3277 opCode = spv::OpAtomicIDecrement;
3278 break;
3279 case glslang::EOpAtomicCounter:
3280 opCode = spv::OpAtomicLoad;
3281 break;
3282 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003283 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003284 break;
3285 }
3286
3287 // Sort out the operands
3288 // - mapping from glslang -> SPV
3289 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003290 // - compare-exchange swaps the value and comparator
3291 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003292 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3293 auto opIt = operands.begin(); // walk the glslang operands
3294 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003295 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3296 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3297 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003298 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3299 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003300 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003301 spvAtomicOperands.push_back(*(opIt + 1));
3302 spvAtomicOperands.push_back(*opIt);
3303 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003304 }
John Kessenich426394d2015-07-23 10:22:48 -06003305
John Kessenich3e60a6f2015-09-14 22:45:16 -06003306 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003307 for (; opIt != operands.end(); ++opIt)
3308 spvAtomicOperands.push_back(*opIt);
3309
3310 return builder.createOp(opCode, typeId, spvAtomicOperands);
3311}
3312
John Kessenich5e4b1242015-08-06 22:53:06 -06003313spv::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 -06003314{
John Kessenich5e4b1242015-08-06 22:53:06 -06003315 bool isUnsigned = typeProxy == glslang::EbtUint;
3316 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3317
John Kessenich140f3df2015-06-26 16:58:36 -06003318 spv::Op opCode = spv::OpNop;
3319 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003320 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003321 spv::Id typeId0 = 0;
3322 if (consumedOperands > 0)
3323 typeId0 = builder.getTypeId(operands[0]);
3324 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003325
3326 switch (op) {
3327 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003328 if (isFloat)
3329 libCall = spv::GLSLstd450FMin;
3330 else if (isUnsigned)
3331 libCall = spv::GLSLstd450UMin;
3332 else
3333 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003334 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003335 break;
3336 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003337 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003338 break;
3339 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003340 if (isFloat)
3341 libCall = spv::GLSLstd450FMax;
3342 else if (isUnsigned)
3343 libCall = spv::GLSLstd450UMax;
3344 else
3345 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003346 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003347 break;
3348 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003349 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003350 break;
3351 case glslang::EOpDot:
3352 opCode = spv::OpDot;
3353 break;
3354 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003355 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003356 break;
3357
3358 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003359 if (isFloat)
3360 libCall = spv::GLSLstd450FClamp;
3361 else if (isUnsigned)
3362 libCall = spv::GLSLstd450UClamp;
3363 else
3364 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003365 builder.promoteScalar(precision, operands.front(), operands[1]);
3366 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003367 break;
3368 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003369 if (isFloat)
3370 libCall = spv::GLSLstd450FMix;
John Kessenich6c292d32016-02-15 20:58:50 -07003371 else {
3372 opCode = spv::OpSelect;
3373 spv::MissingFunctionality("translating integer mix to OpSelect");
3374 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003375 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003376 break;
3377 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003378 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003379 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003380 break;
3381 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003382 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003383 builder.promoteScalar(precision, operands[0], operands[2]);
3384 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003385 break;
3386
3387 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003388 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003389 break;
3390 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003391 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003392 break;
3393 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003394 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003395 break;
3396 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003397 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003398 break;
3399 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003400 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003401 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003402 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003403 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003404 libCall = spv::GLSLstd450InterpolateAtSample;
3405 break;
3406 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003407 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003408 libCall = spv::GLSLstd450InterpolateAtOffset;
3409 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003410 case glslang::EOpAddCarry:
3411 opCode = spv::OpIAddCarry;
3412 typeId = builder.makeStructResultType(typeId0, typeId0);
3413 consumedOperands = 2;
3414 break;
3415 case glslang::EOpSubBorrow:
3416 opCode = spv::OpISubBorrow;
3417 typeId = builder.makeStructResultType(typeId0, typeId0);
3418 consumedOperands = 2;
3419 break;
3420 case glslang::EOpUMulExtended:
3421 opCode = spv::OpUMulExtended;
3422 typeId = builder.makeStructResultType(typeId0, typeId0);
3423 consumedOperands = 2;
3424 break;
3425 case glslang::EOpIMulExtended:
3426 opCode = spv::OpSMulExtended;
3427 typeId = builder.makeStructResultType(typeId0, typeId0);
3428 consumedOperands = 2;
3429 break;
3430 case glslang::EOpBitfieldExtract:
3431 if (isUnsigned)
3432 opCode = spv::OpBitFieldUExtract;
3433 else
3434 opCode = spv::OpBitFieldSExtract;
3435 break;
3436 case glslang::EOpBitfieldInsert:
3437 opCode = spv::OpBitFieldInsert;
3438 break;
3439
3440 case glslang::EOpFma:
3441 libCall = spv::GLSLstd450Fma;
3442 break;
3443 case glslang::EOpFrexp:
3444 libCall = spv::GLSLstd450FrexpStruct;
3445 if (builder.getNumComponents(operands[0]) == 1)
3446 frexpIntType = builder.makeIntegerType(32, true);
3447 else
3448 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3449 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3450 consumedOperands = 1;
3451 break;
3452 case glslang::EOpLdexp:
3453 libCall = spv::GLSLstd450Ldexp;
3454 break;
3455
John Kessenich140f3df2015-06-26 16:58:36 -06003456 default:
3457 return 0;
3458 }
3459
3460 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003461 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003462 // Use an extended instruction from the standard library.
3463 // Construct the call arguments, without modifying the original operands vector.
3464 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3465 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003466 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003467 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003468 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003469 case 0:
3470 // should all be handled by visitAggregate and createNoArgOperation
3471 assert(0);
3472 return 0;
3473 case 1:
3474 // should all be handled by createUnaryOperation
3475 assert(0);
3476 return 0;
3477 case 2:
3478 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3479 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003480 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003481 // anything 3 or over doesn't have l-value operands, so all should be consumed
3482 assert(consumedOperands == operands.size());
3483 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003484 break;
3485 }
3486 }
3487
John Kessenich55e7d112015-11-15 21:33:39 -07003488 // Decode the return types that were structures
3489 switch (op) {
3490 case glslang::EOpAddCarry:
3491 case glslang::EOpSubBorrow:
3492 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3493 id = builder.createCompositeExtract(id, typeId0, 0);
3494 break;
3495 case glslang::EOpUMulExtended:
3496 case glslang::EOpIMulExtended:
3497 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3498 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3499 break;
3500 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003501 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003502 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3503 id = builder.createCompositeExtract(id, typeId0, 0);
3504 break;
3505 default:
3506 break;
3507 }
3508
John Kessenich32cfd492016-02-02 12:37:46 -07003509 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003510}
3511
3512// Intrinsics with no arguments, no return value, and no precision.
3513spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3514{
3515 // TODO: get the barrier operands correct
3516
3517 switch (op) {
3518 case glslang::EOpEmitVertex:
3519 builder.createNoResultOp(spv::OpEmitVertex);
3520 return 0;
3521 case glslang::EOpEndPrimitive:
3522 builder.createNoResultOp(spv::OpEndPrimitive);
3523 return 0;
3524 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003525 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3526 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003527 return 0;
3528 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003529 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003530 return 0;
3531 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003532 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003533 return 0;
3534 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003535 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003536 return 0;
3537 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003538 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003539 return 0;
3540 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003541 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003542 return 0;
3543 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003544 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003545 return 0;
3546 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003547 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003548 return 0;
3549 }
3550}
3551
3552spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3553{
John Kessenich2f273362015-07-18 22:34:27 -06003554 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003555 spv::Id id;
3556 if (symbolValues.end() != iter) {
3557 id = iter->second;
3558 return id;
3559 }
3560
3561 // it was not found, create it
3562 id = createSpvVariable(symbol);
3563 symbolValues[symbol->getId()] = id;
3564
3565 if (! symbol->getType().isStruct()) {
3566 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003567 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003568 if (symbol->getType().getQualifier().hasSpecConstantId())
3569 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003570 if (symbol->getQualifier().hasLocation())
3571 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3572 if (symbol->getQualifier().hasIndex())
3573 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3574 if (symbol->getQualifier().hasComponent())
3575 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3576 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003577 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003578 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003579 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003580 if (symbol->getQualifier().hasXfbBuffer())
3581 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3582 if (symbol->getQualifier().hasXfbOffset())
3583 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3584 }
3585 }
3586
John Kesseniche0b6cad2015-12-24 10:30:13 -07003587 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003588 if (symbol->getQualifier().hasStream()) {
3589 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003590 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003591 }
John Kessenich140f3df2015-06-26 16:58:36 -06003592 if (symbol->getQualifier().hasSet())
3593 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003594 else if (IsDescriptorResource(symbol->getType())) {
3595 // default to 0
3596 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3597 }
John Kessenich140f3df2015-06-26 16:58:36 -06003598 if (symbol->getQualifier().hasBinding())
3599 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003600 if (symbol->getQualifier().hasAttachment())
3601 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003602 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003603 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003604 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003605 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003606 if (symbol->getQualifier().hasXfbBuffer())
3607 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3608 }
3609
Rex Xu1da878f2016-02-21 20:59:01 +08003610 if (symbol->getType().isImage()) {
3611 std::vector<spv::Decoration> memory;
3612 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3613 for (unsigned int i = 0; i < memory.size(); ++i)
3614 addDecoration(id, memory[i]);
3615 }
3616
John Kessenich140f3df2015-06-26 16:58:36 -06003617 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003618 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003619 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003620 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003621
John Kessenich140f3df2015-06-26 16:58:36 -06003622 return id;
3623}
3624
John Kessenich55e7d112015-11-15 21:33:39 -07003625// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003626void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3627{
3628 if (dec != spv::BadValue)
3629 builder.addDecoration(id, dec);
3630}
3631
John Kessenich55e7d112015-11-15 21:33:39 -07003632// If 'dec' is valid, add a one-operand decoration to an object
3633void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3634{
3635 if (dec != spv::BadValue)
3636 builder.addDecoration(id, dec, value);
3637}
3638
3639// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003640void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3641{
3642 if (dec != spv::BadValue)
3643 builder.addMemberDecoration(id, (unsigned)member, dec);
3644}
3645
John Kessenich92187592016-02-01 13:45:25 -07003646// If 'dec' is valid, add a one-operand decoration to a struct member
3647void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3648{
3649 if (dec != spv::BadValue)
3650 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3651}
3652
John Kessenich55e7d112015-11-15 21:33:39 -07003653// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003654// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003655//
3656// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3657//
3658// Recursively walk the nodes. The nodes form a tree whose leaves are
3659// regular constants, which themselves are trees that createSpvConstant()
3660// recursively walks. So, this function walks the "top" of the tree:
3661// - emit specialization constant-building instructions for specConstant
3662// - when running into a non-spec-constant, switch to createSpvConstant()
3663spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3664{
3665 assert(node.getQualifier().storage == glslang::EvqConst);
3666
John Kessenich6c292d32016-02-15 20:58:50 -07003667 if (! node.getQualifier().specConstant) {
3668 // hand off to the non-spec-constant path
3669 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3670 int nextConst = 0;
3671 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3672 nextConst, false);
3673 }
3674
3675 // We now know we have a specialization constant to build
3676
3677 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3678 // this is a direct literal assigned to a layout(constant_id=) declaration
3679 int nextConst = 0;
3680 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3681 nextConst, true);
3682 } else {
3683 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3684 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3685 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3686 std::vector<spv::Id> dimConstId;
3687 for (int dim = 0; dim < 3; ++dim) {
3688 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3689 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3690 if (specConst)
3691 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3692 }
3693 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3694 } else {
3695 spv::MissingFunctionality("specialization-constant expression trees");
3696 return spv::NoResult;
3697 }
3698 }
John Kessenich55e7d112015-11-15 21:33:39 -07003699}
3700
John Kessenich140f3df2015-06-26 16:58:36 -06003701// Use 'consts' as the flattened glslang source of scalar constants to recursively
3702// build the aggregate SPIR-V constant.
3703//
3704// If there are not enough elements present in 'consts', 0 will be substituted;
3705// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3706//
John Kessenich55e7d112015-11-15 21:33:39 -07003707spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003708{
3709 // vector of constants for SPIR-V
3710 std::vector<spv::Id> spvConsts;
3711
3712 // Type is used for struct and array constants
3713 spv::Id typeId = convertGlslangToSpvType(glslangType);
3714
3715 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003716 glslang::TType elementType(glslangType, 0);
3717 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003718 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003719 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003720 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003721 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003722 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003723 } else if (glslangType.getStruct()) {
3724 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3725 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003726 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003727 } else if (glslangType.isVector()) {
3728 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3729 bool zero = nextConst >= consts.size();
3730 switch (glslangType.getBasicType()) {
3731 case glslang::EbtInt:
3732 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3733 break;
3734 case glslang::EbtUint:
3735 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3736 break;
3737 case glslang::EbtFloat:
3738 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3739 break;
3740 case glslang::EbtDouble:
3741 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3742 break;
3743 case glslang::EbtBool:
3744 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3745 break;
3746 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003747 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003748 break;
3749 }
3750 ++nextConst;
3751 }
3752 } else {
3753 // we have a non-aggregate (scalar) constant
3754 bool zero = nextConst >= consts.size();
3755 spv::Id scalar = 0;
3756 switch (glslangType.getBasicType()) {
3757 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003758 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003759 break;
3760 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003761 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003764 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003765 break;
3766 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003767 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003768 break;
3769 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003770 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003771 break;
3772 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003773 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003774 break;
3775 }
3776 ++nextConst;
3777 return scalar;
3778 }
3779
3780 return builder.makeCompositeConstant(typeId, spvConsts);
3781}
3782
John Kessenich7c1aa102015-10-15 13:29:11 -06003783// Return true if the node is a constant or symbol whose reading has no
3784// non-trivial observable cost or effect.
3785bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3786{
3787 // don't know what this is
3788 if (node == nullptr)
3789 return false;
3790
3791 // a constant is safe
3792 if (node->getAsConstantUnion() != nullptr)
3793 return true;
3794
3795 // not a symbol means non-trivial
3796 if (node->getAsSymbolNode() == nullptr)
3797 return false;
3798
3799 // a symbol, depends on what's being read
3800 switch (node->getType().getQualifier().storage) {
3801 case glslang::EvqTemporary:
3802 case glslang::EvqGlobal:
3803 case glslang::EvqIn:
3804 case glslang::EvqInOut:
3805 case glslang::EvqConst:
3806 case glslang::EvqConstReadOnly:
3807 case glslang::EvqUniform:
3808 return true;
3809 default:
3810 return false;
3811 }
3812}
3813
3814// A node is trivial if it is a single operation with no side effects.
3815// Error on the side of saying non-trivial.
3816// Return true if trivial.
3817bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3818{
3819 if (node == nullptr)
3820 return false;
3821
3822 // symbols and constants are trivial
3823 if (isTrivialLeaf(node))
3824 return true;
3825
3826 // otherwise, it needs to be a simple operation or one or two leaf nodes
3827
3828 // not a simple operation
3829 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3830 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3831 if (binaryNode == nullptr && unaryNode == nullptr)
3832 return false;
3833
3834 // not on leaf nodes
3835 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3836 return false;
3837
3838 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3839 return false;
3840 }
3841
3842 switch (node->getAsOperator()->getOp()) {
3843 case glslang::EOpLogicalNot:
3844 case glslang::EOpConvIntToBool:
3845 case glslang::EOpConvUintToBool:
3846 case glslang::EOpConvFloatToBool:
3847 case glslang::EOpConvDoubleToBool:
3848 case glslang::EOpEqual:
3849 case glslang::EOpNotEqual:
3850 case glslang::EOpLessThan:
3851 case glslang::EOpGreaterThan:
3852 case glslang::EOpLessThanEqual:
3853 case glslang::EOpGreaterThanEqual:
3854 case glslang::EOpIndexDirect:
3855 case glslang::EOpIndexDirectStruct:
3856 case glslang::EOpLogicalXor:
3857 case glslang::EOpAny:
3858 case glslang::EOpAll:
3859 return true;
3860 default:
3861 return false;
3862 }
3863}
3864
3865// Emit short-circuiting code, where 'right' is never evaluated unless
3866// the left side is true (for &&) or false (for ||).
3867spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3868{
3869 spv::Id boolTypeId = builder.makeBoolType();
3870
3871 // emit left operand
3872 builder.clearAccessChain();
3873 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003874 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003875
3876 // Operands to accumulate OpPhi operands
3877 std::vector<spv::Id> phiOperands;
3878 // accumulate left operand's phi information
3879 phiOperands.push_back(leftId);
3880 phiOperands.push_back(builder.getBuildPoint()->getId());
3881
3882 // Make the two kinds of operation symmetric with a "!"
3883 // || => emit "if (! left) result = right"
3884 // && => emit "if ( left) result = right"
3885 //
3886 // TODO: this runtime "not" for || could be avoided by adding functionality
3887 // to 'builder' to have an "else" without an "then"
3888 if (op == glslang::EOpLogicalOr)
3889 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3890
3891 // make an "if" based on the left value
3892 spv::Builder::If ifBuilder(leftId, builder);
3893
3894 // emit right operand as the "then" part of the "if"
3895 builder.clearAccessChain();
3896 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003897 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003898
3899 // accumulate left operand's phi information
3900 phiOperands.push_back(rightId);
3901 phiOperands.push_back(builder.getBuildPoint()->getId());
3902
3903 // finish the "if"
3904 ifBuilder.makeEndIf();
3905
3906 // phi together the two results
3907 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3908}
3909
John Kessenich140f3df2015-06-26 16:58:36 -06003910}; // end anonymous namespace
3911
3912namespace glslang {
3913
John Kessenich68d78fd2015-07-12 19:28:10 -06003914void GetSpirvVersion(std::string& version)
3915{
John Kessenich9e55f632015-07-15 10:03:39 -06003916 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003917 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003918 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003919 version = buf;
3920}
3921
John Kessenich140f3df2015-06-26 16:58:36 -06003922// Write SPIR-V out to a binary file
3923void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3924{
3925 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003926 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003927 for (int i = 0; i < (int)spirv.size(); ++i) {
3928 unsigned int word = spirv[i];
3929 out.write((const char*)&word, 4);
3930 }
3931 out.close();
3932}
3933
3934//
3935// Set up the glslang traversal
3936//
3937void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3938{
3939 TIntermNode* root = intermediate.getTreeRoot();
3940
3941 if (root == 0)
3942 return;
3943
3944 glslang::GetThreadPoolAllocator().push();
3945
3946 TGlslangToSpvTraverser it(&intermediate);
3947
3948 root->traverse(&it);
3949
3950 it.dumpSpv(spirv);
3951
3952 glslang::GetThreadPoolAllocator().pop();
3953}
3954
3955}; // end namespace glslang