blob: b837a25d9371ee9e9d51846ab82e31272a944ec2 [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);
Rex Xu27253232016-02-23 17:51:09 +0800101 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700102 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700103 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
104 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
105 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 -0600106
107 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
108 void makeFunctions(const glslang::TIntermSequence&);
109 void makeGlobalInitializers(const glslang::TIntermSequence&);
110 void visitFunctions(const glslang::TIntermSequence&);
111 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800112 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600113 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
114 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600115 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
116
117 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 -0700118 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800119 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 -0700120 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600121 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
122 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800123 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 -0600124 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 -0600125 spv::Id createNoArgOperation(glslang::TOperator op);
126 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
127 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700128 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600129 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700130 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700131 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
132 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600133 bool isTrivialLeaf(const glslang::TIntermTyped* node);
134 bool isTrivial(const glslang::TIntermTyped* node);
135 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600136
137 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700138 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600139 int sequenceDepth;
140
141 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
142 spv::Builder builder;
143 bool inMain;
144 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700145 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 -0700146 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600147 const glslang::TIntermediate* glslangIntermediate;
148 spv::Id stdBuiltins;
149
John Kessenich2f273362015-07-18 22:34:27 -0600150 std::unordered_map<int, spv::Id> symbolValues;
151 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
152 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700153 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600154 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 -0600155 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600156};
157
158//
159// Helper functions for translating glslang representations to SPIR-V enumerants.
160//
161
162// Translate glslang profile to SPIR-V source language.
163spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
164{
165 switch (profile) {
166 case ENoProfile:
167 case ECoreProfile:
168 case ECompatibilityProfile:
169 return spv::SourceLanguageGLSL;
170 case EEsProfile:
171 return spv::SourceLanguageESSL;
172 default:
173 return spv::SourceLanguageUnknown;
174 }
175}
176
177// Translate glslang language (stage) to SPIR-V execution model.
178spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
179{
180 switch (stage) {
181 case EShLangVertex: return spv::ExecutionModelVertex;
182 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
183 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
184 case EShLangGeometry: return spv::ExecutionModelGeometry;
185 case EShLangFragment: return spv::ExecutionModelFragment;
186 case EShLangCompute: return spv::ExecutionModelGLCompute;
187 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700188 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 return spv::ExecutionModelFragment;
190 }
191}
192
193// Translate glslang type to SPIR-V storage class.
194spv::StorageClass TranslateStorageClass(const glslang::TType& type)
195{
196 if (type.getQualifier().isPipeInput())
197 return spv::StorageClassInput;
198 else if (type.getQualifier().isPipeOutput())
199 return spv::StorageClassOutput;
200 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700201 if (type.getQualifier().layoutPushConstant)
202 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600203 if (type.getBasicType() == glslang::EbtBlock)
204 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800205 else if (type.getBasicType() == glslang::EbtAtomicUint)
206 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600207 else
208 return spv::StorageClassUniformConstant;
209 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
210 } else {
211 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700212 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
213 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600214 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
215 case glslang::EvqTemporary: return spv::StorageClassFunction;
216 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700217 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600218 return spv::StorageClassFunction;
219 }
220 }
221}
222
223// Translate glslang sampler type to SPIR-V dimensionality.
224spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
225{
226 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700227 case glslang::Esd1D: return spv::Dim1D;
228 case glslang::Esd2D: return spv::Dim2D;
229 case glslang::Esd3D: return spv::Dim3D;
230 case glslang::EsdCube: return spv::DimCube;
231 case glslang::EsdRect: return spv::DimRect;
232 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700233 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700235 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600236 return spv::Dim2D;
237 }
238}
239
240// Translate glslang type to SPIR-V precision decorations.
241spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
242{
243 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700244 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600245 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600246 default:
247 return spv::NoPrecision;
248 }
249}
250
251// Translate glslang type to SPIR-V block decorations.
252spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
253{
254 if (type.getBasicType() == glslang::EbtBlock) {
255 switch (type.getQualifier().storage) {
256 case glslang::EvqUniform: return spv::DecorationBlock;
257 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
258 case glslang::EvqVaryingIn: return spv::DecorationBlock;
259 case glslang::EvqVaryingOut: return spv::DecorationBlock;
260 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700261 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600262 break;
263 }
264 }
265
266 return (spv::Decoration)spv::BadValue;
267}
268
Rex Xu1da878f2016-02-21 20:59:01 +0800269// Translate glslang type to SPIR-V memory decorations.
270void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
271{
272 if (qualifier.coherent)
273 memory.push_back(spv::DecorationCoherent);
274 if (qualifier.volatil)
275 memory.push_back(spv::DecorationVolatile);
276 if (qualifier.restrict)
277 memory.push_back(spv::DecorationRestrict);
278 if (qualifier.readonly)
279 memory.push_back(spv::DecorationNonWritable);
280 if (qualifier.writeonly)
281 memory.push_back(spv::DecorationNonReadable);
282}
283
John Kessenich140f3df2015-06-26 16:58:36 -0600284// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700285spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600286{
287 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700288 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600289 case glslang::ElmRowMajor:
290 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700291 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600292 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700293 default:
294 // opaque layouts don't need a majorness
295 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600296 }
297 } else {
298 switch (type.getBasicType()) {
299 default:
300 return (spv::Decoration)spv::BadValue;
301 break;
302 case glslang::EbtBlock:
303 switch (type.getQualifier().storage) {
304 case glslang::EvqUniform:
305 case glslang::EvqBuffer:
306 switch (type.getQualifier().layoutPacking) {
307 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600308 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
309 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600310 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600311 }
312 case glslang::EvqVaryingIn:
313 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700314 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600315 return (spv::Decoration)spv::BadValue;
316 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700317 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600318 return (spv::Decoration)spv::BadValue;
319 }
320 }
321 }
322}
323
324// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700325// Returns spv::Decoration(spv::BadValue) when no decoration
326// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700327spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600328{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700329 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700330 // Smooth decoration doesn't exist in SPIR-V 1.0
331 return (spv::Decoration)spv::BadValue;
332 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700333 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700334 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700335 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600336 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700337 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600338 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700339 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600340 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700341 else if (qualifier.sample) {
342 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600343 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700344 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return (spv::Decoration)spv::BadValue;
346}
347
John Kessenich92187592016-02-01 13:45:25 -0700348// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700349spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600350{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700351 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600352 return spv::DecorationInvariant;
353 else
354 return (spv::Decoration)spv::BadValue;
355}
356
357// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700358spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600359{
360 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700361 case glslang::EbvPointSize:
362 switch (glslangIntermediate->getStage()) {
363 case EShLangGeometry:
364 builder.addCapability(spv::CapabilityGeometryPointSize);
365 break;
366 case EShLangTessControl:
367 case EShLangTessEvaluation:
368 builder.addCapability(spv::CapabilityTessellationPointSize);
369 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100370 default:
371 break;
John Kessenich92187592016-02-01 13:45:25 -0700372 }
373 return spv::BuiltInPointSize;
374
375 case glslang::EbvClipDistance:
376 builder.addCapability(spv::CapabilityClipDistance);
377 return spv::BuiltInClipDistance;
378
379 case glslang::EbvCullDistance:
380 builder.addCapability(spv::CapabilityCullDistance);
381 return spv::BuiltInCullDistance;
382
383 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500384 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700385 return spv::BuiltInViewportIndex;
386
John Kessenich5e801132016-02-15 11:09:46 -0700387 case glslang::EbvSampleId:
388 builder.addCapability(spv::CapabilitySampleRateShading);
389 return spv::BuiltInSampleId;
390
391 case glslang::EbvSamplePosition:
392 builder.addCapability(spv::CapabilitySampleRateShading);
393 return spv::BuiltInSamplePosition;
394
395 case glslang::EbvSampleMask:
396 builder.addCapability(spv::CapabilitySampleRateShading);
397 return spv::BuiltInSampleMask;
398
John Kessenich140f3df2015-06-26 16:58:36 -0600399 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600400 case glslang::EbvVertexId: return spv::BuiltInVertexId;
401 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700402 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
403 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600404 case glslang::EbvBaseVertex:
405 case glslang::EbvBaseInstance:
406 case glslang::EbvDrawId:
407 // TODO: Add SPIR-V builtin ID.
408 spv::MissingFunctionality("Draw parameters");
409 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600410 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
411 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
412 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600413 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
414 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
415 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
416 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
417 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
418 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
419 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600420 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
421 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
422 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
423 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
424 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
425 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
426 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
427 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
428 default: return (spv::BuiltIn)spv::BadValue;
429 }
430}
431
Rex Xufc618912015-09-09 16:42:49 +0800432// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700433spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800434{
435 assert(type.getBasicType() == glslang::EbtSampler);
436
John Kessenich5d0fa972016-02-15 11:57:00 -0700437 // Check for capabilities
438 switch (type.getQualifier().layoutFormat) {
439 case glslang::ElfRg32f:
440 case glslang::ElfRg16f:
441 case glslang::ElfR11fG11fB10f:
442 case glslang::ElfR16f:
443 case glslang::ElfRgba16:
444 case glslang::ElfRgb10A2:
445 case glslang::ElfRg16:
446 case glslang::ElfRg8:
447 case glslang::ElfR16:
448 case glslang::ElfR8:
449 case glslang::ElfRgba16Snorm:
450 case glslang::ElfRg16Snorm:
451 case glslang::ElfRg8Snorm:
452 case glslang::ElfR16Snorm:
453 case glslang::ElfR8Snorm:
454
455 case glslang::ElfRg32i:
456 case glslang::ElfRg16i:
457 case glslang::ElfRg8i:
458 case glslang::ElfR16i:
459 case glslang::ElfR8i:
460
461 case glslang::ElfRgb10a2ui:
462 case glslang::ElfRg32ui:
463 case glslang::ElfRg16ui:
464 case glslang::ElfRg8ui:
465 case glslang::ElfR16ui:
466 case glslang::ElfR8ui:
467 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
468 break;
469
470 default:
471 break;
472 }
473
474 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800475 switch (type.getQualifier().layoutFormat) {
476 case glslang::ElfNone: return spv::ImageFormatUnknown;
477 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
478 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
479 case glslang::ElfR32f: return spv::ImageFormatR32f;
480 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
481 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
482 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
483 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
484 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
485 case glslang::ElfR16f: return spv::ImageFormatR16f;
486 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
487 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
488 case glslang::ElfRg16: return spv::ImageFormatRg16;
489 case glslang::ElfRg8: return spv::ImageFormatRg8;
490 case glslang::ElfR16: return spv::ImageFormatR16;
491 case glslang::ElfR8: return spv::ImageFormatR8;
492 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
493 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
494 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
495 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
496 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
497 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
498 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
499 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
500 case glslang::ElfR32i: return spv::ImageFormatR32i;
501 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
502 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
503 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
504 case glslang::ElfR16i: return spv::ImageFormatR16i;
505 case glslang::ElfR8i: return spv::ImageFormatR8i;
506 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
507 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
508 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
509 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
510 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
511 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
512 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
513 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
514 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
515 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
516 default: return (spv::ImageFormat)spv::BadValue;
517 }
518}
519
John Kessenich6c292d32016-02-15 20:58:50 -0700520// Return whether or not the given type is something that should be tied to a
521// descriptor set.
522bool IsDescriptorResource(const glslang::TType& type)
523{
John Kessenichf7497e22016-03-08 21:36:22 -0700524 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700525 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700526 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700527
528 // non block...
529 // basically samplerXXX/subpass/sampler/texture are all included
530 // if they are the global-scope-class, not the function parameter
531 // (or local, if they ever exist) class.
532 if (type.getBasicType() == glslang::EbtSampler)
533 return type.getQualifier().isUniformOrBuffer();
534
535 // None of the above.
536 return false;
537}
538
John Kesseniche0b6cad2015-12-24 10:30:13 -0700539void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
540{
541 if (child.layoutMatrix == glslang::ElmNone)
542 child.layoutMatrix = parent.layoutMatrix;
543
544 if (parent.invariant)
545 child.invariant = true;
546 if (parent.nopersp)
547 child.nopersp = true;
548 if (parent.flat)
549 child.flat = true;
550 if (parent.centroid)
551 child.centroid = true;
552 if (parent.patch)
553 child.patch = true;
554 if (parent.sample)
555 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800556 if (parent.coherent)
557 child.coherent = true;
558 if (parent.volatil)
559 child.volatil = true;
560 if (parent.restrict)
561 child.restrict = true;
562 if (parent.readonly)
563 child.readonly = true;
564 if (parent.writeonly)
565 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700566}
567
568bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
569{
John Kessenich7b9fa252016-01-21 18:56:57 -0700570 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700571 // - struct members can inherit from a struct declaration
572 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
573 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700574 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700575}
576
John Kessenich140f3df2015-06-26 16:58:36 -0600577//
578// Implement the TGlslangToSpvTraverser class.
579//
580
581TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
582 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700583 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600584 inMain(false), mainTerminated(false), linkageOnly(false),
585 glslangIntermediate(glslangIntermediate)
586{
587 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
588
589 builder.clearAccessChain();
590 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
591 stdBuiltins = builder.import("GLSL.std.450");
592 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
593 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700594 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600595
596 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600597 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
598 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600599 builder.addSourceExtension(it->c_str());
600
601 // Add the top-level modes for this shader.
602
John Kessenich92187592016-02-01 13:45:25 -0700603 if (glslangIntermediate->getXfbMode()) {
604 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600605 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700606 }
John Kessenich140f3df2015-06-26 16:58:36 -0600607
608 unsigned int mode;
609 switch (glslangIntermediate->getStage()) {
610 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600611 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600612 break;
613
614 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600615 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600616 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
617 break;
618
619 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600620 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600621 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700622 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
623 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
624 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600625 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600626 }
627 if (mode != spv::BadValue)
628 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
629
John Kesseniche6903322015-10-13 16:29:02 -0600630 switch (glslangIntermediate->getVertexSpacing()) {
631 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
632 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
633 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
634 default: mode = spv::BadValue; break;
635 }
636 if (mode != spv::BadValue)
637 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
638
639 switch (glslangIntermediate->getVertexOrder()) {
640 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
641 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
642 default: mode = spv::BadValue; break;
643 }
644 if (mode != spv::BadValue)
645 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
646
647 if (glslangIntermediate->getPointMode())
648 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600649 break;
650
651 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600652 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600653 switch (glslangIntermediate->getInputPrimitive()) {
654 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
655 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
656 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700657 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600658 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
659 default: mode = spv::BadValue; break;
660 }
661 if (mode != spv::BadValue)
662 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600663
John Kessenich140f3df2015-06-26 16:58:36 -0600664 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
665
666 switch (glslangIntermediate->getOutputPrimitive()) {
667 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
668 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
669 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
670 default: mode = spv::BadValue; break;
671 }
672 if (mode != spv::BadValue)
673 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
674 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
675 break;
676
677 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600678 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600679 if (glslangIntermediate->getPixelCenterInteger())
680 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600681
John Kessenich140f3df2015-06-26 16:58:36 -0600682 if (glslangIntermediate->getOriginUpperLeft())
683 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600684 else
685 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600686
687 if (glslangIntermediate->getEarlyFragmentTests())
688 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
689
690 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600691 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
692 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
693 default: mode = spv::BadValue; break;
694 }
695 if (mode != spv::BadValue)
696 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
697
698 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
699 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600700 break;
701
702 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600703 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600704 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
705 glslangIntermediate->getLocalSize(1),
706 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600707 break;
708
709 default:
710 break;
711 }
712
713}
714
John Kessenich7ba63412015-12-20 17:37:07 -0700715// Finish everything and dump
716void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
717{
718 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100719 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
720 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700721
qiningda397332016-03-09 19:54:03 -0500722 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700723 builder.dump(out);
724}
725
John Kessenich140f3df2015-06-26 16:58:36 -0600726TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
727{
728 if (! mainTerminated) {
729 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
730 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600731 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600732 }
733}
734
735//
736// Implement the traversal functions.
737//
738// Return true from interior nodes to have the external traversal
739// continue on to children. Return false if children were
740// already processed.
741//
742
743//
744// Symbols can turn into
745// - uniform/input reads
746// - output writes
747// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
748// - something simple that degenerates into the last bullet
749//
750void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
751{
752 // getSymbolId() will set up all the IO decorations on the first call.
753 // Formal function parameters were mapped during makeFunctions().
754 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700755
756 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
757 if (builder.isPointer(id)) {
758 spv::StorageClass sc = builder.getStorageClass(id);
759 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
760 iOSet.insert(id);
761 }
762
763 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700764 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600765 // Prepare to generate code for the access
766
767 // L-value chains will be computed left to right. We're on the symbol now,
768 // which is the left-most part of the access chain, so now is "clear" time,
769 // followed by setting the base.
770 builder.clearAccessChain();
771
772 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700773 // except for
774 // A) "const in" arguments to a function, which are an intermediate object.
775 // See comments in handleUserFunctionCall().
776 // B) Specialization constants (normal constant don't even come in as a variable),
777 // These are also pure R-values.
778 glslang::TQualifier qualifier = symbol->getQualifier();
779 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
780 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600781 builder.setAccessChainRValue(id);
782 else
783 builder.setAccessChainLValue(id);
784 }
785}
786
787bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
788{
789 // First, handle special cases
790 switch (node->getOp()) {
791 case glslang::EOpAssign:
792 case glslang::EOpAddAssign:
793 case glslang::EOpSubAssign:
794 case glslang::EOpMulAssign:
795 case glslang::EOpVectorTimesMatrixAssign:
796 case glslang::EOpVectorTimesScalarAssign:
797 case glslang::EOpMatrixTimesScalarAssign:
798 case glslang::EOpMatrixTimesMatrixAssign:
799 case glslang::EOpDivAssign:
800 case glslang::EOpModAssign:
801 case glslang::EOpAndAssign:
802 case glslang::EOpInclusiveOrAssign:
803 case glslang::EOpExclusiveOrAssign:
804 case glslang::EOpLeftShiftAssign:
805 case glslang::EOpRightShiftAssign:
806 // A bin-op assign "a += b" means the same thing as "a = a + b"
807 // where a is evaluated before b. For a simple assignment, GLSL
808 // says to evaluate the left before the right. So, always, left
809 // node then right node.
810 {
811 // get the left l-value, save it away
812 builder.clearAccessChain();
813 node->getLeft()->traverse(this);
814 spv::Builder::AccessChain lValue = builder.getAccessChain();
815
816 // evaluate the right
817 builder.clearAccessChain();
818 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700819 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600820
821 if (node->getOp() != glslang::EOpAssign) {
822 // the left is also an r-value
823 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700824 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600825
826 // do the operation
827 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
828 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
829 node->getType().getBasicType());
830
831 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700832 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600833 }
834
835 // store the result
836 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800837 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600838
839 // assignments are expressions having an rValue after they are evaluated...
840 builder.clearAccessChain();
841 builder.setAccessChainRValue(rValue);
842 }
843 return false;
844 case glslang::EOpIndexDirect:
845 case glslang::EOpIndexDirectStruct:
846 {
847 // Get the left part of the access chain.
848 node->getLeft()->traverse(this);
849
850 // Add the next element in the chain
851
John Kessenich55e7d112015-11-15 21:33:39 -0700852 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600853 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
854 // This may be, e.g., an anonymous block-member selection, which generally need
855 // index remapping due to hidden members in anonymous blocks.
856 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700857 assert(remapper.size() > 0);
858 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600859 }
860
861 if (! node->getLeft()->getType().isArray() &&
862 node->getLeft()->getType().isVector() &&
863 node->getOp() == glslang::EOpIndexDirect) {
864 // This is essentially a hard-coded vector swizzle of size 1,
865 // so short circuit the access-chain stuff with a swizzle.
866 std::vector<unsigned> swizzle;
867 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600868 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600869 } else {
870 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600871 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600872 }
873 }
874 return false;
875 case glslang::EOpIndexIndirect:
876 {
877 // Structure or array or vector indirection.
878 // Will use native SPIR-V access-chain for struct and array indirection;
879 // matrices are arrays of vectors, so will also work for a matrix.
880 // Will use the access chain's 'component' for variable index into a vector.
881
882 // This adapter is building access chains left to right.
883 // Set up the access chain to the left.
884 node->getLeft()->traverse(this);
885
886 // save it so that computing the right side doesn't trash it
887 spv::Builder::AccessChain partial = builder.getAccessChain();
888
889 // compute the next index in the chain
890 builder.clearAccessChain();
891 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700892 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600893
894 // restore the saved access chain
895 builder.setAccessChain(partial);
896
897 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600898 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600899 else
John Kessenichfa668da2015-09-13 14:46:30 -0600900 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600901 }
902 return false;
903 case glslang::EOpVectorSwizzle:
904 {
905 node->getLeft()->traverse(this);
906 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
907 std::vector<unsigned> swizzle;
908 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
909 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600910 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600911 }
912 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600913 case glslang::EOpLogicalOr:
914 case glslang::EOpLogicalAnd:
915 {
916
917 // These may require short circuiting, but can sometimes be done as straight
918 // binary operations. The right operand must be short circuited if it has
919 // side effects, and should probably be if it is complex.
920 if (isTrivial(node->getRight()->getAsTyped()))
921 break; // handle below as a normal binary operation
922 // otherwise, we need to do dynamic short circuiting on the right operand
923 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
924 builder.clearAccessChain();
925 builder.setAccessChainRValue(result);
926 }
927 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600928 default:
929 break;
930 }
931
932 // Assume generic binary op...
933
John Kessenich32cfd492016-02-02 12:37:46 -0700934 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600935 builder.clearAccessChain();
936 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700937 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600938
John Kessenich32cfd492016-02-02 12:37:46 -0700939 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600940 builder.clearAccessChain();
941 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700942 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600943
John Kessenich32cfd492016-02-02 12:37:46 -0700944 // get result
945 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
946 convertGlslangToSpvType(node->getType()), left, right,
947 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600948
John Kessenich50e57562015-12-21 21:21:11 -0700949 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600950 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700951 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700952 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600953 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600954 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600955 return false;
956 }
John Kessenich140f3df2015-06-26 16:58:36 -0600957}
958
959bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
960{
John Kessenichfc51d282015-08-19 13:34:18 -0600961 spv::Id result = spv::NoResult;
962
963 // try texturing first
964 result = createImageTextureFunctionCall(node);
965 if (result != spv::NoResult) {
966 builder.clearAccessChain();
967 builder.setAccessChainRValue(result);
968
969 return false; // done with this node
970 }
971
972 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600973
974 if (node->getOp() == glslang::EOpArrayLength) {
975 // Quite special; won't want to evaluate the operand.
976
977 // Normal .length() would have been constant folded by the front-end.
978 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600979 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600980 assert(node->getOperand()->getType().isRuntimeSizedArray());
981 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
982 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600983 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
984 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600985
986 builder.clearAccessChain();
987 builder.setAccessChainRValue(length);
988
989 return false;
990 }
991
John Kessenichfc51d282015-08-19 13:34:18 -0600992 // Start by evaluating the operand
993
John Kessenich140f3df2015-06-26 16:58:36 -0600994 builder.clearAccessChain();
995 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800996
Rex Xufc618912015-09-09 16:42:49 +0800997 spv::Id operand = spv::NoResult;
998
999 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1000 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001001 node->getOp() == glslang::EOpAtomicCounter ||
1002 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001003 operand = builder.accessChainGetLValue(); // Special case l-value operands
1004 else
John Kessenich32cfd492016-02-02 12:37:46 -07001005 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001006
1007 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1008
1009 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001010 if (! result)
1011 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001012
1013 // if not, then possibly an operation
1014 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001015 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001016
1017 if (result) {
1018 builder.clearAccessChain();
1019 builder.setAccessChainRValue(result);
1020
1021 return false; // done with this node
1022 }
1023
1024 // it must be a special case, check...
1025 switch (node->getOp()) {
1026 case glslang::EOpPostIncrement:
1027 case glslang::EOpPostDecrement:
1028 case glslang::EOpPreIncrement:
1029 case glslang::EOpPreDecrement:
1030 {
1031 // we need the integer value "1" or the floating point "1.0" to add/subtract
1032 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1033 builder.makeFloatConstant(1.0F) :
1034 builder.makeIntConstant(1);
1035 glslang::TOperator op;
1036 if (node->getOp() == glslang::EOpPreIncrement ||
1037 node->getOp() == glslang::EOpPostIncrement)
1038 op = glslang::EOpAdd;
1039 else
1040 op = glslang::EOpSub;
1041
1042 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1043 convertGlslangToSpvType(node->getType()), operand, one,
1044 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001045 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001046
1047 // The result of operation is always stored, but conditionally the
1048 // consumed result. The consumed result is always an r-value.
1049 builder.accessChainStore(result);
1050 builder.clearAccessChain();
1051 if (node->getOp() == glslang::EOpPreIncrement ||
1052 node->getOp() == glslang::EOpPreDecrement)
1053 builder.setAccessChainRValue(result);
1054 else
1055 builder.setAccessChainRValue(operand);
1056 }
1057
1058 return false;
1059
1060 case glslang::EOpEmitStreamVertex:
1061 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1062 return false;
1063 case glslang::EOpEndStreamPrimitive:
1064 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1065 return false;
1066
1067 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001068 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001069 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001070 }
John Kessenich140f3df2015-06-26 16:58:36 -06001071}
1072
1073bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1074{
John Kessenichfc51d282015-08-19 13:34:18 -06001075 spv::Id result = spv::NoResult;
1076
1077 // try texturing
1078 result = createImageTextureFunctionCall(node);
1079 if (result != spv::NoResult) {
1080 builder.clearAccessChain();
1081 builder.setAccessChainRValue(result);
1082
1083 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001084 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001085 // "imageStore" is a special case, which has no result
1086 return false;
1087 }
John Kessenichfc51d282015-08-19 13:34:18 -06001088
John Kessenich140f3df2015-06-26 16:58:36 -06001089 glslang::TOperator binOp = glslang::EOpNull;
1090 bool reduceComparison = true;
1091 bool isMatrix = false;
1092 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001093 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001094
1095 assert(node->getOp());
1096
1097 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1098
1099 switch (node->getOp()) {
1100 case glslang::EOpSequence:
1101 {
1102 if (preVisit)
1103 ++sequenceDepth;
1104 else
1105 --sequenceDepth;
1106
1107 if (sequenceDepth == 1) {
1108 // If this is the parent node of all the functions, we want to see them
1109 // early, so all call points have actual SPIR-V functions to reference.
1110 // In all cases, still let the traverser visit the children for us.
1111 makeFunctions(node->getAsAggregate()->getSequence());
1112
1113 // Also, we want all globals initializers to go into the entry of main(), before
1114 // anything else gets there, so visit out of order, doing them all now.
1115 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1116
1117 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1118 // so do them manually.
1119 visitFunctions(node->getAsAggregate()->getSequence());
1120
1121 return false;
1122 }
1123
1124 return true;
1125 }
1126 case glslang::EOpLinkerObjects:
1127 {
1128 if (visit == glslang::EvPreVisit)
1129 linkageOnly = true;
1130 else
1131 linkageOnly = false;
1132
1133 return true;
1134 }
1135 case glslang::EOpComma:
1136 {
1137 // processing from left to right naturally leaves the right-most
1138 // lying around in the access chain
1139 glslang::TIntermSequence& glslangOperands = node->getSequence();
1140 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1141 glslangOperands[i]->traverse(this);
1142
1143 return false;
1144 }
1145 case glslang::EOpFunction:
1146 if (visit == glslang::EvPreVisit) {
1147 if (isShaderEntrypoint(node)) {
1148 inMain = true;
1149 builder.setBuildPoint(shaderEntry->getLastBlock());
1150 } else {
1151 handleFunctionEntry(node);
1152 }
1153 } else {
1154 if (inMain)
1155 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001156 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001157 inMain = false;
1158 }
1159
1160 return true;
1161 case glslang::EOpParameters:
1162 // Parameters will have been consumed by EOpFunction processing, but not
1163 // the body, so we still visited the function node's children, making this
1164 // child redundant.
1165 return false;
1166 case glslang::EOpFunctionCall:
1167 {
1168 if (node->isUserDefined())
1169 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001170 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1171 if (result) {
1172 builder.clearAccessChain();
1173 builder.setAccessChainRValue(result);
1174 } else
1175 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001176
1177 return false;
1178 }
1179 case glslang::EOpConstructMat2x2:
1180 case glslang::EOpConstructMat2x3:
1181 case glslang::EOpConstructMat2x4:
1182 case glslang::EOpConstructMat3x2:
1183 case glslang::EOpConstructMat3x3:
1184 case glslang::EOpConstructMat3x4:
1185 case glslang::EOpConstructMat4x2:
1186 case glslang::EOpConstructMat4x3:
1187 case glslang::EOpConstructMat4x4:
1188 case glslang::EOpConstructDMat2x2:
1189 case glslang::EOpConstructDMat2x3:
1190 case glslang::EOpConstructDMat2x4:
1191 case glslang::EOpConstructDMat3x2:
1192 case glslang::EOpConstructDMat3x3:
1193 case glslang::EOpConstructDMat3x4:
1194 case glslang::EOpConstructDMat4x2:
1195 case glslang::EOpConstructDMat4x3:
1196 case glslang::EOpConstructDMat4x4:
1197 isMatrix = true;
1198 // fall through
1199 case glslang::EOpConstructFloat:
1200 case glslang::EOpConstructVec2:
1201 case glslang::EOpConstructVec3:
1202 case glslang::EOpConstructVec4:
1203 case glslang::EOpConstructDouble:
1204 case glslang::EOpConstructDVec2:
1205 case glslang::EOpConstructDVec3:
1206 case glslang::EOpConstructDVec4:
1207 case glslang::EOpConstructBool:
1208 case glslang::EOpConstructBVec2:
1209 case glslang::EOpConstructBVec3:
1210 case glslang::EOpConstructBVec4:
1211 case glslang::EOpConstructInt:
1212 case glslang::EOpConstructIVec2:
1213 case glslang::EOpConstructIVec3:
1214 case glslang::EOpConstructIVec4:
1215 case glslang::EOpConstructUint:
1216 case glslang::EOpConstructUVec2:
1217 case glslang::EOpConstructUVec3:
1218 case glslang::EOpConstructUVec4:
1219 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001220 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001221 {
1222 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001223 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001224 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1225 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001226 if (node->getOp() == glslang::EOpConstructTextureSampler)
1227 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1228 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001229 std::vector<spv::Id> constituents;
1230 for (int c = 0; c < (int)arguments.size(); ++c)
1231 constituents.push_back(arguments[c]);
1232 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001233 } else if (isMatrix)
1234 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1235 else
1236 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001237
1238 builder.clearAccessChain();
1239 builder.setAccessChainRValue(constructed);
1240
1241 return false;
1242 }
1243
1244 // These six are component-wise compares with component-wise results.
1245 // Forward on to createBinaryOperation(), requesting a vector result.
1246 case glslang::EOpLessThan:
1247 case glslang::EOpGreaterThan:
1248 case glslang::EOpLessThanEqual:
1249 case glslang::EOpGreaterThanEqual:
1250 case glslang::EOpVectorEqual:
1251 case glslang::EOpVectorNotEqual:
1252 {
1253 // Map the operation to a binary
1254 binOp = node->getOp();
1255 reduceComparison = false;
1256 switch (node->getOp()) {
1257 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1258 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1259 default: binOp = node->getOp(); break;
1260 }
1261
1262 break;
1263 }
1264 case glslang::EOpMul:
1265 // compontent-wise matrix multiply
1266 binOp = glslang::EOpMul;
1267 break;
1268 case glslang::EOpOuterProduct:
1269 // two vectors multiplied to make a matrix
1270 binOp = glslang::EOpOuterProduct;
1271 break;
1272 case glslang::EOpDot:
1273 {
1274 // for scalar dot product, use multiply
1275 glslang::TIntermSequence& glslangOperands = node->getSequence();
1276 if (! glslangOperands[0]->getAsTyped()->isVector())
1277 binOp = glslang::EOpMul;
1278 break;
1279 }
1280 case glslang::EOpMod:
1281 // when an aggregate, this is the floating-point mod built-in function,
1282 // which can be emitted by the one in createBinaryOperation()
1283 binOp = glslang::EOpMod;
1284 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001285 case glslang::EOpEmitVertex:
1286 case glslang::EOpEndPrimitive:
1287 case glslang::EOpBarrier:
1288 case glslang::EOpMemoryBarrier:
1289 case glslang::EOpMemoryBarrierAtomicCounter:
1290 case glslang::EOpMemoryBarrierBuffer:
1291 case glslang::EOpMemoryBarrierImage:
1292 case glslang::EOpMemoryBarrierShared:
1293 case glslang::EOpGroupMemoryBarrier:
1294 noReturnValue = true;
1295 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1296 break;
1297
John Kessenich426394d2015-07-23 10:22:48 -06001298 case glslang::EOpAtomicAdd:
1299 case glslang::EOpAtomicMin:
1300 case glslang::EOpAtomicMax:
1301 case glslang::EOpAtomicAnd:
1302 case glslang::EOpAtomicOr:
1303 case glslang::EOpAtomicXor:
1304 case glslang::EOpAtomicExchange:
1305 case glslang::EOpAtomicCompSwap:
1306 atomic = true;
1307 break;
1308
John Kessenich140f3df2015-06-26 16:58:36 -06001309 default:
1310 break;
1311 }
1312
1313 //
1314 // See if it maps to a regular operation.
1315 //
John Kessenich140f3df2015-06-26 16:58:36 -06001316 if (binOp != glslang::EOpNull) {
1317 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1318 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1319 assert(left && right);
1320
1321 builder.clearAccessChain();
1322 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001323 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001324
1325 builder.clearAccessChain();
1326 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001327 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001328
1329 result = createBinaryOperation(binOp, precision,
1330 convertGlslangToSpvType(node->getType()), leftId, rightId,
1331 left->getType().getBasicType(), reduceComparison);
1332
1333 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001334 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001335 builder.clearAccessChain();
1336 builder.setAccessChainRValue(result);
1337
1338 return false;
1339 }
1340
John Kessenich426394d2015-07-23 10:22:48 -06001341 //
1342 // Create the list of operands.
1343 //
John Kessenich140f3df2015-06-26 16:58:36 -06001344 glslang::TIntermSequence& glslangOperands = node->getSequence();
1345 std::vector<spv::Id> operands;
1346 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1347 builder.clearAccessChain();
1348 glslangOperands[arg]->traverse(this);
1349
1350 // special case l-value operands; there are just a few
1351 bool lvalue = false;
1352 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001353 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001354 case glslang::EOpModf:
1355 if (arg == 1)
1356 lvalue = true;
1357 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001358 case glslang::EOpInterpolateAtSample:
1359 case glslang::EOpInterpolateAtOffset:
1360 if (arg == 0)
1361 lvalue = true;
1362 break;
Rex Xud4782c12015-09-06 16:30:11 +08001363 case glslang::EOpAtomicAdd:
1364 case glslang::EOpAtomicMin:
1365 case glslang::EOpAtomicMax:
1366 case glslang::EOpAtomicAnd:
1367 case glslang::EOpAtomicOr:
1368 case glslang::EOpAtomicXor:
1369 case glslang::EOpAtomicExchange:
1370 case glslang::EOpAtomicCompSwap:
1371 if (arg == 0)
1372 lvalue = true;
1373 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001374 case glslang::EOpAddCarry:
1375 case glslang::EOpSubBorrow:
1376 if (arg == 2)
1377 lvalue = true;
1378 break;
1379 case glslang::EOpUMulExtended:
1380 case glslang::EOpIMulExtended:
1381 if (arg >= 2)
1382 lvalue = true;
1383 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001384 default:
1385 break;
1386 }
1387 if (lvalue)
1388 operands.push_back(builder.accessChainGetLValue());
1389 else
John Kessenich32cfd492016-02-02 12:37:46 -07001390 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001391 }
John Kessenich426394d2015-07-23 10:22:48 -06001392
1393 if (atomic) {
1394 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001395 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001396 } else {
1397 // Pass through to generic operations.
1398 switch (glslangOperands.size()) {
1399 case 0:
1400 result = createNoArgOperation(node->getOp());
1401 break;
1402 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001403 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001404 break;
1405 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001406 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001407 break;
1408 }
John Kessenich140f3df2015-06-26 16:58:36 -06001409 }
1410
1411 if (noReturnValue)
1412 return false;
1413
1414 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001415 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001416 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001417 } else {
1418 builder.clearAccessChain();
1419 builder.setAccessChainRValue(result);
1420 return false;
1421 }
1422}
1423
1424bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1425{
1426 // This path handles both if-then-else and ?:
1427 // The if-then-else has a node type of void, while
1428 // ?: has a non-void node type
1429 spv::Id result = 0;
1430 if (node->getBasicType() != glslang::EbtVoid) {
1431 // don't handle this as just on-the-fly temporaries, because there will be two names
1432 // and better to leave SSA to later passes
1433 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1434 }
1435
1436 // emit the condition before doing anything with selection
1437 node->getCondition()->traverse(this);
1438
1439 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001440 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001441
1442 if (node->getTrueBlock()) {
1443 // emit the "then" statement
1444 node->getTrueBlock()->traverse(this);
1445 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001446 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001447 }
1448
1449 if (node->getFalseBlock()) {
1450 ifBuilder.makeBeginElse();
1451 // emit the "else" statement
1452 node->getFalseBlock()->traverse(this);
1453 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001454 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001455 }
1456
1457 ifBuilder.makeEndIf();
1458
1459 if (result) {
1460 // GLSL only has r-values as the result of a :?, but
1461 // if we have an l-value, that can be more efficient if it will
1462 // become the base of a complex r-value expression, because the
1463 // next layer copies r-values into memory to use the access-chain mechanism
1464 builder.clearAccessChain();
1465 builder.setAccessChainLValue(result);
1466 }
1467
1468 return false;
1469}
1470
1471bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1472{
1473 // emit and get the condition before doing anything with switch
1474 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001475 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001476
1477 // browse the children to sort out code segments
1478 int defaultSegment = -1;
1479 std::vector<TIntermNode*> codeSegments;
1480 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1481 std::vector<int> caseValues;
1482 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1483 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1484 TIntermNode* child = *c;
1485 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001486 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001487 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001488 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001489 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1490 } else
1491 codeSegments.push_back(child);
1492 }
1493
1494 // handle the case where the last code segment is missing, due to no code
1495 // statements between the last case and the end of the switch statement
1496 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1497 (int)codeSegments.size() == defaultSegment)
1498 codeSegments.push_back(nullptr);
1499
1500 // make the switch statement
1501 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001502 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001503
1504 // emit all the code in the segments
1505 breakForLoop.push(false);
1506 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1507 builder.nextSwitchSegment(segmentBlocks, s);
1508 if (codeSegments[s])
1509 codeSegments[s]->traverse(this);
1510 else
1511 builder.addSwitchBreak();
1512 }
1513 breakForLoop.pop();
1514
1515 builder.endSwitch(segmentBlocks);
1516
1517 return false;
1518}
1519
1520void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1521{
1522 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001523 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001524
1525 builder.clearAccessChain();
1526 builder.setAccessChainRValue(constant);
1527}
1528
1529bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1530{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001531 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001532 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001533 // Spec requires back edges to target header blocks, and every header block
1534 // must dominate its merge block. Make a header block first to ensure these
1535 // conditions are met. By definition, it will contain OpLoopMerge, followed
1536 // by a block-ending branch. But we don't want to put any other body/test
1537 // instructions in it, since the body/test may have arbitrary instructions,
1538 // including merges of its own.
1539 builder.setBuildPoint(&blocks.head);
1540 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001541 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001542 spv::Block& test = builder.makeNewBlock();
1543 builder.createBranch(&test);
1544
1545 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001546 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001547 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001548 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001549 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1550
1551 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001552 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001553 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001554 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001555 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001556 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001557
1558 builder.setBuildPoint(&blocks.continue_target);
1559 if (node->getTerminal())
1560 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001561 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001562 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001563 builder.createBranch(&blocks.body);
1564
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001565 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001566 builder.setBuildPoint(&blocks.body);
1567 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001568 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001569 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001570 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001571
1572 builder.setBuildPoint(&blocks.continue_target);
1573 if (node->getTerminal())
1574 node->getTerminal()->traverse(this);
1575 if (node->getTest()) {
1576 node->getTest()->traverse(this);
1577 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001578 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001579 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001580 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001581 // TODO: unless there was a break/return/discard instruction
1582 // somewhere in the body, this is an infinite loop, so we should
1583 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001584 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001585 }
John Kessenich140f3df2015-06-26 16:58:36 -06001586 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001587 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001588 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001589 return false;
1590}
1591
1592bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1593{
1594 if (node->getExpression())
1595 node->getExpression()->traverse(this);
1596
1597 switch (node->getFlowOp()) {
1598 case glslang::EOpKill:
1599 builder.makeDiscard();
1600 break;
1601 case glslang::EOpBreak:
1602 if (breakForLoop.top())
1603 builder.createLoopExit();
1604 else
1605 builder.addSwitchBreak();
1606 break;
1607 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001608 builder.createLoopContinue();
1609 break;
1610 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001611 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001612 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001613 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001614 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001615
1616 builder.clearAccessChain();
1617 break;
1618
1619 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001620 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001621 break;
1622 }
1623
1624 return false;
1625}
1626
1627spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1628{
1629 // First, steer off constants, which are not SPIR-V variables, but
1630 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001631 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001632 if (node->getQualifier().isConstant()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001633 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001634 }
1635
1636 // Now, handle actual variables
1637 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1638 spv::Id spvType = convertGlslangToSpvType(node->getType());
1639
1640 const char* name = node->getName().c_str();
1641 if (glslang::IsAnonymous(name))
1642 name = "";
1643
1644 return builder.createVariable(storageClass, spvType, name);
1645}
1646
1647// Return type Id of the sampled type.
1648spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1649{
1650 switch (sampler.type) {
1651 case glslang::EbtFloat: return builder.makeFloatType(32);
1652 case glslang::EbtInt: return builder.makeIntType(32);
1653 case glslang::EbtUint: return builder.makeUintType(32);
1654 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001655 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001656 return builder.makeFloatType(32);
1657 }
1658}
1659
John Kessenich3ac051e2015-12-20 11:29:16 -07001660// Convert from a glslang type to an SPV type, by calling into a
1661// recursive version of this function. This establishes the inherited
1662// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001663spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1664{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001665 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001666}
1667
1668// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001669// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001670spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001671{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001672 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001673
1674 switch (type.getBasicType()) {
1675 case glslang::EbtVoid:
1676 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001677 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001678 break;
1679 case glslang::EbtFloat:
1680 spvType = builder.makeFloatType(32);
1681 break;
1682 case glslang::EbtDouble:
1683 spvType = builder.makeFloatType(64);
1684 break;
1685 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001686 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1687 // a 32-bit int where non-0 means true.
1688 if (explicitLayout != glslang::ElpNone)
1689 spvType = builder.makeUintType(32);
1690 else
1691 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001692 break;
1693 case glslang::EbtInt:
1694 spvType = builder.makeIntType(32);
1695 break;
1696 case glslang::EbtUint:
1697 spvType = builder.makeUintType(32);
1698 break;
John Kessenich426394d2015-07-23 10:22:48 -06001699 case glslang::EbtAtomicUint:
1700 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1701 spvType = builder.makeUintType(32);
1702 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001703 case glslang::EbtSampler:
1704 {
1705 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001706 if (sampler.sampler) {
1707 // pure sampler
1708 spvType = builder.makeSamplerType();
1709 } else {
1710 // an image is present, make its type
1711 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1712 sampler.image ? 2 : 1, TranslateImageFormat(type));
1713 if (sampler.combined) {
1714 // already has both image and sampler, make the combined type
1715 spvType = builder.makeSampledImageType(spvType);
1716 }
John Kessenich55e7d112015-11-15 21:33:39 -07001717 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001718 }
John Kessenich140f3df2015-06-26 16:58:36 -06001719 break;
1720 case glslang::EbtStruct:
1721 case glslang::EbtBlock:
1722 {
1723 // If we've seen this struct type, return it
1724 const glslang::TTypeList* glslangStruct = type.getStruct();
1725 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001726
1727 // Try to share structs for different layouts, but not yet for other
1728 // kinds of qualification (primarily not yet including interpolant qualification).
1729 if (! HasNonLayoutQualifiers(qualifier))
1730 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1731 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001732 break;
1733
1734 // else, we haven't seen it...
1735
1736 // Create a vector of struct types for SPIR-V to consume
1737 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1738 if (type.getBasicType() == glslang::EbtBlock)
1739 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001740 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001741 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1742 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1743 if (glslangType.hiddenMember()) {
1744 ++memberDelta;
1745 if (type.getBasicType() == glslang::EbtBlock)
1746 memberRemapper[glslangStruct][i] = -1;
1747 } else {
1748 if (type.getBasicType() == glslang::EbtBlock)
1749 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001750 // modify just this child's view of the qualifier
1751 glslang::TQualifier subQualifier = glslangType.getQualifier();
1752 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001753
1754 // manually inherit location; it's more complex
1755 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1756 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1757 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001758 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001759
1760 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001761 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001762 }
1763 }
1764
1765 // Make the SPIR-V type
1766 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001767 if (! HasNonLayoutQualifiers(qualifier))
1768 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001769
1770 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001771 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001772 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001773 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1774 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1775 int member = i;
1776 if (type.getBasicType() == glslang::EbtBlock)
1777 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001778
John Kesseniche0b6cad2015-12-24 10:30:13 -07001779 // modify just this child's view of the qualifier
1780 glslang::TQualifier subQualifier = glslangType.getQualifier();
1781 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001782
John Kessenich140f3df2015-06-26 16:58:36 -06001783 // using -1 above to indicate a hidden member
1784 if (member >= 0) {
1785 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001786 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001787 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001788 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1789 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001790
Rex Xu1da878f2016-02-21 20:59:01 +08001791 if (qualifier.storage == glslang::EvqBuffer) {
1792 std::vector<spv::Decoration> memory;
1793 TranslateMemoryDecoration(subQualifier, memory);
1794 for (unsigned int i = 0; i < memory.size(); ++i)
1795 addMemberDecoration(spvType, member, memory[i]);
1796 }
1797
John Kessenich09677482016-02-19 12:21:50 -07001798 // compute location decoration; tricky based on whether inheritance is at play
1799 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1800 // probably move to the linker stage of the front end proper, and just have the
1801 // answer sitting already distributed throughout the individual member locations.
1802 int location = -1; // will only decorate if present or inherited
1803 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1804 location = subQualifier.layoutLocation;
1805 else if (qualifier.hasLocation()) // inheritance
1806 location = qualifier.layoutLocation + locationOffset;
1807 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001808 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001809 if (location >= 0)
1810 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1811
1812 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001813 if (glslangType.getQualifier().hasComponent())
1814 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1815 if (glslangType.getQualifier().hasXfbOffset())
1816 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001817 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001818 // figure out what to do with offset, which is accumulating
1819 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001820 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001821 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001822 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001823 offset = nextOffset;
1824 }
John Kessenich140f3df2015-06-26 16:58:36 -06001825
John Kessenichf85e8062015-12-19 13:57:10 -07001826 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001827 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001828
John Kessenich140f3df2015-06-26 16:58:36 -06001829 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001830 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1831 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001832 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001833 }
1834 }
1835
1836 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001837 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001838 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001839 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001840 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001841 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001842 }
John Kessenich140f3df2015-06-26 16:58:36 -06001843 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001844 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001845 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001846 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001847 if (type.getQualifier().hasXfbBuffer())
1848 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1849 }
1850 }
1851 break;
1852 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001853 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001854 break;
1855 }
1856
1857 if (type.isMatrix())
1858 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1859 else {
1860 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1861 if (type.getVectorSize() > 1)
1862 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1863 }
1864
1865 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001866 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1867
John Kessenichc9a80832015-09-12 12:17:44 -06001868 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001869 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001870 // We need to decorate array strides for types needing explicit layout, except blocks.
1871 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001872 // Use a dummy glslang type for querying internal strides of
1873 // arrays of arrays, but using just a one-dimensional array.
1874 glslang::TType simpleArrayType(type, 0); // deference type of the array
1875 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1876 simpleArrayType.getArraySizes().dereference();
1877
1878 // Will compute the higher-order strides here, rather than making a whole
1879 // pile of types and doing repetitive recursion on their contents.
1880 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1881 }
John Kessenichf8842e52016-01-04 19:22:56 -07001882
1883 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001884 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001885 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001886 if (stride > 0)
1887 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001888 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001889 }
1890 } else {
1891 // single-dimensional array, and don't yet have stride
1892
John Kessenichf8842e52016-01-04 19:22:56 -07001893 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001894 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1895 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001896 }
John Kessenich31ed4832015-09-09 17:51:38 -06001897
John Kessenichc9a80832015-09-12 12:17:44 -06001898 // Do the outer dimension, which might not be known for a runtime-sized array
1899 if (type.isRuntimeSizedArray()) {
1900 spvType = builder.makeRuntimeArray(spvType);
1901 } else {
1902 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001903 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001904 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001905 if (stride > 0)
1906 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001907 }
1908
1909 return spvType;
1910}
1911
John Kessenich6c292d32016-02-15 20:58:50 -07001912// Turn the expression forming the array size into an id.
1913// This is not quite trivial, because of specialization constants.
1914// Sometimes, a raw constant is turned into an Id, and sometimes
1915// a specialization constant expression is.
1916spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1917{
1918 // First, see if this is sized with a node, meaning a specialization constant:
1919 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1920 if (specNode != nullptr) {
1921 builder.clearAccessChain();
1922 specNode->traverse(this);
1923 return accessChainLoad(specNode->getAsTyped()->getType());
1924 }
1925
1926 // Otherwise, need a compile-time (front end) size, get it:
1927 int size = arraySizes.getDimSize(dim);
1928 assert(size > 0);
1929 return builder.makeUintConstant(size);
1930}
1931
John Kessenich103bef92016-02-08 21:38:15 -07001932// Wrap the builder's accessChainLoad to:
1933// - localize handling of RelaxedPrecision
1934// - use the SPIR-V inferred type instead of another conversion of the glslang type
1935// (avoids unnecessary work and possible type punning for structures)
1936// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001937spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1938{
John Kessenich103bef92016-02-08 21:38:15 -07001939 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1940 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1941
1942 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001943 if (type.getBasicType() == glslang::EbtBool) {
1944 if (builder.isScalarType(nominalTypeId)) {
1945 // Conversion for bool
1946 spv::Id boolType = builder.makeBoolType();
1947 if (nominalTypeId != boolType)
1948 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1949 } else if (builder.isVectorType(nominalTypeId)) {
1950 // Conversion for bvec
1951 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1952 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1953 if (nominalTypeId != bvecType)
1954 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1955 }
1956 }
John Kessenich103bef92016-02-08 21:38:15 -07001957
1958 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001959}
1960
Rex Xu27253232016-02-23 17:51:09 +08001961// Wrap the builder's accessChainStore to:
1962// - do conversion of concrete to abstract type
1963void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
1964{
1965 // Need to convert to abstract types when necessary
1966 if (type.getBasicType() == glslang::EbtBool) {
1967 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1968
1969 if (builder.isScalarType(nominalTypeId)) {
1970 // Conversion for bool
1971 spv::Id boolType = builder.makeBoolType();
1972 if (nominalTypeId != boolType) {
1973 spv::Id zero = builder.makeUintConstant(0);
1974 spv::Id one = builder.makeUintConstant(1);
1975 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1976 }
1977 } else if (builder.isVectorType(nominalTypeId)) {
1978 // Conversion for bvec
1979 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1980 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1981 if (nominalTypeId != bvecType) {
1982 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
1983 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
1984 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1985 }
1986 }
1987 }
1988
1989 builder.accessChainStore(rvalue);
1990}
1991
John Kessenichf85e8062015-12-19 13:57:10 -07001992// Decide whether or not this type should be
1993// decorated with offsets and strides, and if so
1994// whether std140 or std430 rules should be applied.
1995glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001996{
John Kessenichf85e8062015-12-19 13:57:10 -07001997 // has to be a block
1998 if (type.getBasicType() != glslang::EbtBlock)
1999 return glslang::ElpNone;
2000
2001 // has to be a uniform or buffer block
2002 if (type.getQualifier().storage != glslang::EvqUniform &&
2003 type.getQualifier().storage != glslang::EvqBuffer)
2004 return glslang::ElpNone;
2005
2006 // return the layout to use
2007 switch (type.getQualifier().layoutPacking) {
2008 case glslang::ElpStd140:
2009 case glslang::ElpStd430:
2010 return type.getQualifier().layoutPacking;
2011 default:
2012 return glslang::ElpNone;
2013 }
John Kessenich31ed4832015-09-09 17:51:38 -06002014}
2015
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002016// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002017int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002018{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002019 int size;
John Kessenich49987892015-12-29 17:11:44 -07002020 int stride;
2021 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002022
2023 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002024}
2025
John Kessenich49987892015-12-29 17:11:44 -07002026// 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 -07002027// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002028int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002029{
John Kessenich49987892015-12-29 17:11:44 -07002030 glslang::TType elementType;
2031 elementType.shallowCopy(matrixType);
2032 elementType.clearArraySizes();
2033
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002034 int size;
John Kessenich49987892015-12-29 17:11:44 -07002035 int stride;
2036 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2037
2038 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002039}
2040
John Kessenich5e4b1242015-08-06 22:53:06 -06002041// Given a member type of a struct, realign the current offset for it, and compute
2042// the next (not yet aligned) offset for the next member, which will get aligned
2043// on the next call.
2044// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2045// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2046// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002047void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002048 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002049{
2050 // this will get a positive value when deemed necessary
2051 nextOffset = -1;
2052
John Kessenich5e4b1242015-08-06 22:53:06 -06002053 // override anything in currentOffset with user-set offset
2054 if (memberType.getQualifier().hasOffset())
2055 currentOffset = memberType.getQualifier().layoutOffset;
2056
2057 // It could be that current linker usage in glslang updated all the layoutOffset,
2058 // in which case the following code does not matter. But, that's not quite right
2059 // once cross-compilation unit GLSL validation is done, as the original user
2060 // settings are needed in layoutOffset, and then the following will come into play.
2061
John Kessenichf85e8062015-12-19 13:57:10 -07002062 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002063 if (! memberType.getQualifier().hasOffset())
2064 currentOffset = -1;
2065
2066 return;
2067 }
2068
John Kessenichf85e8062015-12-19 13:57:10 -07002069 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002070 if (currentOffset < 0)
2071 currentOffset = 0;
2072
2073 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2074 // but possibly not yet correctly aligned.
2075
2076 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002077 int dummyStride;
2078 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002079 glslang::RoundToPow2(currentOffset, memberAlignment);
2080 nextOffset = currentOffset + memberSize;
2081}
2082
John Kessenich140f3df2015-06-26 16:58:36 -06002083bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2084{
2085 return node->getName() == "main(";
2086}
2087
2088// Make all the functions, skeletally, without actually visiting their bodies.
2089void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2090{
2091 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2092 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2093 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2094 continue;
2095
2096 // We're on a user function. Set up the basic interface for the function now,
2097 // so that it's available to call.
2098 // Translating the body will happen later.
2099 //
2100 // Typically (except for a "const in" parameter), an address will be passed to the
2101 // function. What it is an address of varies:
2102 //
2103 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2104 // so that write needs to be to a copy, hence the address of a copy works.
2105 //
2106 // - "const in" parameters can just be the r-value, as no writes need occur.
2107 //
2108 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2109 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2110
2111 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002112 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002113 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2114
2115 for (int p = 0; p < (int)parameters.size(); ++p) {
2116 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2117 spv::Id typeId = convertGlslangToSpvType(paramType);
2118 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2119 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2120 else
2121 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002122 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002123 paramTypes.push_back(typeId);
2124 }
2125
2126 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002127 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2128 convertGlslangToSpvType(glslFunction->getType()),
2129 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002130
2131 // Track function to emit/call later
2132 functionMap[glslFunction->getName().c_str()] = function;
2133
2134 // Set the parameter id's
2135 for (int p = 0; p < (int)parameters.size(); ++p) {
2136 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2137 // give a name too
2138 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2139 }
2140 }
2141}
2142
2143// Process all the initializers, while skipping the functions and link objects
2144void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2145{
2146 builder.setBuildPoint(shaderEntry->getLastBlock());
2147 for (int i = 0; i < (int)initializers.size(); ++i) {
2148 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2149 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2150
2151 // We're on a top-level node that's not a function. Treat as an initializer, whose
2152 // code goes into the beginning of main.
2153 initializer->traverse(this);
2154 }
2155 }
2156}
2157
2158// Process all the functions, while skipping initializers.
2159void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2160{
2161 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2162 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2163 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2164 node->traverse(this);
2165 }
2166}
2167
2168void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2169{
2170 // SPIR-V functions should already be in the functionMap from the prepass
2171 // that called makeFunctions().
2172 spv::Function* function = functionMap[node->getName().c_str()];
2173 spv::Block* functionBlock = function->getEntryBlock();
2174 builder.setBuildPoint(functionBlock);
2175}
2176
Rex Xu04db3f52015-09-16 11:44:02 +08002177void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002178{
Rex Xufc618912015-09-09 16:42:49 +08002179 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002180
2181 glslang::TSampler sampler = {};
2182 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002183 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002184 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2185 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2186 }
2187
John Kessenich140f3df2015-06-26 16:58:36 -06002188 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2189 builder.clearAccessChain();
2190 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002191
2192 // Special case l-value operands
2193 bool lvalue = false;
2194 switch (node.getOp()) {
2195 case glslang::EOpImageAtomicAdd:
2196 case glslang::EOpImageAtomicMin:
2197 case glslang::EOpImageAtomicMax:
2198 case glslang::EOpImageAtomicAnd:
2199 case glslang::EOpImageAtomicOr:
2200 case glslang::EOpImageAtomicXor:
2201 case glslang::EOpImageAtomicExchange:
2202 case glslang::EOpImageAtomicCompSwap:
2203 if (i == 0)
2204 lvalue = true;
2205 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002206 case glslang::EOpSparseImageLoad:
2207 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2208 lvalue = true;
2209 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002210 case glslang::EOpSparseTexture:
2211 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2212 lvalue = true;
2213 break;
2214 case glslang::EOpSparseTextureClamp:
2215 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2216 lvalue = true;
2217 break;
2218 case glslang::EOpSparseTextureLod:
2219 case glslang::EOpSparseTextureOffset:
2220 if (i == 3)
2221 lvalue = true;
2222 break;
2223 case glslang::EOpSparseTextureFetch:
2224 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2225 lvalue = true;
2226 break;
2227 case glslang::EOpSparseTextureFetchOffset:
2228 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2229 lvalue = true;
2230 break;
2231 case glslang::EOpSparseTextureLodOffset:
2232 case glslang::EOpSparseTextureGrad:
2233 case glslang::EOpSparseTextureOffsetClamp:
2234 if (i == 4)
2235 lvalue = true;
2236 break;
2237 case glslang::EOpSparseTextureGradOffset:
2238 case glslang::EOpSparseTextureGradClamp:
2239 if (i == 5)
2240 lvalue = true;
2241 break;
2242 case glslang::EOpSparseTextureGradOffsetClamp:
2243 if (i == 6)
2244 lvalue = true;
2245 break;
2246 case glslang::EOpSparseTextureGather:
2247 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2248 lvalue = true;
2249 break;
2250 case glslang::EOpSparseTextureGatherOffset:
2251 case glslang::EOpSparseTextureGatherOffsets:
2252 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2253 lvalue = true;
2254 break;
Rex Xufc618912015-09-09 16:42:49 +08002255 default:
2256 break;
2257 }
2258
Rex Xu6b86d492015-09-16 17:48:22 +08002259 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002260 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002261 else
John Kessenich32cfd492016-02-02 12:37:46 -07002262 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002263 }
2264}
2265
John Kessenichfc51d282015-08-19 13:34:18 -06002266void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002267{
John Kessenichfc51d282015-08-19 13:34:18 -06002268 builder.clearAccessChain();
2269 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002270 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002271}
John Kessenich140f3df2015-06-26 16:58:36 -06002272
John Kessenichfc51d282015-08-19 13:34:18 -06002273spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2274{
Rex Xufc618912015-09-09 16:42:49 +08002275 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002276 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002277 }
2278
John Kessenichfc51d282015-08-19 13:34:18 -06002279 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002280 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2281 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2282 std::vector<spv::Id> arguments;
2283 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002284 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002285 else
2286 translateArguments(*node->getAsUnaryNode(), arguments);
2287 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2288
2289 spv::Builder::TextureParameters params = { };
2290 params.sampler = arguments[0];
2291
Rex Xu04db3f52015-09-16 11:44:02 +08002292 glslang::TCrackedTextureOp cracked;
2293 node->crackTexture(sampler, cracked);
2294
John Kessenichfc51d282015-08-19 13:34:18 -06002295 // Check for queries
2296 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002297 // a sampled image needs to have the image extracted first
2298 if (builder.isSampledImage(params.sampler))
2299 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002300 switch (node->getOp()) {
2301 case glslang::EOpImageQuerySize:
2302 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002303 if (arguments.size() > 1) {
2304 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002305 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002306 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002307 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002308 case glslang::EOpImageQuerySamples:
2309 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002310 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002311 case glslang::EOpTextureQueryLod:
2312 params.coords = arguments[1];
2313 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2314 case glslang::EOpTextureQueryLevels:
2315 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002316 case glslang::EOpSparseTexelsResident:
2317 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002318 default:
2319 assert(0);
2320 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002321 }
John Kessenich140f3df2015-06-26 16:58:36 -06002322 }
2323
Rex Xufc618912015-09-09 16:42:49 +08002324 // Check for image functions other than queries
2325 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002326 std::vector<spv::Id> operands;
2327 auto opIt = arguments.begin();
2328 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002329
2330 // Handle subpass operations
2331 // TODO: GLSL should change to have the "MS" only on the type rather than the
2332 // built-in function.
2333 if (cracked.subpass) {
2334 // add on the (0,0) coordinate
2335 spv::Id zero = builder.makeIntConstant(0);
2336 std::vector<spv::Id> comps;
2337 comps.push_back(zero);
2338 comps.push_back(zero);
2339 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2340 if (sampler.ms) {
2341 operands.push_back(spv::ImageOperandsSampleMask);
2342 operands.push_back(*(opIt++));
2343 }
2344 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2345 }
2346
John Kessenich56bab042015-09-16 10:54:31 -06002347 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002348 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002349 if (sampler.ms) {
2350 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002351 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002352 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002353 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2354 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002355 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002356 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002357 if (sampler.ms) {
2358 operands.push_back(*(opIt + 1));
2359 operands.push_back(spv::ImageOperandsSampleMask);
2360 operands.push_back(*opIt);
2361 } else
2362 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002363 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002364 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2365 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002366 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002367 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2368 builder.addCapability(spv::CapabilitySparseResidency);
2369 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2370 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2371
2372 if (sampler.ms) {
2373 operands.push_back(spv::ImageOperandsSampleMask);
2374 operands.push_back(*opIt++);
2375 }
2376
2377 // Create the return type that was a special structure
2378 spv::Id texelOut = *opIt;
2379 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2380 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2381 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2382
2383 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2384
2385 // Decode the return type
2386 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2387 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002388 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002389 // Process image atomic operations
2390
2391 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2392 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002393 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002394
Rex Xufc618912015-09-09 16:42:49 +08002395 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002396 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002397
2398 std::vector<spv::Id> operands;
2399 operands.push_back(pointer);
2400 for (; opIt != arguments.end(); ++opIt)
2401 operands.push_back(*opIt);
2402
Rex Xu04db3f52015-09-16 11:44:02 +08002403 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002404 }
2405 }
2406
2407 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002408 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002409 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2410
John Kessenichfc51d282015-08-19 13:34:18 -06002411 // check for bias argument
2412 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002413 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002414 int nonBiasArgCount = 2;
2415 if (cracked.offset)
2416 ++nonBiasArgCount;
2417 if (cracked.grad)
2418 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002419 if (cracked.lodClamp)
2420 ++nonBiasArgCount;
2421 if (sparse)
2422 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002423
2424 if ((int)arguments.size() > nonBiasArgCount)
2425 bias = true;
2426 }
2427
John Kessenichfc51d282015-08-19 13:34:18 -06002428 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002429
John Kessenichfc51d282015-08-19 13:34:18 -06002430 params.coords = arguments[1];
2431 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002432 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002433
2434 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002435 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002436 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002437 ++extraArgs;
2438 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002439 params.Dref = arguments[2];
2440 ++extraArgs;
2441 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002442 std::vector<spv::Id> indexes;
2443 int comp;
2444 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002445 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002446 else
2447 comp = builder.getNumComponents(params.coords) - 1;
2448 indexes.push_back(comp);
2449 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2450 }
2451 if (cracked.lod) {
2452 params.lod = arguments[2];
2453 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002454 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2455 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2456 noImplicitLod = true;
2457 }
2458 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002459 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002460 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002461 }
2462 if (cracked.grad) {
2463 params.gradX = arguments[2 + extraArgs];
2464 params.gradY = arguments[3 + extraArgs];
2465 extraArgs += 2;
2466 }
John Kessenich55e7d112015-11-15 21:33:39 -07002467 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002468 params.offset = arguments[2 + extraArgs];
2469 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002470 } else if (cracked.offsets) {
2471 params.offsets = arguments[2 + extraArgs];
2472 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002473 }
Rex Xu48edadf2015-12-31 16:11:41 +08002474 if (cracked.lodClamp) {
2475 params.lodClamp = arguments[2 + extraArgs];
2476 ++extraArgs;
2477 }
2478 if (sparse) {
2479 params.texelOut = arguments[2 + extraArgs];
2480 ++extraArgs;
2481 }
John Kessenichfc51d282015-08-19 13:34:18 -06002482 if (bias) {
2483 params.bias = arguments[2 + extraArgs];
2484 ++extraArgs;
2485 }
John Kessenich55e7d112015-11-15 21:33:39 -07002486 if (cracked.gather && ! sampler.shadow) {
2487 // default component is 0, if missing, otherwise an argument
2488 if (2 + extraArgs < (int)arguments.size()) {
2489 params.comp = arguments[2 + extraArgs];
2490 ++extraArgs;
2491 } else {
2492 params.comp = builder.makeIntConstant(0);
2493 }
2494 }
John Kessenichfc51d282015-08-19 13:34:18 -06002495
John Kessenich019f08f2016-02-15 15:40:42 -07002496 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002497}
2498
2499spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2500{
2501 // Grab the function's pointer from the previously created function
2502 spv::Function* function = functionMap[node->getName().c_str()];
2503 if (! function)
2504 return 0;
2505
2506 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2507 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2508
2509 // See comments in makeFunctions() for details about the semantics for parameter passing.
2510 //
2511 // These imply we need a four step process:
2512 // 1. Evaluate the arguments
2513 // 2. Allocate and make copies of in, out, and inout arguments
2514 // 3. Make the call
2515 // 4. Copy back the results
2516
2517 // 1. Evaluate the arguments
2518 std::vector<spv::Builder::AccessChain> lValues;
2519 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002520 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002521 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2522 // build l-value
2523 builder.clearAccessChain();
2524 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002525 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002526 // keep outputs as l-values, evaluate input-only as r-values
2527 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2528 // save l-value
2529 lValues.push_back(builder.getAccessChain());
2530 } else {
2531 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002532 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002533 }
2534 }
2535
2536 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2537 // copy the original into that space.
2538 //
2539 // Also, build up the list of actual arguments to pass in for the call
2540 int lValueCount = 0;
2541 int rValueCount = 0;
2542 std::vector<spv::Id> spvArgs;
2543 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2544 spv::Id arg;
2545 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2546 // need space to hold the copy
2547 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2548 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2549 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2550 // need to copy the input into output space
2551 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002552 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002553 builder.createStore(copy, arg);
2554 }
2555 ++lValueCount;
2556 } else {
2557 arg = rValues[rValueCount];
2558 ++rValueCount;
2559 }
2560 spvArgs.push_back(arg);
2561 }
2562
2563 // 3. Make the call.
2564 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002565 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002566
2567 // 4. Copy back out an "out" arguments.
2568 lValueCount = 0;
2569 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2570 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2571 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2572 spv::Id copy = builder.createLoad(spvArgs[a]);
2573 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002574 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002575 }
2576 ++lValueCount;
2577 }
2578 }
2579
2580 return result;
2581}
2582
2583// Translate AST operation to SPV operation, already having SPV-based operands/types.
2584spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2585 spv::Id typeId, spv::Id left, spv::Id right,
2586 glslang::TBasicType typeProxy, bool reduceComparison)
2587{
2588 bool isUnsigned = typeProxy == glslang::EbtUint;
2589 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2590
2591 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002592 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002593 bool comparison = false;
2594
2595 switch (op) {
2596 case glslang::EOpAdd:
2597 case glslang::EOpAddAssign:
2598 if (isFloat)
2599 binOp = spv::OpFAdd;
2600 else
2601 binOp = spv::OpIAdd;
2602 break;
2603 case glslang::EOpSub:
2604 case glslang::EOpSubAssign:
2605 if (isFloat)
2606 binOp = spv::OpFSub;
2607 else
2608 binOp = spv::OpISub;
2609 break;
2610 case glslang::EOpMul:
2611 case glslang::EOpMulAssign:
2612 if (isFloat)
2613 binOp = spv::OpFMul;
2614 else
2615 binOp = spv::OpIMul;
2616 break;
2617 case glslang::EOpVectorTimesScalar:
2618 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002619 if (isFloat) {
2620 if (builder.isVector(right))
2621 std::swap(left, right);
2622 assert(builder.isScalar(right));
2623 needMatchingVectors = false;
2624 binOp = spv::OpVectorTimesScalar;
2625 } else
2626 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002627 break;
2628 case glslang::EOpVectorTimesMatrix:
2629 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002630 binOp = spv::OpVectorTimesMatrix;
2631 break;
2632 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002633 binOp = spv::OpMatrixTimesVector;
2634 break;
2635 case glslang::EOpMatrixTimesScalar:
2636 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002637 binOp = spv::OpMatrixTimesScalar;
2638 break;
2639 case glslang::EOpMatrixTimesMatrix:
2640 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002641 binOp = spv::OpMatrixTimesMatrix;
2642 break;
2643 case glslang::EOpOuterProduct:
2644 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002645 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002646 break;
2647
2648 case glslang::EOpDiv:
2649 case glslang::EOpDivAssign:
2650 if (isFloat)
2651 binOp = spv::OpFDiv;
2652 else if (isUnsigned)
2653 binOp = spv::OpUDiv;
2654 else
2655 binOp = spv::OpSDiv;
2656 break;
2657 case glslang::EOpMod:
2658 case glslang::EOpModAssign:
2659 if (isFloat)
2660 binOp = spv::OpFMod;
2661 else if (isUnsigned)
2662 binOp = spv::OpUMod;
2663 else
2664 binOp = spv::OpSMod;
2665 break;
2666 case glslang::EOpRightShift:
2667 case glslang::EOpRightShiftAssign:
2668 if (isUnsigned)
2669 binOp = spv::OpShiftRightLogical;
2670 else
2671 binOp = spv::OpShiftRightArithmetic;
2672 break;
2673 case glslang::EOpLeftShift:
2674 case glslang::EOpLeftShiftAssign:
2675 binOp = spv::OpShiftLeftLogical;
2676 break;
2677 case glslang::EOpAnd:
2678 case glslang::EOpAndAssign:
2679 binOp = spv::OpBitwiseAnd;
2680 break;
2681 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002682 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002683 binOp = spv::OpLogicalAnd;
2684 break;
2685 case glslang::EOpInclusiveOr:
2686 case glslang::EOpInclusiveOrAssign:
2687 binOp = spv::OpBitwiseOr;
2688 break;
2689 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002690 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002691 binOp = spv::OpLogicalOr;
2692 break;
2693 case glslang::EOpExclusiveOr:
2694 case glslang::EOpExclusiveOrAssign:
2695 binOp = spv::OpBitwiseXor;
2696 break;
2697 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002698 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002699 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002700 break;
2701
2702 case glslang::EOpLessThan:
2703 case glslang::EOpGreaterThan:
2704 case glslang::EOpLessThanEqual:
2705 case glslang::EOpGreaterThanEqual:
2706 case glslang::EOpEqual:
2707 case glslang::EOpNotEqual:
2708 case glslang::EOpVectorEqual:
2709 case glslang::EOpVectorNotEqual:
2710 comparison = true;
2711 break;
2712 default:
2713 break;
2714 }
2715
John Kessenich7c1aa102015-10-15 13:29:11 -06002716 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002717 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002718 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002719 if (builder.isMatrix(left) || builder.isMatrix(right))
2720 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002721
2722 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002723 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002724 builder.promoteScalar(precision, left, right);
2725
John Kessenich32cfd492016-02-02 12:37:46 -07002726 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002727 }
2728
2729 if (! comparison)
2730 return 0;
2731
John Kessenich7c1aa102015-10-15 13:29:11 -06002732 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002733
2734 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2735 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2736
John Kessenich22118352015-12-21 20:54:09 -07002737 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002738 }
2739
2740 switch (op) {
2741 case glslang::EOpLessThan:
2742 if (isFloat)
2743 binOp = spv::OpFOrdLessThan;
2744 else if (isUnsigned)
2745 binOp = spv::OpULessThan;
2746 else
2747 binOp = spv::OpSLessThan;
2748 break;
2749 case glslang::EOpGreaterThan:
2750 if (isFloat)
2751 binOp = spv::OpFOrdGreaterThan;
2752 else if (isUnsigned)
2753 binOp = spv::OpUGreaterThan;
2754 else
2755 binOp = spv::OpSGreaterThan;
2756 break;
2757 case glslang::EOpLessThanEqual:
2758 if (isFloat)
2759 binOp = spv::OpFOrdLessThanEqual;
2760 else if (isUnsigned)
2761 binOp = spv::OpULessThanEqual;
2762 else
2763 binOp = spv::OpSLessThanEqual;
2764 break;
2765 case glslang::EOpGreaterThanEqual:
2766 if (isFloat)
2767 binOp = spv::OpFOrdGreaterThanEqual;
2768 else if (isUnsigned)
2769 binOp = spv::OpUGreaterThanEqual;
2770 else
2771 binOp = spv::OpSGreaterThanEqual;
2772 break;
2773 case glslang::EOpEqual:
2774 case glslang::EOpVectorEqual:
2775 if (isFloat)
2776 binOp = spv::OpFOrdEqual;
2777 else
2778 binOp = spv::OpIEqual;
2779 break;
2780 case glslang::EOpNotEqual:
2781 case glslang::EOpVectorNotEqual:
2782 if (isFloat)
2783 binOp = spv::OpFOrdNotEqual;
2784 else
2785 binOp = spv::OpINotEqual;
2786 break;
2787 default:
2788 break;
2789 }
2790
John Kessenich32cfd492016-02-02 12:37:46 -07002791 if (binOp != spv::OpNop)
2792 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002793
2794 return 0;
2795}
2796
John Kessenich04bb8a02015-12-12 12:28:14 -07002797//
2798// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2799// These can be any of:
2800//
2801// matrix * scalar
2802// scalar * matrix
2803// matrix * matrix linear algebraic
2804// matrix * vector
2805// vector * matrix
2806// matrix * matrix componentwise
2807// matrix op matrix op in {+, -, /}
2808// matrix op scalar op in {+, -, /}
2809// scalar op matrix op in {+, -, /}
2810//
2811spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2812{
2813 bool firstClass = true;
2814
2815 // First, handle first-class matrix operations (* and matrix/scalar)
2816 switch (op) {
2817 case spv::OpFDiv:
2818 if (builder.isMatrix(left) && builder.isScalar(right)) {
2819 // turn matrix / scalar into a multiply...
2820 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2821 op = spv::OpMatrixTimesScalar;
2822 } else
2823 firstClass = false;
2824 break;
2825 case spv::OpMatrixTimesScalar:
2826 if (builder.isMatrix(right))
2827 std::swap(left, right);
2828 assert(builder.isScalar(right));
2829 break;
2830 case spv::OpVectorTimesMatrix:
2831 assert(builder.isVector(left));
2832 assert(builder.isMatrix(right));
2833 break;
2834 case spv::OpMatrixTimesVector:
2835 assert(builder.isMatrix(left));
2836 assert(builder.isVector(right));
2837 break;
2838 case spv::OpMatrixTimesMatrix:
2839 assert(builder.isMatrix(left));
2840 assert(builder.isMatrix(right));
2841 break;
2842 default:
2843 firstClass = false;
2844 break;
2845 }
2846
John Kessenich32cfd492016-02-02 12:37:46 -07002847 if (firstClass)
2848 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002849
2850 // Handle component-wise +, -, *, and / for all combinations of type.
2851 // The result type of all of them is the same type as the (a) matrix operand.
2852 // The algorithm is to:
2853 // - break the matrix(es) into vectors
2854 // - smear any scalar to a vector
2855 // - do vector operations
2856 // - make a matrix out the vector results
2857 switch (op) {
2858 case spv::OpFAdd:
2859 case spv::OpFSub:
2860 case spv::OpFDiv:
2861 case spv::OpFMul:
2862 {
2863 // one time set up...
2864 bool leftMat = builder.isMatrix(left);
2865 bool rightMat = builder.isMatrix(right);
2866 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2867 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2868 spv::Id scalarType = builder.getScalarTypeId(typeId);
2869 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2870 std::vector<spv::Id> results;
2871 spv::Id smearVec = spv::NoResult;
2872 if (builder.isScalar(left))
2873 smearVec = builder.smearScalar(precision, left, vecType);
2874 else if (builder.isScalar(right))
2875 smearVec = builder.smearScalar(precision, right, vecType);
2876
2877 // do each vector op
2878 for (unsigned int c = 0; c < numCols; ++c) {
2879 std::vector<unsigned int> indexes;
2880 indexes.push_back(c);
2881 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2882 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2883 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2884 builder.setPrecision(results.back(), precision);
2885 }
2886
2887 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002888 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002889 }
2890 default:
2891 assert(0);
2892 return spv::NoResult;
2893 }
2894}
2895
Rex Xu04db3f52015-09-16 11:44:02 +08002896spv::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 -06002897{
2898 spv::Op unaryOp = spv::OpNop;
2899 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002900 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002901 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002902
2903 switch (op) {
2904 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002905 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002906 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002907 if (builder.isMatrixType(typeId))
2908 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2909 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002910 unaryOp = spv::OpSNegate;
2911 break;
2912
2913 case glslang::EOpLogicalNot:
2914 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002915 unaryOp = spv::OpLogicalNot;
2916 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002917 case glslang::EOpBitwiseNot:
2918 unaryOp = spv::OpNot;
2919 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002920
John Kessenich140f3df2015-06-26 16:58:36 -06002921 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002922 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002923 break;
2924 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002925 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002926 break;
2927 case glslang::EOpTranspose:
2928 unaryOp = spv::OpTranspose;
2929 break;
2930
2931 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002932 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002933 break;
2934 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002935 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002936 break;
2937 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002938 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002939 break;
2940 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002941 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002942 break;
2943 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002944 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002945 break;
2946 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002947 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002948 break;
2949 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002950 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002951 break;
2952 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002953 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002954 break;
2955
2956 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002957 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002958 break;
2959 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002960 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002961 break;
2962 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002963 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002964 break;
2965 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002966 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002967 break;
2968 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002969 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002970 break;
2971 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002972 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002973 break;
2974
2975 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002976 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002977 break;
2978 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002979 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002980 break;
2981
2982 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002983 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002984 break;
2985 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002986 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002987 break;
2988 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002989 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002990 break;
2991 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002992 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002993 break;
2994 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002995 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002996 break;
2997 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002998 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002999 break;
3000
3001 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003002 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003003 break;
3004 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003005 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003006 break;
3007 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003008 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003009 break;
3010 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003011 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003012 break;
3013 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003014 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003015 break;
3016 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003017 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003018 break;
3019
3020 case glslang::EOpIsNan:
3021 unaryOp = spv::OpIsNan;
3022 break;
3023 case glslang::EOpIsInf:
3024 unaryOp = spv::OpIsInf;
3025 break;
3026
Rex Xucbc426e2015-12-15 16:03:10 +08003027 case glslang::EOpFloatBitsToInt:
3028 case glslang::EOpFloatBitsToUint:
3029 case glslang::EOpIntBitsToFloat:
3030 case glslang::EOpUintBitsToFloat:
3031 unaryOp = spv::OpBitcast;
3032 break;
3033
John Kessenich140f3df2015-06-26 16:58:36 -06003034 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003035 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003036 break;
3037 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003038 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003039 break;
3040 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003041 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003042 break;
3043 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003044 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003045 break;
3046 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 break;
3049 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003050 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003052 case glslang::EOpPackSnorm4x8:
3053 libCall = spv::GLSLstd450PackSnorm4x8;
3054 break;
3055 case glslang::EOpUnpackSnorm4x8:
3056 libCall = spv::GLSLstd450UnpackSnorm4x8;
3057 break;
3058 case glslang::EOpPackUnorm4x8:
3059 libCall = spv::GLSLstd450PackUnorm4x8;
3060 break;
3061 case glslang::EOpUnpackUnorm4x8:
3062 libCall = spv::GLSLstd450UnpackUnorm4x8;
3063 break;
3064 case glslang::EOpPackDouble2x32:
3065 libCall = spv::GLSLstd450PackDouble2x32;
3066 break;
3067 case glslang::EOpUnpackDouble2x32:
3068 libCall = spv::GLSLstd450UnpackDouble2x32;
3069 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003070
3071 case glslang::EOpDPdx:
3072 unaryOp = spv::OpDPdx;
3073 break;
3074 case glslang::EOpDPdy:
3075 unaryOp = spv::OpDPdy;
3076 break;
3077 case glslang::EOpFwidth:
3078 unaryOp = spv::OpFwidth;
3079 break;
3080 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003081 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003082 unaryOp = spv::OpDPdxFine;
3083 break;
3084 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003085 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003086 unaryOp = spv::OpDPdyFine;
3087 break;
3088 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003089 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003090 unaryOp = spv::OpFwidthFine;
3091 break;
3092 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003093 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003094 unaryOp = spv::OpDPdxCoarse;
3095 break;
3096 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003097 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003098 unaryOp = spv::OpDPdyCoarse;
3099 break;
3100 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003101 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003102 unaryOp = spv::OpFwidthCoarse;
3103 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003104 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003105 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003106 libCall = spv::GLSLstd450InterpolateAtCentroid;
3107 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003108 case glslang::EOpAny:
3109 unaryOp = spv::OpAny;
3110 break;
3111 case glslang::EOpAll:
3112 unaryOp = spv::OpAll;
3113 break;
3114
3115 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003116 if (isFloat)
3117 libCall = spv::GLSLstd450FAbs;
3118 else
3119 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003120 break;
3121 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003122 if (isFloat)
3123 libCall = spv::GLSLstd450FSign;
3124 else
3125 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003126 break;
3127
John Kessenichfc51d282015-08-19 13:34:18 -06003128 case glslang::EOpAtomicCounterIncrement:
3129 case glslang::EOpAtomicCounterDecrement:
3130 case glslang::EOpAtomicCounter:
3131 {
3132 // Handle all of the atomics in one place, in createAtomicOperation()
3133 std::vector<spv::Id> operands;
3134 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003135 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003136 }
3137
John Kessenichfc51d282015-08-19 13:34:18 -06003138 case glslang::EOpBitFieldReverse:
3139 unaryOp = spv::OpBitReverse;
3140 break;
3141 case glslang::EOpBitCount:
3142 unaryOp = spv::OpBitCount;
3143 break;
3144 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003145 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003146 break;
3147 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003148 if (isUnsigned)
3149 libCall = spv::GLSLstd450FindUMsb;
3150 else
3151 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003152 break;
3153
John Kessenich140f3df2015-06-26 16:58:36 -06003154 default:
3155 return 0;
3156 }
3157
3158 spv::Id id;
3159 if (libCall >= 0) {
3160 std::vector<spv::Id> args;
3161 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003162 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003163 } else
3164 id = builder.createUnaryOp(unaryOp, typeId, operand);
3165
John Kessenich32cfd492016-02-02 12:37:46 -07003166 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003167}
3168
John Kessenich7a53f762016-01-20 11:19:27 -07003169// Create a unary operation on a matrix
3170spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3171{
3172 // Handle unary operations vector by vector.
3173 // The result type is the same type as the original type.
3174 // The algorithm is to:
3175 // - break the matrix into vectors
3176 // - apply the operation to each vector
3177 // - make a matrix out the vector results
3178
3179 // get the types sorted out
3180 int numCols = builder.getNumColumns(operand);
3181 int numRows = builder.getNumRows(operand);
3182 spv::Id scalarType = builder.getScalarTypeId(typeId);
3183 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3184 std::vector<spv::Id> results;
3185
3186 // do each vector op
3187 for (int c = 0; c < numCols; ++c) {
3188 std::vector<unsigned int> indexes;
3189 indexes.push_back(c);
3190 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3191 results.push_back(builder.createUnaryOp(op, vecType, vec));
3192 builder.setPrecision(results.back(), precision);
3193 }
3194
3195 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003196 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003197}
3198
John Kessenich140f3df2015-06-26 16:58:36 -06003199spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3200{
3201 spv::Op convOp = spv::OpNop;
3202 spv::Id zero = 0;
3203 spv::Id one = 0;
3204
3205 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3206
3207 switch (op) {
3208 case glslang::EOpConvIntToBool:
3209 case glslang::EOpConvUintToBool:
3210 zero = builder.makeUintConstant(0);
3211 zero = makeSmearedConstant(zero, vectorSize);
3212 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3213
3214 case glslang::EOpConvFloatToBool:
3215 zero = builder.makeFloatConstant(0.0F);
3216 zero = makeSmearedConstant(zero, vectorSize);
3217 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3218
3219 case glslang::EOpConvDoubleToBool:
3220 zero = builder.makeDoubleConstant(0.0);
3221 zero = makeSmearedConstant(zero, vectorSize);
3222 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3223
3224 case glslang::EOpConvBoolToFloat:
3225 convOp = spv::OpSelect;
3226 zero = builder.makeFloatConstant(0.0);
3227 one = builder.makeFloatConstant(1.0);
3228 break;
3229 case glslang::EOpConvBoolToDouble:
3230 convOp = spv::OpSelect;
3231 zero = builder.makeDoubleConstant(0.0);
3232 one = builder.makeDoubleConstant(1.0);
3233 break;
3234 case glslang::EOpConvBoolToInt:
3235 zero = builder.makeIntConstant(0);
3236 one = builder.makeIntConstant(1);
3237 convOp = spv::OpSelect;
3238 break;
3239 case glslang::EOpConvBoolToUint:
3240 zero = builder.makeUintConstant(0);
3241 one = builder.makeUintConstant(1);
3242 convOp = spv::OpSelect;
3243 break;
3244
3245 case glslang::EOpConvIntToFloat:
3246 case glslang::EOpConvIntToDouble:
3247 convOp = spv::OpConvertSToF;
3248 break;
3249
3250 case glslang::EOpConvUintToFloat:
3251 case glslang::EOpConvUintToDouble:
3252 convOp = spv::OpConvertUToF;
3253 break;
3254
3255 case glslang::EOpConvDoubleToFloat:
3256 case glslang::EOpConvFloatToDouble:
3257 convOp = spv::OpFConvert;
3258 break;
3259
3260 case glslang::EOpConvFloatToInt:
3261 case glslang::EOpConvDoubleToInt:
3262 convOp = spv::OpConvertFToS;
3263 break;
3264
3265 case glslang::EOpConvUintToInt:
3266 case glslang::EOpConvIntToUint:
3267 convOp = spv::OpBitcast;
3268 break;
3269
3270 case glslang::EOpConvFloatToUint:
3271 case glslang::EOpConvDoubleToUint:
3272 convOp = spv::OpConvertFToU;
3273 break;
3274 default:
3275 break;
3276 }
3277
3278 spv::Id result = 0;
3279 if (convOp == spv::OpNop)
3280 return result;
3281
3282 if (convOp == spv::OpSelect) {
3283 zero = makeSmearedConstant(zero, vectorSize);
3284 one = makeSmearedConstant(one, vectorSize);
3285 result = builder.createTriOp(convOp, destType, operand, one, zero);
3286 } else
3287 result = builder.createUnaryOp(convOp, destType, operand);
3288
John Kessenich32cfd492016-02-02 12:37:46 -07003289 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003290}
3291
3292spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3293{
3294 if (vectorSize == 0)
3295 return constant;
3296
3297 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3298 std::vector<spv::Id> components;
3299 for (int c = 0; c < vectorSize; ++c)
3300 components.push_back(constant);
3301 return builder.makeCompositeConstant(vectorTypeId, components);
3302}
3303
John Kessenich426394d2015-07-23 10:22:48 -06003304// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003305spv::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 -06003306{
3307 spv::Op opCode = spv::OpNop;
3308
3309 switch (op) {
3310 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003311 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003312 opCode = spv::OpAtomicIAdd;
3313 break;
3314 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003315 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003316 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003317 break;
3318 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003319 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003320 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003321 break;
3322 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003323 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003324 opCode = spv::OpAtomicAnd;
3325 break;
3326 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003327 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003328 opCode = spv::OpAtomicOr;
3329 break;
3330 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003331 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003332 opCode = spv::OpAtomicXor;
3333 break;
3334 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003335 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003336 opCode = spv::OpAtomicExchange;
3337 break;
3338 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003339 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003340 opCode = spv::OpAtomicCompareExchange;
3341 break;
3342 case glslang::EOpAtomicCounterIncrement:
3343 opCode = spv::OpAtomicIIncrement;
3344 break;
3345 case glslang::EOpAtomicCounterDecrement:
3346 opCode = spv::OpAtomicIDecrement;
3347 break;
3348 case glslang::EOpAtomicCounter:
3349 opCode = spv::OpAtomicLoad;
3350 break;
3351 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003352 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003353 break;
3354 }
3355
3356 // Sort out the operands
3357 // - mapping from glslang -> SPV
3358 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003359 // - compare-exchange swaps the value and comparator
3360 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003361 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3362 auto opIt = operands.begin(); // walk the glslang operands
3363 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003364 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3365 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3366 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003367 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3368 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003369 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003370 spvAtomicOperands.push_back(*(opIt + 1));
3371 spvAtomicOperands.push_back(*opIt);
3372 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003373 }
John Kessenich426394d2015-07-23 10:22:48 -06003374
John Kessenich3e60a6f2015-09-14 22:45:16 -06003375 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003376 for (; opIt != operands.end(); ++opIt)
3377 spvAtomicOperands.push_back(*opIt);
3378
3379 return builder.createOp(opCode, typeId, spvAtomicOperands);
3380}
3381
John Kessenich5e4b1242015-08-06 22:53:06 -06003382spv::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 -06003383{
John Kessenich5e4b1242015-08-06 22:53:06 -06003384 bool isUnsigned = typeProxy == glslang::EbtUint;
3385 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3386
John Kessenich140f3df2015-06-26 16:58:36 -06003387 spv::Op opCode = spv::OpNop;
3388 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003389 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003390 spv::Id typeId0 = 0;
3391 if (consumedOperands > 0)
3392 typeId0 = builder.getTypeId(operands[0]);
3393 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003394
3395 switch (op) {
3396 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003397 if (isFloat)
3398 libCall = spv::GLSLstd450FMin;
3399 else if (isUnsigned)
3400 libCall = spv::GLSLstd450UMin;
3401 else
3402 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003403 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003404 break;
3405 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003409 if (isFloat)
3410 libCall = spv::GLSLstd450FMax;
3411 else if (isUnsigned)
3412 libCall = spv::GLSLstd450UMax;
3413 else
3414 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003415 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003416 break;
3417 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003418 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003419 break;
3420 case glslang::EOpDot:
3421 opCode = spv::OpDot;
3422 break;
3423 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003424 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003425 break;
3426
3427 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003428 if (isFloat)
3429 libCall = spv::GLSLstd450FClamp;
3430 else if (isUnsigned)
3431 libCall = spv::GLSLstd450UClamp;
3432 else
3433 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003434 builder.promoteScalar(precision, operands.front(), operands[1]);
3435 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003436 break;
3437 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003438 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3439 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003440 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003441 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003442 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003443 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003444 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003445 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003446 break;
3447 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003448 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003449 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003450 break;
3451 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003452 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003453 builder.promoteScalar(precision, operands[0], operands[2]);
3454 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003455 break;
3456
3457 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003458 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003459 break;
3460 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003461 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003462 break;
3463 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003464 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003465 break;
3466 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003467 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003468 break;
3469 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003470 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003471 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003472 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003473 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003474 libCall = spv::GLSLstd450InterpolateAtSample;
3475 break;
3476 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003477 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003478 libCall = spv::GLSLstd450InterpolateAtOffset;
3479 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003480 case glslang::EOpAddCarry:
3481 opCode = spv::OpIAddCarry;
3482 typeId = builder.makeStructResultType(typeId0, typeId0);
3483 consumedOperands = 2;
3484 break;
3485 case glslang::EOpSubBorrow:
3486 opCode = spv::OpISubBorrow;
3487 typeId = builder.makeStructResultType(typeId0, typeId0);
3488 consumedOperands = 2;
3489 break;
3490 case glslang::EOpUMulExtended:
3491 opCode = spv::OpUMulExtended;
3492 typeId = builder.makeStructResultType(typeId0, typeId0);
3493 consumedOperands = 2;
3494 break;
3495 case glslang::EOpIMulExtended:
3496 opCode = spv::OpSMulExtended;
3497 typeId = builder.makeStructResultType(typeId0, typeId0);
3498 consumedOperands = 2;
3499 break;
3500 case glslang::EOpBitfieldExtract:
3501 if (isUnsigned)
3502 opCode = spv::OpBitFieldUExtract;
3503 else
3504 opCode = spv::OpBitFieldSExtract;
3505 break;
3506 case glslang::EOpBitfieldInsert:
3507 opCode = spv::OpBitFieldInsert;
3508 break;
3509
3510 case glslang::EOpFma:
3511 libCall = spv::GLSLstd450Fma;
3512 break;
3513 case glslang::EOpFrexp:
3514 libCall = spv::GLSLstd450FrexpStruct;
3515 if (builder.getNumComponents(operands[0]) == 1)
3516 frexpIntType = builder.makeIntegerType(32, true);
3517 else
3518 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3519 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3520 consumedOperands = 1;
3521 break;
3522 case glslang::EOpLdexp:
3523 libCall = spv::GLSLstd450Ldexp;
3524 break;
3525
John Kessenich140f3df2015-06-26 16:58:36 -06003526 default:
3527 return 0;
3528 }
3529
3530 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003531 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003532 // Use an extended instruction from the standard library.
3533 // Construct the call arguments, without modifying the original operands vector.
3534 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3535 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003536 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003537 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003538 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003539 case 0:
3540 // should all be handled by visitAggregate and createNoArgOperation
3541 assert(0);
3542 return 0;
3543 case 1:
3544 // should all be handled by createUnaryOperation
3545 assert(0);
3546 return 0;
3547 case 2:
3548 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3549 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003550 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003551 // anything 3 or over doesn't have l-value operands, so all should be consumed
3552 assert(consumedOperands == operands.size());
3553 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003554 break;
3555 }
3556 }
3557
John Kessenich55e7d112015-11-15 21:33:39 -07003558 // Decode the return types that were structures
3559 switch (op) {
3560 case glslang::EOpAddCarry:
3561 case glslang::EOpSubBorrow:
3562 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3563 id = builder.createCompositeExtract(id, typeId0, 0);
3564 break;
3565 case glslang::EOpUMulExtended:
3566 case glslang::EOpIMulExtended:
3567 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3568 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3569 break;
3570 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003571 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003572 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3573 id = builder.createCompositeExtract(id, typeId0, 0);
3574 break;
3575 default:
3576 break;
3577 }
3578
John Kessenich32cfd492016-02-02 12:37:46 -07003579 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003580}
3581
3582// Intrinsics with no arguments, no return value, and no precision.
3583spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3584{
3585 // TODO: get the barrier operands correct
3586
3587 switch (op) {
3588 case glslang::EOpEmitVertex:
3589 builder.createNoResultOp(spv::OpEmitVertex);
3590 return 0;
3591 case glslang::EOpEndPrimitive:
3592 builder.createNoResultOp(spv::OpEndPrimitive);
3593 return 0;
3594 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003595 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3596 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003597 return 0;
3598 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003599 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003600 return 0;
3601 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003602 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003603 return 0;
3604 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003605 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003606 return 0;
3607 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003608 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003609 return 0;
3610 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003611 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003612 return 0;
3613 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003614 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003615 return 0;
3616 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003617 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003618 return 0;
3619 }
3620}
3621
3622spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3623{
John Kessenich2f273362015-07-18 22:34:27 -06003624 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003625 spv::Id id;
3626 if (symbolValues.end() != iter) {
3627 id = iter->second;
3628 return id;
3629 }
3630
3631 // it was not found, create it
3632 id = createSpvVariable(symbol);
3633 symbolValues[symbol->getId()] = id;
3634
3635 if (! symbol->getType().isStruct()) {
3636 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003637 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003638 if (symbol->getType().getQualifier().hasSpecConstantId())
3639 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003640 if (symbol->getQualifier().hasLocation())
3641 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3642 if (symbol->getQualifier().hasIndex())
3643 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3644 if (symbol->getQualifier().hasComponent())
3645 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3646 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003647 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003648 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003649 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003650 if (symbol->getQualifier().hasXfbBuffer())
3651 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3652 if (symbol->getQualifier().hasXfbOffset())
3653 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3654 }
3655 }
3656
John Kesseniche0b6cad2015-12-24 10:30:13 -07003657 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003658 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003659 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003660 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003661 }
John Kessenich140f3df2015-06-26 16:58:36 -06003662 if (symbol->getQualifier().hasSet())
3663 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003664 else if (IsDescriptorResource(symbol->getType())) {
3665 // default to 0
3666 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3667 }
John Kessenich140f3df2015-06-26 16:58:36 -06003668 if (symbol->getQualifier().hasBinding())
3669 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003670 if (symbol->getQualifier().hasAttachment())
3671 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003672 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003673 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003674 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003675 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003676 if (symbol->getQualifier().hasXfbBuffer())
3677 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3678 }
3679
Rex Xu1da878f2016-02-21 20:59:01 +08003680 if (symbol->getType().isImage()) {
3681 std::vector<spv::Decoration> memory;
3682 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3683 for (unsigned int i = 0; i < memory.size(); ++i)
3684 addDecoration(id, memory[i]);
3685 }
3686
John Kessenich140f3df2015-06-26 16:58:36 -06003687 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003688 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003689 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003690 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003691
John Kessenich140f3df2015-06-26 16:58:36 -06003692 return id;
3693}
3694
John Kessenich55e7d112015-11-15 21:33:39 -07003695// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003696void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3697{
3698 if (dec != spv::BadValue)
3699 builder.addDecoration(id, dec);
3700}
3701
John Kessenich55e7d112015-11-15 21:33:39 -07003702// If 'dec' is valid, add a one-operand decoration to an object
3703void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3704{
3705 if (dec != spv::BadValue)
3706 builder.addDecoration(id, dec, value);
3707}
3708
3709// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003710void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3711{
3712 if (dec != spv::BadValue)
3713 builder.addMemberDecoration(id, (unsigned)member, dec);
3714}
3715
John Kessenich92187592016-02-01 13:45:25 -07003716// If 'dec' is valid, add a one-operand decoration to a struct member
3717void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3718{
3719 if (dec != spv::BadValue)
3720 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3721}
3722
John Kessenich55e7d112015-11-15 21:33:39 -07003723// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003724// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003725//
3726// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3727//
3728// Recursively walk the nodes. The nodes form a tree whose leaves are
3729// regular constants, which themselves are trees that createSpvConstant()
3730// recursively walks. So, this function walks the "top" of the tree:
3731// - emit specialization constant-building instructions for specConstant
3732// - when running into a non-spec-constant, switch to createSpvConstant()
3733spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3734{
John Kessenich7cc0e282016-03-20 00:46:02 -06003735 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003736
John Kessenich6c292d32016-02-15 20:58:50 -07003737 if (! node.getQualifier().specConstant) {
3738 // hand off to the non-spec-constant path
3739 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3740 int nextConst = 0;
3741 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3742 nextConst, false);
3743 }
3744
3745 // We now know we have a specialization constant to build
3746
3747 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3748 // this is a direct literal assigned to a layout(constant_id=) declaration
3749 int nextConst = 0;
3750 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3751 nextConst, true);
3752 } else {
3753 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3754 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3755 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3756 std::vector<spv::Id> dimConstId;
3757 for (int dim = 0; dim < 3; ++dim) {
3758 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3759 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3760 if (specConst)
3761 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3762 }
3763 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3764 } else {
3765 spv::MissingFunctionality("specialization-constant expression trees");
3766 return spv::NoResult;
3767 }
3768 }
John Kessenich55e7d112015-11-15 21:33:39 -07003769}
3770
John Kessenich140f3df2015-06-26 16:58:36 -06003771// Use 'consts' as the flattened glslang source of scalar constants to recursively
3772// build the aggregate SPIR-V constant.
3773//
3774// If there are not enough elements present in 'consts', 0 will be substituted;
3775// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3776//
John Kessenich55e7d112015-11-15 21:33:39 -07003777spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003778{
3779 // vector of constants for SPIR-V
3780 std::vector<spv::Id> spvConsts;
3781
3782 // Type is used for struct and array constants
3783 spv::Id typeId = convertGlslangToSpvType(glslangType);
3784
3785 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003786 glslang::TType elementType(glslangType, 0);
3787 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003788 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003789 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003790 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003791 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003792 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003793 } else if (glslangType.getStruct()) {
3794 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3795 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003796 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003797 } else if (glslangType.isVector()) {
3798 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3799 bool zero = nextConst >= consts.size();
3800 switch (glslangType.getBasicType()) {
3801 case glslang::EbtInt:
3802 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3803 break;
3804 case glslang::EbtUint:
3805 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3806 break;
3807 case glslang::EbtFloat:
3808 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3809 break;
3810 case glslang::EbtDouble:
3811 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3812 break;
3813 case glslang::EbtBool:
3814 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3815 break;
3816 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003817 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003818 break;
3819 }
3820 ++nextConst;
3821 }
3822 } else {
3823 // we have a non-aggregate (scalar) constant
3824 bool zero = nextConst >= consts.size();
3825 spv::Id scalar = 0;
3826 switch (glslangType.getBasicType()) {
3827 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003828 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003829 break;
3830 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003831 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003832 break;
3833 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003834 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003835 break;
3836 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003837 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003838 break;
3839 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003840 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003841 break;
3842 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003843 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003844 break;
3845 }
3846 ++nextConst;
3847 return scalar;
3848 }
3849
3850 return builder.makeCompositeConstant(typeId, spvConsts);
3851}
3852
John Kessenich7c1aa102015-10-15 13:29:11 -06003853// Return true if the node is a constant or symbol whose reading has no
3854// non-trivial observable cost or effect.
3855bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3856{
3857 // don't know what this is
3858 if (node == nullptr)
3859 return false;
3860
3861 // a constant is safe
3862 if (node->getAsConstantUnion() != nullptr)
3863 return true;
3864
3865 // not a symbol means non-trivial
3866 if (node->getAsSymbolNode() == nullptr)
3867 return false;
3868
3869 // a symbol, depends on what's being read
3870 switch (node->getType().getQualifier().storage) {
3871 case glslang::EvqTemporary:
3872 case glslang::EvqGlobal:
3873 case glslang::EvqIn:
3874 case glslang::EvqInOut:
3875 case glslang::EvqConst:
3876 case glslang::EvqConstReadOnly:
3877 case glslang::EvqUniform:
3878 return true;
3879 default:
3880 return false;
3881 }
3882}
3883
3884// A node is trivial if it is a single operation with no side effects.
3885// Error on the side of saying non-trivial.
3886// Return true if trivial.
3887bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3888{
3889 if (node == nullptr)
3890 return false;
3891
3892 // symbols and constants are trivial
3893 if (isTrivialLeaf(node))
3894 return true;
3895
3896 // otherwise, it needs to be a simple operation or one or two leaf nodes
3897
3898 // not a simple operation
3899 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3900 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3901 if (binaryNode == nullptr && unaryNode == nullptr)
3902 return false;
3903
3904 // not on leaf nodes
3905 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3906 return false;
3907
3908 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3909 return false;
3910 }
3911
3912 switch (node->getAsOperator()->getOp()) {
3913 case glslang::EOpLogicalNot:
3914 case glslang::EOpConvIntToBool:
3915 case glslang::EOpConvUintToBool:
3916 case glslang::EOpConvFloatToBool:
3917 case glslang::EOpConvDoubleToBool:
3918 case glslang::EOpEqual:
3919 case glslang::EOpNotEqual:
3920 case glslang::EOpLessThan:
3921 case glslang::EOpGreaterThan:
3922 case glslang::EOpLessThanEqual:
3923 case glslang::EOpGreaterThanEqual:
3924 case glslang::EOpIndexDirect:
3925 case glslang::EOpIndexDirectStruct:
3926 case glslang::EOpLogicalXor:
3927 case glslang::EOpAny:
3928 case glslang::EOpAll:
3929 return true;
3930 default:
3931 return false;
3932 }
3933}
3934
3935// Emit short-circuiting code, where 'right' is never evaluated unless
3936// the left side is true (for &&) or false (for ||).
3937spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3938{
3939 spv::Id boolTypeId = builder.makeBoolType();
3940
3941 // emit left operand
3942 builder.clearAccessChain();
3943 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003944 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003945
3946 // Operands to accumulate OpPhi operands
3947 std::vector<spv::Id> phiOperands;
3948 // accumulate left operand's phi information
3949 phiOperands.push_back(leftId);
3950 phiOperands.push_back(builder.getBuildPoint()->getId());
3951
3952 // Make the two kinds of operation symmetric with a "!"
3953 // || => emit "if (! left) result = right"
3954 // && => emit "if ( left) result = right"
3955 //
3956 // TODO: this runtime "not" for || could be avoided by adding functionality
3957 // to 'builder' to have an "else" without an "then"
3958 if (op == glslang::EOpLogicalOr)
3959 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3960
3961 // make an "if" based on the left value
3962 spv::Builder::If ifBuilder(leftId, builder);
3963
3964 // emit right operand as the "then" part of the "if"
3965 builder.clearAccessChain();
3966 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003967 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003968
3969 // accumulate left operand's phi information
3970 phiOperands.push_back(rightId);
3971 phiOperands.push_back(builder.getBuildPoint()->getId());
3972
3973 // finish the "if"
3974 ifBuilder.makeEndIf();
3975
3976 // phi together the two results
3977 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3978}
3979
John Kessenich140f3df2015-06-26 16:58:36 -06003980}; // end anonymous namespace
3981
3982namespace glslang {
3983
John Kessenich68d78fd2015-07-12 19:28:10 -06003984void GetSpirvVersion(std::string& version)
3985{
John Kessenich9e55f632015-07-15 10:03:39 -06003986 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003987 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003988 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003989 version = buf;
3990}
3991
John Kessenich140f3df2015-06-26 16:58:36 -06003992// Write SPIR-V out to a binary file
3993void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3994{
3995 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003996 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003997 for (int i = 0; i < (int)spirv.size(); ++i) {
3998 unsigned int word = spirv[i];
3999 out.write((const char*)&word, 4);
4000 }
4001 out.close();
4002}
4003
4004//
4005// Set up the glslang traversal
4006//
4007void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4008{
4009 TIntermNode* root = intermediate.getTreeRoot();
4010
4011 if (root == 0)
4012 return;
4013
4014 glslang::GetThreadPoolAllocator().push();
4015
4016 TGlslangToSpvTraverser it(&intermediate);
4017
4018 root->traverse(&it);
4019
4020 it.dumpSpv(spirv);
4021
4022 glslang::GetThreadPoolAllocator().pop();
4023}
4024
4025}; // end namespace glslang