blob: 205e9247e17ccdc3c97f9870b3a0c977c7965f2b [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);
qining08408382016-03-21 09:51:37 -0400131 spv::Id createSpvConstant(const glslang::TIntermTyped&);
132 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
qining13545202016-03-21 09:51:37 -0400133 spv::Id createSpvConstantFromConstSubTree(glslang::TIntermTyped* subTree);
John Kessenich7c1aa102015-10-15 13:29:11 -0600134 bool isTrivialLeaf(const glslang::TIntermTyped* node);
135 bool isTrivial(const glslang::TIntermTyped* node);
136 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600137
138 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700139 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600140 int sequenceDepth;
141
142 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
143 spv::Builder builder;
144 bool inMain;
145 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700146 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 -0700147 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600148 const glslang::TIntermediate* glslangIntermediate;
149 spv::Id stdBuiltins;
150
John Kessenich2f273362015-07-18 22:34:27 -0600151 std::unordered_map<int, spv::Id> symbolValues;
152 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
153 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700154 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600155 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 -0600156 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600157};
158
159//
160// Helper functions for translating glslang representations to SPIR-V enumerants.
161//
162
163// Translate glslang profile to SPIR-V source language.
164spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
165{
166 switch (profile) {
167 case ENoProfile:
168 case ECoreProfile:
169 case ECompatibilityProfile:
170 return spv::SourceLanguageGLSL;
171 case EEsProfile:
172 return spv::SourceLanguageESSL;
173 default:
174 return spv::SourceLanguageUnknown;
175 }
176}
177
178// Translate glslang language (stage) to SPIR-V execution model.
179spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
180{
181 switch (stage) {
182 case EShLangVertex: return spv::ExecutionModelVertex;
183 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
184 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
185 case EShLangGeometry: return spv::ExecutionModelGeometry;
186 case EShLangFragment: return spv::ExecutionModelFragment;
187 case EShLangCompute: return spv::ExecutionModelGLCompute;
188 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700189 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600190 return spv::ExecutionModelFragment;
191 }
192}
193
194// Translate glslang type to SPIR-V storage class.
195spv::StorageClass TranslateStorageClass(const glslang::TType& type)
196{
197 if (type.getQualifier().isPipeInput())
198 return spv::StorageClassInput;
199 else if (type.getQualifier().isPipeOutput())
200 return spv::StorageClassOutput;
201 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700202 if (type.getQualifier().layoutPushConstant)
203 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600204 if (type.getBasicType() == glslang::EbtBlock)
205 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800206 else if (type.getBasicType() == glslang::EbtAtomicUint)
207 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600208 else
209 return spv::StorageClassUniformConstant;
210 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
211 } else {
212 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700213 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
214 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600215 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
216 case glslang::EvqTemporary: return spv::StorageClassFunction;
217 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700218 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600219 return spv::StorageClassFunction;
220 }
221 }
222}
223
224// Translate glslang sampler type to SPIR-V dimensionality.
225spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
226{
227 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700228 case glslang::Esd1D: return spv::Dim1D;
229 case glslang::Esd2D: return spv::Dim2D;
230 case glslang::Esd3D: return spv::Dim3D;
231 case glslang::EsdCube: return spv::DimCube;
232 case glslang::EsdRect: return spv::DimRect;
233 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700234 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600235 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700236 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600237 return spv::Dim2D;
238 }
239}
240
241// Translate glslang type to SPIR-V precision decorations.
242spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
243{
244 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700245 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600246 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600247 default:
248 return spv::NoPrecision;
249 }
250}
251
252// Translate glslang type to SPIR-V block decorations.
253spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
254{
255 if (type.getBasicType() == glslang::EbtBlock) {
256 switch (type.getQualifier().storage) {
257 case glslang::EvqUniform: return spv::DecorationBlock;
258 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
259 case glslang::EvqVaryingIn: return spv::DecorationBlock;
260 case glslang::EvqVaryingOut: return spv::DecorationBlock;
261 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700262 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600263 break;
264 }
265 }
266
267 return (spv::Decoration)spv::BadValue;
268}
269
Rex Xu1da878f2016-02-21 20:59:01 +0800270// Translate glslang type to SPIR-V memory decorations.
271void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
272{
273 if (qualifier.coherent)
274 memory.push_back(spv::DecorationCoherent);
275 if (qualifier.volatil)
276 memory.push_back(spv::DecorationVolatile);
277 if (qualifier.restrict)
278 memory.push_back(spv::DecorationRestrict);
279 if (qualifier.readonly)
280 memory.push_back(spv::DecorationNonWritable);
281 if (qualifier.writeonly)
282 memory.push_back(spv::DecorationNonReadable);
283}
284
John Kessenich140f3df2015-06-26 16:58:36 -0600285// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700286spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600287{
288 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700289 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600290 case glslang::ElmRowMajor:
291 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700292 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600293 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700294 default:
295 // opaque layouts don't need a majorness
296 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600297 }
298 } else {
299 switch (type.getBasicType()) {
300 default:
301 return (spv::Decoration)spv::BadValue;
302 break;
303 case glslang::EbtBlock:
304 switch (type.getQualifier().storage) {
305 case glslang::EvqUniform:
306 case glslang::EvqBuffer:
307 switch (type.getQualifier().layoutPacking) {
308 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600309 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
310 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600311 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600312 }
313 case glslang::EvqVaryingIn:
314 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700315 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600316 return (spv::Decoration)spv::BadValue;
317 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700318 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600319 return (spv::Decoration)spv::BadValue;
320 }
321 }
322 }
323}
324
325// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700326// Returns spv::Decoration(spv::BadValue) when no decoration
327// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700328spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600329{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700330 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700331 // Smooth decoration doesn't exist in SPIR-V 1.0
332 return (spv::Decoration)spv::BadValue;
333 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700334 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700335 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700336 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600337 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700338 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600339 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700340 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600341 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700342 else if (qualifier.sample) {
343 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600344 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700345 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600346 return (spv::Decoration)spv::BadValue;
347}
348
John Kessenich92187592016-02-01 13:45:25 -0700349// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700350spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600351{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700352 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600353 return spv::DecorationInvariant;
354 else
355 return (spv::Decoration)spv::BadValue;
356}
357
358// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700359spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600360{
361 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700362 case glslang::EbvPointSize:
363 switch (glslangIntermediate->getStage()) {
364 case EShLangGeometry:
365 builder.addCapability(spv::CapabilityGeometryPointSize);
366 break;
367 case EShLangTessControl:
368 case EShLangTessEvaluation:
369 builder.addCapability(spv::CapabilityTessellationPointSize);
370 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100371 default:
372 break;
John Kessenich92187592016-02-01 13:45:25 -0700373 }
374 return spv::BuiltInPointSize;
375
376 case glslang::EbvClipDistance:
377 builder.addCapability(spv::CapabilityClipDistance);
378 return spv::BuiltInClipDistance;
379
380 case glslang::EbvCullDistance:
381 builder.addCapability(spv::CapabilityCullDistance);
382 return spv::BuiltInCullDistance;
383
384 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500385 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700386 return spv::BuiltInViewportIndex;
387
John Kessenich5e801132016-02-15 11:09:46 -0700388 case glslang::EbvSampleId:
389 builder.addCapability(spv::CapabilitySampleRateShading);
390 return spv::BuiltInSampleId;
391
392 case glslang::EbvSamplePosition:
393 builder.addCapability(spv::CapabilitySampleRateShading);
394 return spv::BuiltInSamplePosition;
395
396 case glslang::EbvSampleMask:
397 builder.addCapability(spv::CapabilitySampleRateShading);
398 return spv::BuiltInSampleMask;
399
John Kessenich140f3df2015-06-26 16:58:36 -0600400 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600401 case glslang::EbvVertexId: return spv::BuiltInVertexId;
402 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700403 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
404 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600405 case glslang::EbvBaseVertex:
406 case glslang::EbvBaseInstance:
407 case glslang::EbvDrawId:
408 // TODO: Add SPIR-V builtin ID.
409 spv::MissingFunctionality("Draw parameters");
410 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600411 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
412 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
413 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600414 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
415 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
416 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
417 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
418 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
419 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
420 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600421 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
422 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
423 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
424 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
425 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
426 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
427 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
428 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
429 default: return (spv::BuiltIn)spv::BadValue;
430 }
431}
432
Rex Xufc618912015-09-09 16:42:49 +0800433// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700434spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800435{
436 assert(type.getBasicType() == glslang::EbtSampler);
437
John Kessenich5d0fa972016-02-15 11:57:00 -0700438 // Check for capabilities
439 switch (type.getQualifier().layoutFormat) {
440 case glslang::ElfRg32f:
441 case glslang::ElfRg16f:
442 case glslang::ElfR11fG11fB10f:
443 case glslang::ElfR16f:
444 case glslang::ElfRgba16:
445 case glslang::ElfRgb10A2:
446 case glslang::ElfRg16:
447 case glslang::ElfRg8:
448 case glslang::ElfR16:
449 case glslang::ElfR8:
450 case glslang::ElfRgba16Snorm:
451 case glslang::ElfRg16Snorm:
452 case glslang::ElfRg8Snorm:
453 case glslang::ElfR16Snorm:
454 case glslang::ElfR8Snorm:
455
456 case glslang::ElfRg32i:
457 case glslang::ElfRg16i:
458 case glslang::ElfRg8i:
459 case glslang::ElfR16i:
460 case glslang::ElfR8i:
461
462 case glslang::ElfRgb10a2ui:
463 case glslang::ElfRg32ui:
464 case glslang::ElfRg16ui:
465 case glslang::ElfRg8ui:
466 case glslang::ElfR16ui:
467 case glslang::ElfR8ui:
468 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
469 break;
470
471 default:
472 break;
473 }
474
475 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800476 switch (type.getQualifier().layoutFormat) {
477 case glslang::ElfNone: return spv::ImageFormatUnknown;
478 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
479 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
480 case glslang::ElfR32f: return spv::ImageFormatR32f;
481 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
482 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
483 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
484 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
485 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
486 case glslang::ElfR16f: return spv::ImageFormatR16f;
487 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
488 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
489 case glslang::ElfRg16: return spv::ImageFormatRg16;
490 case glslang::ElfRg8: return spv::ImageFormatRg8;
491 case glslang::ElfR16: return spv::ImageFormatR16;
492 case glslang::ElfR8: return spv::ImageFormatR8;
493 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
494 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
495 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
496 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
497 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
498 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
499 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
500 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
501 case glslang::ElfR32i: return spv::ImageFormatR32i;
502 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
503 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
504 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
505 case glslang::ElfR16i: return spv::ImageFormatR16i;
506 case glslang::ElfR8i: return spv::ImageFormatR8i;
507 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
508 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
509 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
510 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
511 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
512 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
513 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
514 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
515 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
516 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
517 default: return (spv::ImageFormat)spv::BadValue;
518 }
519}
520
John Kessenich6c292d32016-02-15 20:58:50 -0700521// Return whether or not the given type is something that should be tied to a
522// descriptor set.
523bool IsDescriptorResource(const glslang::TType& type)
524{
John Kessenichf7497e22016-03-08 21:36:22 -0700525 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700526 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700527 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700528
529 // non block...
530 // basically samplerXXX/subpass/sampler/texture are all included
531 // if they are the global-scope-class, not the function parameter
532 // (or local, if they ever exist) class.
533 if (type.getBasicType() == glslang::EbtSampler)
534 return type.getQualifier().isUniformOrBuffer();
535
536 // None of the above.
537 return false;
538}
539
John Kesseniche0b6cad2015-12-24 10:30:13 -0700540void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
541{
542 if (child.layoutMatrix == glslang::ElmNone)
543 child.layoutMatrix = parent.layoutMatrix;
544
545 if (parent.invariant)
546 child.invariant = true;
547 if (parent.nopersp)
548 child.nopersp = true;
549 if (parent.flat)
550 child.flat = true;
551 if (parent.centroid)
552 child.centroid = true;
553 if (parent.patch)
554 child.patch = true;
555 if (parent.sample)
556 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800557 if (parent.coherent)
558 child.coherent = true;
559 if (parent.volatil)
560 child.volatil = true;
561 if (parent.restrict)
562 child.restrict = true;
563 if (parent.readonly)
564 child.readonly = true;
565 if (parent.writeonly)
566 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700567}
568
569bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
570{
John Kessenich7b9fa252016-01-21 18:56:57 -0700571 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700572 // - struct members can inherit from a struct declaration
573 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
574 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700575 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700576}
577
John Kessenich140f3df2015-06-26 16:58:36 -0600578//
579// Implement the TGlslangToSpvTraverser class.
580//
581
582TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
583 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700584 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600585 inMain(false), mainTerminated(false), linkageOnly(false),
586 glslangIntermediate(glslangIntermediate)
587{
588 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
589
590 builder.clearAccessChain();
591 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
592 stdBuiltins = builder.import("GLSL.std.450");
593 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
594 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700595 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600596
597 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600598 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
599 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600600 builder.addSourceExtension(it->c_str());
601
602 // Add the top-level modes for this shader.
603
John Kessenich92187592016-02-01 13:45:25 -0700604 if (glslangIntermediate->getXfbMode()) {
605 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600606 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700607 }
John Kessenich140f3df2015-06-26 16:58:36 -0600608
609 unsigned int mode;
610 switch (glslangIntermediate->getStage()) {
611 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600612 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600613 break;
614
615 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600616 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600617 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
618 break;
619
620 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600621 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600622 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700623 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
624 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
625 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600626 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600627 }
628 if (mode != spv::BadValue)
629 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
630
John Kesseniche6903322015-10-13 16:29:02 -0600631 switch (glslangIntermediate->getVertexSpacing()) {
632 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
633 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
634 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
635 default: mode = spv::BadValue; break;
636 }
637 if (mode != spv::BadValue)
638 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
639
640 switch (glslangIntermediate->getVertexOrder()) {
641 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
642 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
643 default: mode = spv::BadValue; break;
644 }
645 if (mode != spv::BadValue)
646 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
647
648 if (glslangIntermediate->getPointMode())
649 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600650 break;
651
652 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600653 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600654 switch (glslangIntermediate->getInputPrimitive()) {
655 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
656 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
657 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700658 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600659 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
660 default: mode = spv::BadValue; break;
661 }
662 if (mode != spv::BadValue)
663 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600664
John Kessenich140f3df2015-06-26 16:58:36 -0600665 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
666
667 switch (glslangIntermediate->getOutputPrimitive()) {
668 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
669 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
670 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
671 default: mode = spv::BadValue; break;
672 }
673 if (mode != spv::BadValue)
674 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
675 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
676 break;
677
678 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600679 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600680 if (glslangIntermediate->getPixelCenterInteger())
681 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600682
John Kessenich140f3df2015-06-26 16:58:36 -0600683 if (glslangIntermediate->getOriginUpperLeft())
684 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600685 else
686 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600687
688 if (glslangIntermediate->getEarlyFragmentTests())
689 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
690
691 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600692 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
693 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
694 default: mode = spv::BadValue; break;
695 }
696 if (mode != spv::BadValue)
697 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
698
699 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
700 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600701 break;
702
703 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600704 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600705 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
706 glslangIntermediate->getLocalSize(1),
707 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600708 break;
709
710 default:
711 break;
712 }
713
714}
715
John Kessenich7ba63412015-12-20 17:37:07 -0700716// Finish everything and dump
717void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
718{
719 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100720 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
721 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700722
qiningda397332016-03-09 19:54:03 -0500723 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700724 builder.dump(out);
725}
726
John Kessenich140f3df2015-06-26 16:58:36 -0600727TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
728{
729 if (! mainTerminated) {
730 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
731 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600732 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600733 }
734}
735
736//
737// Implement the traversal functions.
738//
739// Return true from interior nodes to have the external traversal
740// continue on to children. Return false if children were
741// already processed.
742//
743
744//
745// Symbols can turn into
746// - uniform/input reads
747// - output writes
748// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
749// - something simple that degenerates into the last bullet
750//
751void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
752{
753 // getSymbolId() will set up all the IO decorations on the first call.
754 // Formal function parameters were mapped during makeFunctions().
755 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700756
757 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
758 if (builder.isPointer(id)) {
759 spv::StorageClass sc = builder.getStorageClass(id);
760 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
761 iOSet.insert(id);
762 }
763
764 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700765 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600766 // Prepare to generate code for the access
767
768 // L-value chains will be computed left to right. We're on the symbol now,
769 // which is the left-most part of the access chain, so now is "clear" time,
770 // followed by setting the base.
771 builder.clearAccessChain();
772
773 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700774 // except for
775 // A) "const in" arguments to a function, which are an intermediate object.
776 // See comments in handleUserFunctionCall().
777 // B) Specialization constants (normal constant don't even come in as a variable),
778 // These are also pure R-values.
779 glslang::TQualifier qualifier = symbol->getQualifier();
780 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
781 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600782 builder.setAccessChainRValue(id);
783 else
784 builder.setAccessChainLValue(id);
785 }
786}
787
788bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
789{
790 // First, handle special cases
791 switch (node->getOp()) {
792 case glslang::EOpAssign:
793 case glslang::EOpAddAssign:
794 case glslang::EOpSubAssign:
795 case glslang::EOpMulAssign:
796 case glslang::EOpVectorTimesMatrixAssign:
797 case glslang::EOpVectorTimesScalarAssign:
798 case glslang::EOpMatrixTimesScalarAssign:
799 case glslang::EOpMatrixTimesMatrixAssign:
800 case glslang::EOpDivAssign:
801 case glslang::EOpModAssign:
802 case glslang::EOpAndAssign:
803 case glslang::EOpInclusiveOrAssign:
804 case glslang::EOpExclusiveOrAssign:
805 case glslang::EOpLeftShiftAssign:
806 case glslang::EOpRightShiftAssign:
807 // A bin-op assign "a += b" means the same thing as "a = a + b"
808 // where a is evaluated before b. For a simple assignment, GLSL
809 // says to evaluate the left before the right. So, always, left
810 // node then right node.
811 {
812 // get the left l-value, save it away
813 builder.clearAccessChain();
814 node->getLeft()->traverse(this);
815 spv::Builder::AccessChain lValue = builder.getAccessChain();
816
817 // evaluate the right
818 builder.clearAccessChain();
819 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700820 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600821
822 if (node->getOp() != glslang::EOpAssign) {
823 // the left is also an r-value
824 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700825 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600826
827 // do the operation
828 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
829 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
830 node->getType().getBasicType());
831
832 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700833 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600834 }
835
836 // store the result
837 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800838 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600839
840 // assignments are expressions having an rValue after they are evaluated...
841 builder.clearAccessChain();
842 builder.setAccessChainRValue(rValue);
843 }
844 return false;
845 case glslang::EOpIndexDirect:
846 case glslang::EOpIndexDirectStruct:
847 {
848 // Get the left part of the access chain.
849 node->getLeft()->traverse(this);
850
851 // Add the next element in the chain
852
John Kessenich55e7d112015-11-15 21:33:39 -0700853 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600854 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
855 // This may be, e.g., an anonymous block-member selection, which generally need
856 // index remapping due to hidden members in anonymous blocks.
857 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700858 assert(remapper.size() > 0);
859 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600860 }
861
862 if (! node->getLeft()->getType().isArray() &&
863 node->getLeft()->getType().isVector() &&
864 node->getOp() == glslang::EOpIndexDirect) {
865 // This is essentially a hard-coded vector swizzle of size 1,
866 // so short circuit the access-chain stuff with a swizzle.
867 std::vector<unsigned> swizzle;
868 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600869 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600870 } else {
871 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600872 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600873 }
874 }
875 return false;
876 case glslang::EOpIndexIndirect:
877 {
878 // Structure or array or vector indirection.
879 // Will use native SPIR-V access-chain for struct and array indirection;
880 // matrices are arrays of vectors, so will also work for a matrix.
881 // Will use the access chain's 'component' for variable index into a vector.
882
883 // This adapter is building access chains left to right.
884 // Set up the access chain to the left.
885 node->getLeft()->traverse(this);
886
887 // save it so that computing the right side doesn't trash it
888 spv::Builder::AccessChain partial = builder.getAccessChain();
889
890 // compute the next index in the chain
891 builder.clearAccessChain();
892 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700893 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600894
895 // restore the saved access chain
896 builder.setAccessChain(partial);
897
898 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600899 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600900 else
John Kessenichfa668da2015-09-13 14:46:30 -0600901 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600902 }
903 return false;
904 case glslang::EOpVectorSwizzle:
905 {
906 node->getLeft()->traverse(this);
907 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
908 std::vector<unsigned> swizzle;
909 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
910 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600911 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600912 }
913 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600914 case glslang::EOpLogicalOr:
915 case glslang::EOpLogicalAnd:
916 {
917
918 // These may require short circuiting, but can sometimes be done as straight
919 // binary operations. The right operand must be short circuited if it has
920 // side effects, and should probably be if it is complex.
921 if (isTrivial(node->getRight()->getAsTyped()))
922 break; // handle below as a normal binary operation
923 // otherwise, we need to do dynamic short circuiting on the right operand
924 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
925 builder.clearAccessChain();
926 builder.setAccessChainRValue(result);
927 }
928 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600929 default:
930 break;
931 }
932
933 // Assume generic binary op...
934
John Kessenich32cfd492016-02-02 12:37:46 -0700935 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600936 builder.clearAccessChain();
937 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700938 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600939
John Kessenich32cfd492016-02-02 12:37:46 -0700940 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600941 builder.clearAccessChain();
942 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700943 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600944
John Kessenich32cfd492016-02-02 12:37:46 -0700945 // get result
946 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
947 convertGlslangToSpvType(node->getType()), left, right,
948 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600949
John Kessenich50e57562015-12-21 21:21:11 -0700950 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600951 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700952 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700953 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600954 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600955 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600956 return false;
957 }
John Kessenich140f3df2015-06-26 16:58:36 -0600958}
959
960bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
961{
John Kessenichfc51d282015-08-19 13:34:18 -0600962 spv::Id result = spv::NoResult;
963
964 // try texturing first
965 result = createImageTextureFunctionCall(node);
966 if (result != spv::NoResult) {
967 builder.clearAccessChain();
968 builder.setAccessChainRValue(result);
969
970 return false; // done with this node
971 }
972
973 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600974
975 if (node->getOp() == glslang::EOpArrayLength) {
976 // Quite special; won't want to evaluate the operand.
977
978 // Normal .length() would have been constant folded by the front-end.
979 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600980 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600981 assert(node->getOperand()->getType().isRuntimeSizedArray());
982 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
983 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600984 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
985 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600986
987 builder.clearAccessChain();
988 builder.setAccessChainRValue(length);
989
990 return false;
991 }
992
John Kessenichfc51d282015-08-19 13:34:18 -0600993 // Start by evaluating the operand
994
John Kessenich140f3df2015-06-26 16:58:36 -0600995 builder.clearAccessChain();
996 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800997
Rex Xufc618912015-09-09 16:42:49 +0800998 spv::Id operand = spv::NoResult;
999
1000 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1001 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001002 node->getOp() == glslang::EOpAtomicCounter ||
1003 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001004 operand = builder.accessChainGetLValue(); // Special case l-value operands
1005 else
John Kessenich32cfd492016-02-02 12:37:46 -07001006 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001007
1008 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1009
1010 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001011 if (! result)
1012 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001013
1014 // if not, then possibly an operation
1015 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001016 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001017
1018 if (result) {
1019 builder.clearAccessChain();
1020 builder.setAccessChainRValue(result);
1021
1022 return false; // done with this node
1023 }
1024
1025 // it must be a special case, check...
1026 switch (node->getOp()) {
1027 case glslang::EOpPostIncrement:
1028 case glslang::EOpPostDecrement:
1029 case glslang::EOpPreIncrement:
1030 case glslang::EOpPreDecrement:
1031 {
1032 // we need the integer value "1" or the floating point "1.0" to add/subtract
1033 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1034 builder.makeFloatConstant(1.0F) :
1035 builder.makeIntConstant(1);
1036 glslang::TOperator op;
1037 if (node->getOp() == glslang::EOpPreIncrement ||
1038 node->getOp() == glslang::EOpPostIncrement)
1039 op = glslang::EOpAdd;
1040 else
1041 op = glslang::EOpSub;
1042
1043 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1044 convertGlslangToSpvType(node->getType()), operand, one,
1045 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001046 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001047
1048 // The result of operation is always stored, but conditionally the
1049 // consumed result. The consumed result is always an r-value.
1050 builder.accessChainStore(result);
1051 builder.clearAccessChain();
1052 if (node->getOp() == glslang::EOpPreIncrement ||
1053 node->getOp() == glslang::EOpPreDecrement)
1054 builder.setAccessChainRValue(result);
1055 else
1056 builder.setAccessChainRValue(operand);
1057 }
1058
1059 return false;
1060
1061 case glslang::EOpEmitStreamVertex:
1062 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1063 return false;
1064 case glslang::EOpEndStreamPrimitive:
1065 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1066 return false;
1067
1068 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001069 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001070 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001071 }
John Kessenich140f3df2015-06-26 16:58:36 -06001072}
1073
1074bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1075{
John Kessenichfc51d282015-08-19 13:34:18 -06001076 spv::Id result = spv::NoResult;
1077
1078 // try texturing
1079 result = createImageTextureFunctionCall(node);
1080 if (result != spv::NoResult) {
1081 builder.clearAccessChain();
1082 builder.setAccessChainRValue(result);
1083
1084 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001085 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001086 // "imageStore" is a special case, which has no result
1087 return false;
1088 }
John Kessenichfc51d282015-08-19 13:34:18 -06001089
John Kessenich140f3df2015-06-26 16:58:36 -06001090 glslang::TOperator binOp = glslang::EOpNull;
1091 bool reduceComparison = true;
1092 bool isMatrix = false;
1093 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001094 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001095
1096 assert(node->getOp());
1097
1098 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1099
1100 switch (node->getOp()) {
1101 case glslang::EOpSequence:
1102 {
1103 if (preVisit)
1104 ++sequenceDepth;
1105 else
1106 --sequenceDepth;
1107
1108 if (sequenceDepth == 1) {
1109 // If this is the parent node of all the functions, we want to see them
1110 // early, so all call points have actual SPIR-V functions to reference.
1111 // In all cases, still let the traverser visit the children for us.
1112 makeFunctions(node->getAsAggregate()->getSequence());
1113
1114 // Also, we want all globals initializers to go into the entry of main(), before
1115 // anything else gets there, so visit out of order, doing them all now.
1116 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1117
1118 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1119 // so do them manually.
1120 visitFunctions(node->getAsAggregate()->getSequence());
1121
1122 return false;
1123 }
1124
1125 return true;
1126 }
1127 case glslang::EOpLinkerObjects:
1128 {
1129 if (visit == glslang::EvPreVisit)
1130 linkageOnly = true;
1131 else
1132 linkageOnly = false;
1133
1134 return true;
1135 }
1136 case glslang::EOpComma:
1137 {
1138 // processing from left to right naturally leaves the right-most
1139 // lying around in the access chain
1140 glslang::TIntermSequence& glslangOperands = node->getSequence();
1141 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1142 glslangOperands[i]->traverse(this);
1143
1144 return false;
1145 }
1146 case glslang::EOpFunction:
1147 if (visit == glslang::EvPreVisit) {
1148 if (isShaderEntrypoint(node)) {
1149 inMain = true;
1150 builder.setBuildPoint(shaderEntry->getLastBlock());
1151 } else {
1152 handleFunctionEntry(node);
1153 }
1154 } else {
1155 if (inMain)
1156 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001157 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001158 inMain = false;
1159 }
1160
1161 return true;
1162 case glslang::EOpParameters:
1163 // Parameters will have been consumed by EOpFunction processing, but not
1164 // the body, so we still visited the function node's children, making this
1165 // child redundant.
1166 return false;
1167 case glslang::EOpFunctionCall:
1168 {
1169 if (node->isUserDefined())
1170 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001171 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1172 if (result) {
1173 builder.clearAccessChain();
1174 builder.setAccessChainRValue(result);
1175 } else
1176 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001177
1178 return false;
1179 }
1180 case glslang::EOpConstructMat2x2:
1181 case glslang::EOpConstructMat2x3:
1182 case glslang::EOpConstructMat2x4:
1183 case glslang::EOpConstructMat3x2:
1184 case glslang::EOpConstructMat3x3:
1185 case glslang::EOpConstructMat3x4:
1186 case glslang::EOpConstructMat4x2:
1187 case glslang::EOpConstructMat4x3:
1188 case glslang::EOpConstructMat4x4:
1189 case glslang::EOpConstructDMat2x2:
1190 case glslang::EOpConstructDMat2x3:
1191 case glslang::EOpConstructDMat2x4:
1192 case glslang::EOpConstructDMat3x2:
1193 case glslang::EOpConstructDMat3x3:
1194 case glslang::EOpConstructDMat3x4:
1195 case glslang::EOpConstructDMat4x2:
1196 case glslang::EOpConstructDMat4x3:
1197 case glslang::EOpConstructDMat4x4:
1198 isMatrix = true;
1199 // fall through
1200 case glslang::EOpConstructFloat:
1201 case glslang::EOpConstructVec2:
1202 case glslang::EOpConstructVec3:
1203 case glslang::EOpConstructVec4:
1204 case glslang::EOpConstructDouble:
1205 case glslang::EOpConstructDVec2:
1206 case glslang::EOpConstructDVec3:
1207 case glslang::EOpConstructDVec4:
1208 case glslang::EOpConstructBool:
1209 case glslang::EOpConstructBVec2:
1210 case glslang::EOpConstructBVec3:
1211 case glslang::EOpConstructBVec4:
1212 case glslang::EOpConstructInt:
1213 case glslang::EOpConstructIVec2:
1214 case glslang::EOpConstructIVec3:
1215 case glslang::EOpConstructIVec4:
1216 case glslang::EOpConstructUint:
1217 case glslang::EOpConstructUVec2:
1218 case glslang::EOpConstructUVec3:
1219 case glslang::EOpConstructUVec4:
1220 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001221 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001222 {
1223 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001224 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001225 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1226 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001227 if (node->getOp() == glslang::EOpConstructTextureSampler)
1228 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1229 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001230 std::vector<spv::Id> constituents;
1231 for (int c = 0; c < (int)arguments.size(); ++c)
1232 constituents.push_back(arguments[c]);
1233 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001234 } else if (isMatrix)
1235 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1236 else
1237 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001238
1239 builder.clearAccessChain();
1240 builder.setAccessChainRValue(constructed);
1241
1242 return false;
1243 }
1244
1245 // These six are component-wise compares with component-wise results.
1246 // Forward on to createBinaryOperation(), requesting a vector result.
1247 case glslang::EOpLessThan:
1248 case glslang::EOpGreaterThan:
1249 case glslang::EOpLessThanEqual:
1250 case glslang::EOpGreaterThanEqual:
1251 case glslang::EOpVectorEqual:
1252 case glslang::EOpVectorNotEqual:
1253 {
1254 // Map the operation to a binary
1255 binOp = node->getOp();
1256 reduceComparison = false;
1257 switch (node->getOp()) {
1258 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1259 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1260 default: binOp = node->getOp(); break;
1261 }
1262
1263 break;
1264 }
1265 case glslang::EOpMul:
1266 // compontent-wise matrix multiply
1267 binOp = glslang::EOpMul;
1268 break;
1269 case glslang::EOpOuterProduct:
1270 // two vectors multiplied to make a matrix
1271 binOp = glslang::EOpOuterProduct;
1272 break;
1273 case glslang::EOpDot:
1274 {
1275 // for scalar dot product, use multiply
1276 glslang::TIntermSequence& glslangOperands = node->getSequence();
1277 if (! glslangOperands[0]->getAsTyped()->isVector())
1278 binOp = glslang::EOpMul;
1279 break;
1280 }
1281 case glslang::EOpMod:
1282 // when an aggregate, this is the floating-point mod built-in function,
1283 // which can be emitted by the one in createBinaryOperation()
1284 binOp = glslang::EOpMod;
1285 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001286 case glslang::EOpEmitVertex:
1287 case glslang::EOpEndPrimitive:
1288 case glslang::EOpBarrier:
1289 case glslang::EOpMemoryBarrier:
1290 case glslang::EOpMemoryBarrierAtomicCounter:
1291 case glslang::EOpMemoryBarrierBuffer:
1292 case glslang::EOpMemoryBarrierImage:
1293 case glslang::EOpMemoryBarrierShared:
1294 case glslang::EOpGroupMemoryBarrier:
1295 noReturnValue = true;
1296 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1297 break;
1298
John Kessenich426394d2015-07-23 10:22:48 -06001299 case glslang::EOpAtomicAdd:
1300 case glslang::EOpAtomicMin:
1301 case glslang::EOpAtomicMax:
1302 case glslang::EOpAtomicAnd:
1303 case glslang::EOpAtomicOr:
1304 case glslang::EOpAtomicXor:
1305 case glslang::EOpAtomicExchange:
1306 case glslang::EOpAtomicCompSwap:
1307 atomic = true;
1308 break;
1309
John Kessenich140f3df2015-06-26 16:58:36 -06001310 default:
1311 break;
1312 }
1313
1314 //
1315 // See if it maps to a regular operation.
1316 //
John Kessenich140f3df2015-06-26 16:58:36 -06001317 if (binOp != glslang::EOpNull) {
1318 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1319 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1320 assert(left && right);
1321
1322 builder.clearAccessChain();
1323 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001324 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001325
1326 builder.clearAccessChain();
1327 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001328 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 result = createBinaryOperation(binOp, precision,
1331 convertGlslangToSpvType(node->getType()), leftId, rightId,
1332 left->getType().getBasicType(), reduceComparison);
1333
1334 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001335 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001336 builder.clearAccessChain();
1337 builder.setAccessChainRValue(result);
1338
1339 return false;
1340 }
1341
John Kessenich426394d2015-07-23 10:22:48 -06001342 //
1343 // Create the list of operands.
1344 //
John Kessenich140f3df2015-06-26 16:58:36 -06001345 glslang::TIntermSequence& glslangOperands = node->getSequence();
1346 std::vector<spv::Id> operands;
1347 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1348 builder.clearAccessChain();
1349 glslangOperands[arg]->traverse(this);
1350
1351 // special case l-value operands; there are just a few
1352 bool lvalue = false;
1353 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001354 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001355 case glslang::EOpModf:
1356 if (arg == 1)
1357 lvalue = true;
1358 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001359 case glslang::EOpInterpolateAtSample:
1360 case glslang::EOpInterpolateAtOffset:
1361 if (arg == 0)
1362 lvalue = true;
1363 break;
Rex Xud4782c12015-09-06 16:30:11 +08001364 case glslang::EOpAtomicAdd:
1365 case glslang::EOpAtomicMin:
1366 case glslang::EOpAtomicMax:
1367 case glslang::EOpAtomicAnd:
1368 case glslang::EOpAtomicOr:
1369 case glslang::EOpAtomicXor:
1370 case glslang::EOpAtomicExchange:
1371 case glslang::EOpAtomicCompSwap:
1372 if (arg == 0)
1373 lvalue = true;
1374 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001375 case glslang::EOpAddCarry:
1376 case glslang::EOpSubBorrow:
1377 if (arg == 2)
1378 lvalue = true;
1379 break;
1380 case glslang::EOpUMulExtended:
1381 case glslang::EOpIMulExtended:
1382 if (arg >= 2)
1383 lvalue = true;
1384 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001385 default:
1386 break;
1387 }
1388 if (lvalue)
1389 operands.push_back(builder.accessChainGetLValue());
1390 else
John Kessenich32cfd492016-02-02 12:37:46 -07001391 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001392 }
John Kessenich426394d2015-07-23 10:22:48 -06001393
1394 if (atomic) {
1395 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001396 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001397 } else {
1398 // Pass through to generic operations.
1399 switch (glslangOperands.size()) {
1400 case 0:
1401 result = createNoArgOperation(node->getOp());
1402 break;
1403 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001404 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001405 break;
1406 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001407 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001408 break;
1409 }
John Kessenich140f3df2015-06-26 16:58:36 -06001410 }
1411
1412 if (noReturnValue)
1413 return false;
1414
1415 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001416 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001417 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001418 } else {
1419 builder.clearAccessChain();
1420 builder.setAccessChainRValue(result);
1421 return false;
1422 }
1423}
1424
1425bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1426{
1427 // This path handles both if-then-else and ?:
1428 // The if-then-else has a node type of void, while
1429 // ?: has a non-void node type
1430 spv::Id result = 0;
1431 if (node->getBasicType() != glslang::EbtVoid) {
1432 // don't handle this as just on-the-fly temporaries, because there will be two names
1433 // and better to leave SSA to later passes
1434 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1435 }
1436
1437 // emit the condition before doing anything with selection
1438 node->getCondition()->traverse(this);
1439
1440 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001441 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001442
1443 if (node->getTrueBlock()) {
1444 // emit the "then" statement
1445 node->getTrueBlock()->traverse(this);
1446 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001447 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001448 }
1449
1450 if (node->getFalseBlock()) {
1451 ifBuilder.makeBeginElse();
1452 // emit the "else" statement
1453 node->getFalseBlock()->traverse(this);
1454 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001455 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001456 }
1457
1458 ifBuilder.makeEndIf();
1459
1460 if (result) {
1461 // GLSL only has r-values as the result of a :?, but
1462 // if we have an l-value, that can be more efficient if it will
1463 // become the base of a complex r-value expression, because the
1464 // next layer copies r-values into memory to use the access-chain mechanism
1465 builder.clearAccessChain();
1466 builder.setAccessChainLValue(result);
1467 }
1468
1469 return false;
1470}
1471
1472bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1473{
1474 // emit and get the condition before doing anything with switch
1475 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001476 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001477
1478 // browse the children to sort out code segments
1479 int defaultSegment = -1;
1480 std::vector<TIntermNode*> codeSegments;
1481 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1482 std::vector<int> caseValues;
1483 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1484 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1485 TIntermNode* child = *c;
1486 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001487 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001488 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001489 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001490 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1491 } else
1492 codeSegments.push_back(child);
1493 }
1494
1495 // handle the case where the last code segment is missing, due to no code
1496 // statements between the last case and the end of the switch statement
1497 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1498 (int)codeSegments.size() == defaultSegment)
1499 codeSegments.push_back(nullptr);
1500
1501 // make the switch statement
1502 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001503 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001504
1505 // emit all the code in the segments
1506 breakForLoop.push(false);
1507 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1508 builder.nextSwitchSegment(segmentBlocks, s);
1509 if (codeSegments[s])
1510 codeSegments[s]->traverse(this);
1511 else
1512 builder.addSwitchBreak();
1513 }
1514 breakForLoop.pop();
1515
1516 builder.endSwitch(segmentBlocks);
1517
1518 return false;
1519}
1520
1521void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1522{
1523 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001524 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001525
1526 builder.clearAccessChain();
1527 builder.setAccessChainRValue(constant);
1528}
1529
1530bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1531{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001532 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001533 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001534 // Spec requires back edges to target header blocks, and every header block
1535 // must dominate its merge block. Make a header block first to ensure these
1536 // conditions are met. By definition, it will contain OpLoopMerge, followed
1537 // by a block-ending branch. But we don't want to put any other body/test
1538 // instructions in it, since the body/test may have arbitrary instructions,
1539 // including merges of its own.
1540 builder.setBuildPoint(&blocks.head);
1541 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001542 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001543 spv::Block& test = builder.makeNewBlock();
1544 builder.createBranch(&test);
1545
1546 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001547 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001548 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001549 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001550 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1551
1552 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001553 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001554 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001555 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001556 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001557 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001558
1559 builder.setBuildPoint(&blocks.continue_target);
1560 if (node->getTerminal())
1561 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001562 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001563 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001564 builder.createBranch(&blocks.body);
1565
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001566 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001567 builder.setBuildPoint(&blocks.body);
1568 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001569 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001570 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001571 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001572
1573 builder.setBuildPoint(&blocks.continue_target);
1574 if (node->getTerminal())
1575 node->getTerminal()->traverse(this);
1576 if (node->getTest()) {
1577 node->getTest()->traverse(this);
1578 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001579 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001580 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001581 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001582 // TODO: unless there was a break/return/discard instruction
1583 // somewhere in the body, this is an infinite loop, so we should
1584 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001585 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001586 }
John Kessenich140f3df2015-06-26 16:58:36 -06001587 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001588 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001589 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001590 return false;
1591}
1592
1593bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1594{
1595 if (node->getExpression())
1596 node->getExpression()->traverse(this);
1597
1598 switch (node->getFlowOp()) {
1599 case glslang::EOpKill:
1600 builder.makeDiscard();
1601 break;
1602 case glslang::EOpBreak:
1603 if (breakForLoop.top())
1604 builder.createLoopExit();
1605 else
1606 builder.addSwitchBreak();
1607 break;
1608 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001609 builder.createLoopContinue();
1610 break;
1611 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001612 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001613 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001614 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001615 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001616
1617 builder.clearAccessChain();
1618 break;
1619
1620 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001621 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001622 break;
1623 }
1624
1625 return false;
1626}
1627
1628spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1629{
1630 // First, steer off constants, which are not SPIR-V variables, but
1631 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001632 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06001633 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04001634 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001635 }
1636
1637 // Now, handle actual variables
1638 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1639 spv::Id spvType = convertGlslangToSpvType(node->getType());
1640
1641 const char* name = node->getName().c_str();
1642 if (glslang::IsAnonymous(name))
1643 name = "";
1644
1645 return builder.createVariable(storageClass, spvType, name);
1646}
1647
1648// Return type Id of the sampled type.
1649spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1650{
1651 switch (sampler.type) {
1652 case glslang::EbtFloat: return builder.makeFloatType(32);
1653 case glslang::EbtInt: return builder.makeIntType(32);
1654 case glslang::EbtUint: return builder.makeUintType(32);
1655 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001656 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001657 return builder.makeFloatType(32);
1658 }
1659}
1660
John Kessenich3ac051e2015-12-20 11:29:16 -07001661// Convert from a glslang type to an SPV type, by calling into a
1662// recursive version of this function. This establishes the inherited
1663// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001664spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1665{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001666 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001667}
1668
1669// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001670// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001671spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001672{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001673 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001674
1675 switch (type.getBasicType()) {
1676 case glslang::EbtVoid:
1677 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001678 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001679 break;
1680 case glslang::EbtFloat:
1681 spvType = builder.makeFloatType(32);
1682 break;
1683 case glslang::EbtDouble:
1684 spvType = builder.makeFloatType(64);
1685 break;
1686 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001687 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1688 // a 32-bit int where non-0 means true.
1689 if (explicitLayout != glslang::ElpNone)
1690 spvType = builder.makeUintType(32);
1691 else
1692 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001693 break;
1694 case glslang::EbtInt:
1695 spvType = builder.makeIntType(32);
1696 break;
1697 case glslang::EbtUint:
1698 spvType = builder.makeUintType(32);
1699 break;
John Kessenich426394d2015-07-23 10:22:48 -06001700 case glslang::EbtAtomicUint:
1701 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1702 spvType = builder.makeUintType(32);
1703 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001704 case glslang::EbtSampler:
1705 {
1706 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001707 if (sampler.sampler) {
1708 // pure sampler
1709 spvType = builder.makeSamplerType();
1710 } else {
1711 // an image is present, make its type
1712 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1713 sampler.image ? 2 : 1, TranslateImageFormat(type));
1714 if (sampler.combined) {
1715 // already has both image and sampler, make the combined type
1716 spvType = builder.makeSampledImageType(spvType);
1717 }
John Kessenich55e7d112015-11-15 21:33:39 -07001718 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001719 }
John Kessenich140f3df2015-06-26 16:58:36 -06001720 break;
1721 case glslang::EbtStruct:
1722 case glslang::EbtBlock:
1723 {
1724 // If we've seen this struct type, return it
1725 const glslang::TTypeList* glslangStruct = type.getStruct();
1726 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001727
1728 // Try to share structs for different layouts, but not yet for other
1729 // kinds of qualification (primarily not yet including interpolant qualification).
1730 if (! HasNonLayoutQualifiers(qualifier))
1731 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1732 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001733 break;
1734
1735 // else, we haven't seen it...
1736
1737 // Create a vector of struct types for SPIR-V to consume
1738 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1739 if (type.getBasicType() == glslang::EbtBlock)
1740 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001741 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001742 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1743 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1744 if (glslangType.hiddenMember()) {
1745 ++memberDelta;
1746 if (type.getBasicType() == glslang::EbtBlock)
1747 memberRemapper[glslangStruct][i] = -1;
1748 } else {
1749 if (type.getBasicType() == glslang::EbtBlock)
1750 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001751 // modify just this child's view of the qualifier
1752 glslang::TQualifier subQualifier = glslangType.getQualifier();
1753 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001754
1755 // manually inherit location; it's more complex
1756 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1757 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1758 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001759 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001760
1761 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001762 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001763 }
1764 }
1765
1766 // Make the SPIR-V type
1767 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001768 if (! HasNonLayoutQualifiers(qualifier))
1769 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001770
1771 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001772 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001773 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001774 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1775 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1776 int member = i;
1777 if (type.getBasicType() == glslang::EbtBlock)
1778 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001779
John Kesseniche0b6cad2015-12-24 10:30:13 -07001780 // modify just this child's view of the qualifier
1781 glslang::TQualifier subQualifier = glslangType.getQualifier();
1782 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001783
John Kessenich140f3df2015-06-26 16:58:36 -06001784 // using -1 above to indicate a hidden member
1785 if (member >= 0) {
1786 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001787 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001788 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001789 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1790 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001791
Rex Xu1da878f2016-02-21 20:59:01 +08001792 if (qualifier.storage == glslang::EvqBuffer) {
1793 std::vector<spv::Decoration> memory;
1794 TranslateMemoryDecoration(subQualifier, memory);
1795 for (unsigned int i = 0; i < memory.size(); ++i)
1796 addMemberDecoration(spvType, member, memory[i]);
1797 }
1798
John Kessenich09677482016-02-19 12:21:50 -07001799 // compute location decoration; tricky based on whether inheritance is at play
1800 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1801 // probably move to the linker stage of the front end proper, and just have the
1802 // answer sitting already distributed throughout the individual member locations.
1803 int location = -1; // will only decorate if present or inherited
1804 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1805 location = subQualifier.layoutLocation;
1806 else if (qualifier.hasLocation()) // inheritance
1807 location = qualifier.layoutLocation + locationOffset;
1808 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001809 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001810 if (location >= 0)
1811 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1812
1813 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001814 if (glslangType.getQualifier().hasComponent())
1815 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1816 if (glslangType.getQualifier().hasXfbOffset())
1817 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001818 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001819 // figure out what to do with offset, which is accumulating
1820 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001821 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001822 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001823 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001824 offset = nextOffset;
1825 }
John Kessenich140f3df2015-06-26 16:58:36 -06001826
John Kessenichf85e8062015-12-19 13:57:10 -07001827 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001828 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001829
John Kessenich140f3df2015-06-26 16:58:36 -06001830 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001831 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1832 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001833 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001834 }
1835 }
1836
1837 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001838 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001839 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001840 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001841 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001842 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001843 }
John Kessenich140f3df2015-06-26 16:58:36 -06001844 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001845 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001846 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001847 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001848 if (type.getQualifier().hasXfbBuffer())
1849 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1850 }
1851 }
1852 break;
1853 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001854 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001855 break;
1856 }
1857
1858 if (type.isMatrix())
1859 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1860 else {
1861 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1862 if (type.getVectorSize() > 1)
1863 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1864 }
1865
1866 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001867 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1868
John Kessenichc9a80832015-09-12 12:17:44 -06001869 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001870 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001871 // We need to decorate array strides for types needing explicit layout, except blocks.
1872 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001873 // Use a dummy glslang type for querying internal strides of
1874 // arrays of arrays, but using just a one-dimensional array.
1875 glslang::TType simpleArrayType(type, 0); // deference type of the array
1876 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1877 simpleArrayType.getArraySizes().dereference();
1878
1879 // Will compute the higher-order strides here, rather than making a whole
1880 // pile of types and doing repetitive recursion on their contents.
1881 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1882 }
John Kessenichf8842e52016-01-04 19:22:56 -07001883
1884 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001885 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001886 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001887 if (stride > 0)
1888 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001889 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001890 }
1891 } else {
1892 // single-dimensional array, and don't yet have stride
1893
John Kessenichf8842e52016-01-04 19:22:56 -07001894 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001895 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1896 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001897 }
John Kessenich31ed4832015-09-09 17:51:38 -06001898
John Kessenichc9a80832015-09-12 12:17:44 -06001899 // Do the outer dimension, which might not be known for a runtime-sized array
1900 if (type.isRuntimeSizedArray()) {
1901 spvType = builder.makeRuntimeArray(spvType);
1902 } else {
1903 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001904 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001905 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001906 if (stride > 0)
1907 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001908 }
1909
1910 return spvType;
1911}
1912
John Kessenich6c292d32016-02-15 20:58:50 -07001913// Turn the expression forming the array size into an id.
1914// This is not quite trivial, because of specialization constants.
1915// Sometimes, a raw constant is turned into an Id, and sometimes
1916// a specialization constant expression is.
1917spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1918{
1919 // First, see if this is sized with a node, meaning a specialization constant:
1920 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1921 if (specNode != nullptr) {
1922 builder.clearAccessChain();
1923 specNode->traverse(this);
1924 return accessChainLoad(specNode->getAsTyped()->getType());
1925 }
1926
1927 // Otherwise, need a compile-time (front end) size, get it:
1928 int size = arraySizes.getDimSize(dim);
1929 assert(size > 0);
1930 return builder.makeUintConstant(size);
1931}
1932
John Kessenich103bef92016-02-08 21:38:15 -07001933// Wrap the builder's accessChainLoad to:
1934// - localize handling of RelaxedPrecision
1935// - use the SPIR-V inferred type instead of another conversion of the glslang type
1936// (avoids unnecessary work and possible type punning for structures)
1937// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001938spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1939{
John Kessenich103bef92016-02-08 21:38:15 -07001940 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1941 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1942
1943 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001944 if (type.getBasicType() == glslang::EbtBool) {
1945 if (builder.isScalarType(nominalTypeId)) {
1946 // Conversion for bool
1947 spv::Id boolType = builder.makeBoolType();
1948 if (nominalTypeId != boolType)
1949 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1950 } else if (builder.isVectorType(nominalTypeId)) {
1951 // Conversion for bvec
1952 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1953 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1954 if (nominalTypeId != bvecType)
1955 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1956 }
1957 }
John Kessenich103bef92016-02-08 21:38:15 -07001958
1959 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001960}
1961
Rex Xu27253232016-02-23 17:51:09 +08001962// Wrap the builder's accessChainStore to:
1963// - do conversion of concrete to abstract type
1964void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
1965{
1966 // Need to convert to abstract types when necessary
1967 if (type.getBasicType() == glslang::EbtBool) {
1968 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1969
1970 if (builder.isScalarType(nominalTypeId)) {
1971 // Conversion for bool
1972 spv::Id boolType = builder.makeBoolType();
1973 if (nominalTypeId != boolType) {
1974 spv::Id zero = builder.makeUintConstant(0);
1975 spv::Id one = builder.makeUintConstant(1);
1976 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1977 }
1978 } else if (builder.isVectorType(nominalTypeId)) {
1979 // Conversion for bvec
1980 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1981 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1982 if (nominalTypeId != bvecType) {
1983 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
1984 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
1985 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1986 }
1987 }
1988 }
1989
1990 builder.accessChainStore(rvalue);
1991}
1992
John Kessenichf85e8062015-12-19 13:57:10 -07001993// Decide whether or not this type should be
1994// decorated with offsets and strides, and if so
1995// whether std140 or std430 rules should be applied.
1996glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001997{
John Kessenichf85e8062015-12-19 13:57:10 -07001998 // has to be a block
1999 if (type.getBasicType() != glslang::EbtBlock)
2000 return glslang::ElpNone;
2001
2002 // has to be a uniform or buffer block
2003 if (type.getQualifier().storage != glslang::EvqUniform &&
2004 type.getQualifier().storage != glslang::EvqBuffer)
2005 return glslang::ElpNone;
2006
2007 // return the layout to use
2008 switch (type.getQualifier().layoutPacking) {
2009 case glslang::ElpStd140:
2010 case glslang::ElpStd430:
2011 return type.getQualifier().layoutPacking;
2012 default:
2013 return glslang::ElpNone;
2014 }
John Kessenich31ed4832015-09-09 17:51:38 -06002015}
2016
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002017// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002018int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002019{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002020 int size;
John Kessenich49987892015-12-29 17:11:44 -07002021 int stride;
2022 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002023
2024 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002025}
2026
John Kessenich49987892015-12-29 17:11:44 -07002027// 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 -07002028// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002029int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002030{
John Kessenich49987892015-12-29 17:11:44 -07002031 glslang::TType elementType;
2032 elementType.shallowCopy(matrixType);
2033 elementType.clearArraySizes();
2034
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002035 int size;
John Kessenich49987892015-12-29 17:11:44 -07002036 int stride;
2037 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2038
2039 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002040}
2041
John Kessenich5e4b1242015-08-06 22:53:06 -06002042// Given a member type of a struct, realign the current offset for it, and compute
2043// the next (not yet aligned) offset for the next member, which will get aligned
2044// on the next call.
2045// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2046// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2047// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002048void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002049 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002050{
2051 // this will get a positive value when deemed necessary
2052 nextOffset = -1;
2053
John Kessenich5e4b1242015-08-06 22:53:06 -06002054 // override anything in currentOffset with user-set offset
2055 if (memberType.getQualifier().hasOffset())
2056 currentOffset = memberType.getQualifier().layoutOffset;
2057
2058 // It could be that current linker usage in glslang updated all the layoutOffset,
2059 // in which case the following code does not matter. But, that's not quite right
2060 // once cross-compilation unit GLSL validation is done, as the original user
2061 // settings are needed in layoutOffset, and then the following will come into play.
2062
John Kessenichf85e8062015-12-19 13:57:10 -07002063 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002064 if (! memberType.getQualifier().hasOffset())
2065 currentOffset = -1;
2066
2067 return;
2068 }
2069
John Kessenichf85e8062015-12-19 13:57:10 -07002070 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002071 if (currentOffset < 0)
2072 currentOffset = 0;
2073
2074 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2075 // but possibly not yet correctly aligned.
2076
2077 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002078 int dummyStride;
2079 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002080 glslang::RoundToPow2(currentOffset, memberAlignment);
2081 nextOffset = currentOffset + memberSize;
2082}
2083
John Kessenich140f3df2015-06-26 16:58:36 -06002084bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2085{
2086 return node->getName() == "main(";
2087}
2088
2089// Make all the functions, skeletally, without actually visiting their bodies.
2090void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2091{
2092 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2093 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2094 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2095 continue;
2096
2097 // We're on a user function. Set up the basic interface for the function now,
2098 // so that it's available to call.
2099 // Translating the body will happen later.
2100 //
2101 // Typically (except for a "const in" parameter), an address will be passed to the
2102 // function. What it is an address of varies:
2103 //
2104 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2105 // so that write needs to be to a copy, hence the address of a copy works.
2106 //
2107 // - "const in" parameters can just be the r-value, as no writes need occur.
2108 //
2109 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2110 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2111
2112 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002113 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002114 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2115
2116 for (int p = 0; p < (int)parameters.size(); ++p) {
2117 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2118 spv::Id typeId = convertGlslangToSpvType(paramType);
2119 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2120 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2121 else
2122 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002123 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002124 paramTypes.push_back(typeId);
2125 }
2126
2127 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002128 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2129 convertGlslangToSpvType(glslFunction->getType()),
2130 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002131
2132 // Track function to emit/call later
2133 functionMap[glslFunction->getName().c_str()] = function;
2134
2135 // Set the parameter id's
2136 for (int p = 0; p < (int)parameters.size(); ++p) {
2137 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2138 // give a name too
2139 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2140 }
2141 }
2142}
2143
2144// Process all the initializers, while skipping the functions and link objects
2145void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2146{
2147 builder.setBuildPoint(shaderEntry->getLastBlock());
2148 for (int i = 0; i < (int)initializers.size(); ++i) {
2149 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2150 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2151
2152 // We're on a top-level node that's not a function. Treat as an initializer, whose
2153 // code goes into the beginning of main.
2154 initializer->traverse(this);
2155 }
2156 }
2157}
2158
2159// Process all the functions, while skipping initializers.
2160void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2161{
2162 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2163 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2164 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2165 node->traverse(this);
2166 }
2167}
2168
2169void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2170{
2171 // SPIR-V functions should already be in the functionMap from the prepass
2172 // that called makeFunctions().
2173 spv::Function* function = functionMap[node->getName().c_str()];
2174 spv::Block* functionBlock = function->getEntryBlock();
2175 builder.setBuildPoint(functionBlock);
2176}
2177
Rex Xu04db3f52015-09-16 11:44:02 +08002178void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002179{
Rex Xufc618912015-09-09 16:42:49 +08002180 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002181
2182 glslang::TSampler sampler = {};
2183 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002184 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002185 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2186 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2187 }
2188
John Kessenich140f3df2015-06-26 16:58:36 -06002189 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2190 builder.clearAccessChain();
2191 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002192
2193 // Special case l-value operands
2194 bool lvalue = false;
2195 switch (node.getOp()) {
2196 case glslang::EOpImageAtomicAdd:
2197 case glslang::EOpImageAtomicMin:
2198 case glslang::EOpImageAtomicMax:
2199 case glslang::EOpImageAtomicAnd:
2200 case glslang::EOpImageAtomicOr:
2201 case glslang::EOpImageAtomicXor:
2202 case glslang::EOpImageAtomicExchange:
2203 case glslang::EOpImageAtomicCompSwap:
2204 if (i == 0)
2205 lvalue = true;
2206 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002207 case glslang::EOpSparseImageLoad:
2208 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2209 lvalue = true;
2210 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002211 case glslang::EOpSparseTexture:
2212 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2213 lvalue = true;
2214 break;
2215 case glslang::EOpSparseTextureClamp:
2216 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2217 lvalue = true;
2218 break;
2219 case glslang::EOpSparseTextureLod:
2220 case glslang::EOpSparseTextureOffset:
2221 if (i == 3)
2222 lvalue = true;
2223 break;
2224 case glslang::EOpSparseTextureFetch:
2225 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2226 lvalue = true;
2227 break;
2228 case glslang::EOpSparseTextureFetchOffset:
2229 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2230 lvalue = true;
2231 break;
2232 case glslang::EOpSparseTextureLodOffset:
2233 case glslang::EOpSparseTextureGrad:
2234 case glslang::EOpSparseTextureOffsetClamp:
2235 if (i == 4)
2236 lvalue = true;
2237 break;
2238 case glslang::EOpSparseTextureGradOffset:
2239 case glslang::EOpSparseTextureGradClamp:
2240 if (i == 5)
2241 lvalue = true;
2242 break;
2243 case glslang::EOpSparseTextureGradOffsetClamp:
2244 if (i == 6)
2245 lvalue = true;
2246 break;
2247 case glslang::EOpSparseTextureGather:
2248 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2249 lvalue = true;
2250 break;
2251 case glslang::EOpSparseTextureGatherOffset:
2252 case glslang::EOpSparseTextureGatherOffsets:
2253 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2254 lvalue = true;
2255 break;
Rex Xufc618912015-09-09 16:42:49 +08002256 default:
2257 break;
2258 }
2259
Rex Xu6b86d492015-09-16 17:48:22 +08002260 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002261 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002262 else
John Kessenich32cfd492016-02-02 12:37:46 -07002263 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002264 }
2265}
2266
John Kessenichfc51d282015-08-19 13:34:18 -06002267void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002268{
John Kessenichfc51d282015-08-19 13:34:18 -06002269 builder.clearAccessChain();
2270 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002271 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002272}
John Kessenich140f3df2015-06-26 16:58:36 -06002273
John Kessenichfc51d282015-08-19 13:34:18 -06002274spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2275{
Rex Xufc618912015-09-09 16:42:49 +08002276 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002277 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002278 }
2279
John Kessenichfc51d282015-08-19 13:34:18 -06002280 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002281 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2282 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2283 std::vector<spv::Id> arguments;
2284 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002285 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002286 else
2287 translateArguments(*node->getAsUnaryNode(), arguments);
2288 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2289
2290 spv::Builder::TextureParameters params = { };
2291 params.sampler = arguments[0];
2292
Rex Xu04db3f52015-09-16 11:44:02 +08002293 glslang::TCrackedTextureOp cracked;
2294 node->crackTexture(sampler, cracked);
2295
John Kessenichfc51d282015-08-19 13:34:18 -06002296 // Check for queries
2297 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002298 // a sampled image needs to have the image extracted first
2299 if (builder.isSampledImage(params.sampler))
2300 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002301 switch (node->getOp()) {
2302 case glslang::EOpImageQuerySize:
2303 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002304 if (arguments.size() > 1) {
2305 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002306 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002307 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002308 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002309 case glslang::EOpImageQuerySamples:
2310 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002311 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002312 case glslang::EOpTextureQueryLod:
2313 params.coords = arguments[1];
2314 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2315 case glslang::EOpTextureQueryLevels:
2316 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002317 case glslang::EOpSparseTexelsResident:
2318 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002319 default:
2320 assert(0);
2321 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002322 }
John Kessenich140f3df2015-06-26 16:58:36 -06002323 }
2324
Rex Xufc618912015-09-09 16:42:49 +08002325 // Check for image functions other than queries
2326 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002327 std::vector<spv::Id> operands;
2328 auto opIt = arguments.begin();
2329 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002330
2331 // Handle subpass operations
2332 // TODO: GLSL should change to have the "MS" only on the type rather than the
2333 // built-in function.
2334 if (cracked.subpass) {
2335 // add on the (0,0) coordinate
2336 spv::Id zero = builder.makeIntConstant(0);
2337 std::vector<spv::Id> comps;
2338 comps.push_back(zero);
2339 comps.push_back(zero);
2340 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2341 if (sampler.ms) {
2342 operands.push_back(spv::ImageOperandsSampleMask);
2343 operands.push_back(*(opIt++));
2344 }
2345 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2346 }
2347
John Kessenich56bab042015-09-16 10:54:31 -06002348 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002349 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002350 if (sampler.ms) {
2351 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002352 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002353 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002354 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2355 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002356 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002357 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002358 if (sampler.ms) {
2359 operands.push_back(*(opIt + 1));
2360 operands.push_back(spv::ImageOperandsSampleMask);
2361 operands.push_back(*opIt);
2362 } else
2363 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002364 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002365 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2366 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002367 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002368 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2369 builder.addCapability(spv::CapabilitySparseResidency);
2370 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2371 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2372
2373 if (sampler.ms) {
2374 operands.push_back(spv::ImageOperandsSampleMask);
2375 operands.push_back(*opIt++);
2376 }
2377
2378 // Create the return type that was a special structure
2379 spv::Id texelOut = *opIt;
2380 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2381 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2382 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2383
2384 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2385
2386 // Decode the return type
2387 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2388 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002389 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002390 // Process image atomic operations
2391
2392 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2393 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002394 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002395
Rex Xufc618912015-09-09 16:42:49 +08002396 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002397 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002398
2399 std::vector<spv::Id> operands;
2400 operands.push_back(pointer);
2401 for (; opIt != arguments.end(); ++opIt)
2402 operands.push_back(*opIt);
2403
Rex Xu04db3f52015-09-16 11:44:02 +08002404 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002405 }
2406 }
2407
2408 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002409 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002410 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2411
John Kessenichfc51d282015-08-19 13:34:18 -06002412 // check for bias argument
2413 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002414 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002415 int nonBiasArgCount = 2;
2416 if (cracked.offset)
2417 ++nonBiasArgCount;
2418 if (cracked.grad)
2419 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002420 if (cracked.lodClamp)
2421 ++nonBiasArgCount;
2422 if (sparse)
2423 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002424
2425 if ((int)arguments.size() > nonBiasArgCount)
2426 bias = true;
2427 }
2428
John Kessenichfc51d282015-08-19 13:34:18 -06002429 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002430
John Kessenichfc51d282015-08-19 13:34:18 -06002431 params.coords = arguments[1];
2432 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002433 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002434
2435 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002436 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002437 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002438 ++extraArgs;
2439 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002440 params.Dref = arguments[2];
2441 ++extraArgs;
2442 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002443 std::vector<spv::Id> indexes;
2444 int comp;
2445 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002446 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002447 else
2448 comp = builder.getNumComponents(params.coords) - 1;
2449 indexes.push_back(comp);
2450 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2451 }
2452 if (cracked.lod) {
2453 params.lod = arguments[2];
2454 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002455 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2456 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2457 noImplicitLod = true;
2458 }
2459 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002460 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002461 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002462 }
2463 if (cracked.grad) {
2464 params.gradX = arguments[2 + extraArgs];
2465 params.gradY = arguments[3 + extraArgs];
2466 extraArgs += 2;
2467 }
John Kessenich55e7d112015-11-15 21:33:39 -07002468 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002469 params.offset = arguments[2 + extraArgs];
2470 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002471 } else if (cracked.offsets) {
2472 params.offsets = arguments[2 + extraArgs];
2473 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002474 }
Rex Xu48edadf2015-12-31 16:11:41 +08002475 if (cracked.lodClamp) {
2476 params.lodClamp = arguments[2 + extraArgs];
2477 ++extraArgs;
2478 }
2479 if (sparse) {
2480 params.texelOut = arguments[2 + extraArgs];
2481 ++extraArgs;
2482 }
John Kessenichfc51d282015-08-19 13:34:18 -06002483 if (bias) {
2484 params.bias = arguments[2 + extraArgs];
2485 ++extraArgs;
2486 }
John Kessenich55e7d112015-11-15 21:33:39 -07002487 if (cracked.gather && ! sampler.shadow) {
2488 // default component is 0, if missing, otherwise an argument
2489 if (2 + extraArgs < (int)arguments.size()) {
2490 params.comp = arguments[2 + extraArgs];
2491 ++extraArgs;
2492 } else {
2493 params.comp = builder.makeIntConstant(0);
2494 }
2495 }
John Kessenichfc51d282015-08-19 13:34:18 -06002496
John Kessenich019f08f2016-02-15 15:40:42 -07002497 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002498}
2499
2500spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2501{
2502 // Grab the function's pointer from the previously created function
2503 spv::Function* function = functionMap[node->getName().c_str()];
2504 if (! function)
2505 return 0;
2506
2507 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2508 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2509
2510 // See comments in makeFunctions() for details about the semantics for parameter passing.
2511 //
2512 // These imply we need a four step process:
2513 // 1. Evaluate the arguments
2514 // 2. Allocate and make copies of in, out, and inout arguments
2515 // 3. Make the call
2516 // 4. Copy back the results
2517
2518 // 1. Evaluate the arguments
2519 std::vector<spv::Builder::AccessChain> lValues;
2520 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002521 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002522 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2523 // build l-value
2524 builder.clearAccessChain();
2525 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002526 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002527 // keep outputs as l-values, evaluate input-only as r-values
2528 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2529 // save l-value
2530 lValues.push_back(builder.getAccessChain());
2531 } else {
2532 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002533 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002534 }
2535 }
2536
2537 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2538 // copy the original into that space.
2539 //
2540 // Also, build up the list of actual arguments to pass in for the call
2541 int lValueCount = 0;
2542 int rValueCount = 0;
2543 std::vector<spv::Id> spvArgs;
2544 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2545 spv::Id arg;
2546 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2547 // need space to hold the copy
2548 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2549 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2550 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2551 // need to copy the input into output space
2552 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002553 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002554 builder.createStore(copy, arg);
2555 }
2556 ++lValueCount;
2557 } else {
2558 arg = rValues[rValueCount];
2559 ++rValueCount;
2560 }
2561 spvArgs.push_back(arg);
2562 }
2563
2564 // 3. Make the call.
2565 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002566 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002567
2568 // 4. Copy back out an "out" arguments.
2569 lValueCount = 0;
2570 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2571 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2572 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2573 spv::Id copy = builder.createLoad(spvArgs[a]);
2574 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002575 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002576 }
2577 ++lValueCount;
2578 }
2579 }
2580
2581 return result;
2582}
2583
2584// Translate AST operation to SPV operation, already having SPV-based operands/types.
2585spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2586 spv::Id typeId, spv::Id left, spv::Id right,
2587 glslang::TBasicType typeProxy, bool reduceComparison)
2588{
2589 bool isUnsigned = typeProxy == glslang::EbtUint;
2590 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2591
2592 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002593 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002594 bool comparison = false;
2595
2596 switch (op) {
2597 case glslang::EOpAdd:
2598 case glslang::EOpAddAssign:
2599 if (isFloat)
2600 binOp = spv::OpFAdd;
2601 else
2602 binOp = spv::OpIAdd;
2603 break;
2604 case glslang::EOpSub:
2605 case glslang::EOpSubAssign:
2606 if (isFloat)
2607 binOp = spv::OpFSub;
2608 else
2609 binOp = spv::OpISub;
2610 break;
2611 case glslang::EOpMul:
2612 case glslang::EOpMulAssign:
2613 if (isFloat)
2614 binOp = spv::OpFMul;
2615 else
2616 binOp = spv::OpIMul;
2617 break;
2618 case glslang::EOpVectorTimesScalar:
2619 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002620 if (isFloat) {
2621 if (builder.isVector(right))
2622 std::swap(left, right);
2623 assert(builder.isScalar(right));
2624 needMatchingVectors = false;
2625 binOp = spv::OpVectorTimesScalar;
2626 } else
2627 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002628 break;
2629 case glslang::EOpVectorTimesMatrix:
2630 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002631 binOp = spv::OpVectorTimesMatrix;
2632 break;
2633 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002634 binOp = spv::OpMatrixTimesVector;
2635 break;
2636 case glslang::EOpMatrixTimesScalar:
2637 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002638 binOp = spv::OpMatrixTimesScalar;
2639 break;
2640 case glslang::EOpMatrixTimesMatrix:
2641 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002642 binOp = spv::OpMatrixTimesMatrix;
2643 break;
2644 case glslang::EOpOuterProduct:
2645 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002646 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002647 break;
2648
2649 case glslang::EOpDiv:
2650 case glslang::EOpDivAssign:
2651 if (isFloat)
2652 binOp = spv::OpFDiv;
2653 else if (isUnsigned)
2654 binOp = spv::OpUDiv;
2655 else
2656 binOp = spv::OpSDiv;
2657 break;
2658 case glslang::EOpMod:
2659 case glslang::EOpModAssign:
2660 if (isFloat)
2661 binOp = spv::OpFMod;
2662 else if (isUnsigned)
2663 binOp = spv::OpUMod;
2664 else
2665 binOp = spv::OpSMod;
2666 break;
2667 case glslang::EOpRightShift:
2668 case glslang::EOpRightShiftAssign:
2669 if (isUnsigned)
2670 binOp = spv::OpShiftRightLogical;
2671 else
2672 binOp = spv::OpShiftRightArithmetic;
2673 break;
2674 case glslang::EOpLeftShift:
2675 case glslang::EOpLeftShiftAssign:
2676 binOp = spv::OpShiftLeftLogical;
2677 break;
2678 case glslang::EOpAnd:
2679 case glslang::EOpAndAssign:
2680 binOp = spv::OpBitwiseAnd;
2681 break;
2682 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002683 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002684 binOp = spv::OpLogicalAnd;
2685 break;
2686 case glslang::EOpInclusiveOr:
2687 case glslang::EOpInclusiveOrAssign:
2688 binOp = spv::OpBitwiseOr;
2689 break;
2690 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002691 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002692 binOp = spv::OpLogicalOr;
2693 break;
2694 case glslang::EOpExclusiveOr:
2695 case glslang::EOpExclusiveOrAssign:
2696 binOp = spv::OpBitwiseXor;
2697 break;
2698 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002699 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002700 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002701 break;
2702
2703 case glslang::EOpLessThan:
2704 case glslang::EOpGreaterThan:
2705 case glslang::EOpLessThanEqual:
2706 case glslang::EOpGreaterThanEqual:
2707 case glslang::EOpEqual:
2708 case glslang::EOpNotEqual:
2709 case glslang::EOpVectorEqual:
2710 case glslang::EOpVectorNotEqual:
2711 comparison = true;
2712 break;
2713 default:
2714 break;
2715 }
2716
John Kessenich7c1aa102015-10-15 13:29:11 -06002717 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002718 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002719 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002720 if (builder.isMatrix(left) || builder.isMatrix(right))
2721 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002722
2723 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002724 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002725 builder.promoteScalar(precision, left, right);
2726
John Kessenich32cfd492016-02-02 12:37:46 -07002727 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002728 }
2729
2730 if (! comparison)
2731 return 0;
2732
John Kessenich7c1aa102015-10-15 13:29:11 -06002733 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002734
2735 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2736 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2737
John Kessenich22118352015-12-21 20:54:09 -07002738 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002739 }
2740
2741 switch (op) {
2742 case glslang::EOpLessThan:
2743 if (isFloat)
2744 binOp = spv::OpFOrdLessThan;
2745 else if (isUnsigned)
2746 binOp = spv::OpULessThan;
2747 else
2748 binOp = spv::OpSLessThan;
2749 break;
2750 case glslang::EOpGreaterThan:
2751 if (isFloat)
2752 binOp = spv::OpFOrdGreaterThan;
2753 else if (isUnsigned)
2754 binOp = spv::OpUGreaterThan;
2755 else
2756 binOp = spv::OpSGreaterThan;
2757 break;
2758 case glslang::EOpLessThanEqual:
2759 if (isFloat)
2760 binOp = spv::OpFOrdLessThanEqual;
2761 else if (isUnsigned)
2762 binOp = spv::OpULessThanEqual;
2763 else
2764 binOp = spv::OpSLessThanEqual;
2765 break;
2766 case glslang::EOpGreaterThanEqual:
2767 if (isFloat)
2768 binOp = spv::OpFOrdGreaterThanEqual;
2769 else if (isUnsigned)
2770 binOp = spv::OpUGreaterThanEqual;
2771 else
2772 binOp = spv::OpSGreaterThanEqual;
2773 break;
2774 case glslang::EOpEqual:
2775 case glslang::EOpVectorEqual:
2776 if (isFloat)
2777 binOp = spv::OpFOrdEqual;
2778 else
2779 binOp = spv::OpIEqual;
2780 break;
2781 case glslang::EOpNotEqual:
2782 case glslang::EOpVectorNotEqual:
2783 if (isFloat)
2784 binOp = spv::OpFOrdNotEqual;
2785 else
2786 binOp = spv::OpINotEqual;
2787 break;
2788 default:
2789 break;
2790 }
2791
John Kessenich32cfd492016-02-02 12:37:46 -07002792 if (binOp != spv::OpNop)
2793 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002794
2795 return 0;
2796}
2797
John Kessenich04bb8a02015-12-12 12:28:14 -07002798//
2799// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2800// These can be any of:
2801//
2802// matrix * scalar
2803// scalar * matrix
2804// matrix * matrix linear algebraic
2805// matrix * vector
2806// vector * matrix
2807// matrix * matrix componentwise
2808// matrix op matrix op in {+, -, /}
2809// matrix op scalar op in {+, -, /}
2810// scalar op matrix op in {+, -, /}
2811//
2812spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2813{
2814 bool firstClass = true;
2815
2816 // First, handle first-class matrix operations (* and matrix/scalar)
2817 switch (op) {
2818 case spv::OpFDiv:
2819 if (builder.isMatrix(left) && builder.isScalar(right)) {
2820 // turn matrix / scalar into a multiply...
2821 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2822 op = spv::OpMatrixTimesScalar;
2823 } else
2824 firstClass = false;
2825 break;
2826 case spv::OpMatrixTimesScalar:
2827 if (builder.isMatrix(right))
2828 std::swap(left, right);
2829 assert(builder.isScalar(right));
2830 break;
2831 case spv::OpVectorTimesMatrix:
2832 assert(builder.isVector(left));
2833 assert(builder.isMatrix(right));
2834 break;
2835 case spv::OpMatrixTimesVector:
2836 assert(builder.isMatrix(left));
2837 assert(builder.isVector(right));
2838 break;
2839 case spv::OpMatrixTimesMatrix:
2840 assert(builder.isMatrix(left));
2841 assert(builder.isMatrix(right));
2842 break;
2843 default:
2844 firstClass = false;
2845 break;
2846 }
2847
John Kessenich32cfd492016-02-02 12:37:46 -07002848 if (firstClass)
2849 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002850
2851 // Handle component-wise +, -, *, and / for all combinations of type.
2852 // The result type of all of them is the same type as the (a) matrix operand.
2853 // The algorithm is to:
2854 // - break the matrix(es) into vectors
2855 // - smear any scalar to a vector
2856 // - do vector operations
2857 // - make a matrix out the vector results
2858 switch (op) {
2859 case spv::OpFAdd:
2860 case spv::OpFSub:
2861 case spv::OpFDiv:
2862 case spv::OpFMul:
2863 {
2864 // one time set up...
2865 bool leftMat = builder.isMatrix(left);
2866 bool rightMat = builder.isMatrix(right);
2867 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2868 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2869 spv::Id scalarType = builder.getScalarTypeId(typeId);
2870 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2871 std::vector<spv::Id> results;
2872 spv::Id smearVec = spv::NoResult;
2873 if (builder.isScalar(left))
2874 smearVec = builder.smearScalar(precision, left, vecType);
2875 else if (builder.isScalar(right))
2876 smearVec = builder.smearScalar(precision, right, vecType);
2877
2878 // do each vector op
2879 for (unsigned int c = 0; c < numCols; ++c) {
2880 std::vector<unsigned int> indexes;
2881 indexes.push_back(c);
2882 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2883 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2884 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2885 builder.setPrecision(results.back(), precision);
2886 }
2887
2888 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002889 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002890 }
2891 default:
2892 assert(0);
2893 return spv::NoResult;
2894 }
2895}
2896
Rex Xu04db3f52015-09-16 11:44:02 +08002897spv::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 -06002898{
2899 spv::Op unaryOp = spv::OpNop;
2900 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002901 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002902 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002903
2904 switch (op) {
2905 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002906 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002907 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002908 if (builder.isMatrixType(typeId))
2909 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2910 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002911 unaryOp = spv::OpSNegate;
2912 break;
2913
2914 case glslang::EOpLogicalNot:
2915 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002916 unaryOp = spv::OpLogicalNot;
2917 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002918 case glslang::EOpBitwiseNot:
2919 unaryOp = spv::OpNot;
2920 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002921
John Kessenich140f3df2015-06-26 16:58:36 -06002922 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002923 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002924 break;
2925 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002926 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002927 break;
2928 case glslang::EOpTranspose:
2929 unaryOp = spv::OpTranspose;
2930 break;
2931
2932 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002933 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002934 break;
2935 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002936 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002937 break;
2938 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002939 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002940 break;
2941 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002942 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002943 break;
2944 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002945 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002946 break;
2947 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002948 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002949 break;
2950 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002951 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002952 break;
2953 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002954 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002955 break;
2956
2957 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002958 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002959 break;
2960 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002961 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002962 break;
2963 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002964 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002965 break;
2966 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002967 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002968 break;
2969 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002970 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002971 break;
2972 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002973 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002974 break;
2975
2976 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002977 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002978 break;
2979 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002980 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002981 break;
2982
2983 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002984 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002985 break;
2986 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002987 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002988 break;
2989 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002990 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002991 break;
2992 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002993 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002994 break;
2995 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002996 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002997 break;
2998 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002999 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003000 break;
3001
3002 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003003 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003004 break;
3005 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003006 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003007 break;
3008 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003009 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003010 break;
3011 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003012 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003013 break;
3014 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003015 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003016 break;
3017 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003018 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003019 break;
3020
3021 case glslang::EOpIsNan:
3022 unaryOp = spv::OpIsNan;
3023 break;
3024 case glslang::EOpIsInf:
3025 unaryOp = spv::OpIsInf;
3026 break;
3027
Rex Xucbc426e2015-12-15 16:03:10 +08003028 case glslang::EOpFloatBitsToInt:
3029 case glslang::EOpFloatBitsToUint:
3030 case glslang::EOpIntBitsToFloat:
3031 case glslang::EOpUintBitsToFloat:
3032 unaryOp = spv::OpBitcast;
3033 break;
3034
John Kessenich140f3df2015-06-26 16:58:36 -06003035 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003036 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003037 break;
3038 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003039 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003040 break;
3041 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003042 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003043 break;
3044 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003045 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003046 break;
3047 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003048 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003049 break;
3050 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003051 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003052 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003053 case glslang::EOpPackSnorm4x8:
3054 libCall = spv::GLSLstd450PackSnorm4x8;
3055 break;
3056 case glslang::EOpUnpackSnorm4x8:
3057 libCall = spv::GLSLstd450UnpackSnorm4x8;
3058 break;
3059 case glslang::EOpPackUnorm4x8:
3060 libCall = spv::GLSLstd450PackUnorm4x8;
3061 break;
3062 case glslang::EOpUnpackUnorm4x8:
3063 libCall = spv::GLSLstd450UnpackUnorm4x8;
3064 break;
3065 case glslang::EOpPackDouble2x32:
3066 libCall = spv::GLSLstd450PackDouble2x32;
3067 break;
3068 case glslang::EOpUnpackDouble2x32:
3069 libCall = spv::GLSLstd450UnpackDouble2x32;
3070 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003071
3072 case glslang::EOpDPdx:
3073 unaryOp = spv::OpDPdx;
3074 break;
3075 case glslang::EOpDPdy:
3076 unaryOp = spv::OpDPdy;
3077 break;
3078 case glslang::EOpFwidth:
3079 unaryOp = spv::OpFwidth;
3080 break;
3081 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003082 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003083 unaryOp = spv::OpDPdxFine;
3084 break;
3085 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003086 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003087 unaryOp = spv::OpDPdyFine;
3088 break;
3089 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003090 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003091 unaryOp = spv::OpFwidthFine;
3092 break;
3093 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003094 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003095 unaryOp = spv::OpDPdxCoarse;
3096 break;
3097 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003098 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003099 unaryOp = spv::OpDPdyCoarse;
3100 break;
3101 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003102 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003103 unaryOp = spv::OpFwidthCoarse;
3104 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003105 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003106 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003107 libCall = spv::GLSLstd450InterpolateAtCentroid;
3108 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003109 case glslang::EOpAny:
3110 unaryOp = spv::OpAny;
3111 break;
3112 case glslang::EOpAll:
3113 unaryOp = spv::OpAll;
3114 break;
3115
3116 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003117 if (isFloat)
3118 libCall = spv::GLSLstd450FAbs;
3119 else
3120 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003121 break;
3122 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003123 if (isFloat)
3124 libCall = spv::GLSLstd450FSign;
3125 else
3126 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003127 break;
3128
John Kessenichfc51d282015-08-19 13:34:18 -06003129 case glslang::EOpAtomicCounterIncrement:
3130 case glslang::EOpAtomicCounterDecrement:
3131 case glslang::EOpAtomicCounter:
3132 {
3133 // Handle all of the atomics in one place, in createAtomicOperation()
3134 std::vector<spv::Id> operands;
3135 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003136 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003137 }
3138
John Kessenichfc51d282015-08-19 13:34:18 -06003139 case glslang::EOpBitFieldReverse:
3140 unaryOp = spv::OpBitReverse;
3141 break;
3142 case glslang::EOpBitCount:
3143 unaryOp = spv::OpBitCount;
3144 break;
3145 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003146 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003147 break;
3148 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003149 if (isUnsigned)
3150 libCall = spv::GLSLstd450FindUMsb;
3151 else
3152 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003153 break;
3154
John Kessenich140f3df2015-06-26 16:58:36 -06003155 default:
3156 return 0;
3157 }
3158
3159 spv::Id id;
3160 if (libCall >= 0) {
3161 std::vector<spv::Id> args;
3162 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003163 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003164 } else
3165 id = builder.createUnaryOp(unaryOp, typeId, operand);
3166
John Kessenich32cfd492016-02-02 12:37:46 -07003167 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003168}
3169
John Kessenich7a53f762016-01-20 11:19:27 -07003170// Create a unary operation on a matrix
3171spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3172{
3173 // Handle unary operations vector by vector.
3174 // The result type is the same type as the original type.
3175 // The algorithm is to:
3176 // - break the matrix into vectors
3177 // - apply the operation to each vector
3178 // - make a matrix out the vector results
3179
3180 // get the types sorted out
3181 int numCols = builder.getNumColumns(operand);
3182 int numRows = builder.getNumRows(operand);
3183 spv::Id scalarType = builder.getScalarTypeId(typeId);
3184 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3185 std::vector<spv::Id> results;
3186
3187 // do each vector op
3188 for (int c = 0; c < numCols; ++c) {
3189 std::vector<unsigned int> indexes;
3190 indexes.push_back(c);
3191 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3192 results.push_back(builder.createUnaryOp(op, vecType, vec));
3193 builder.setPrecision(results.back(), precision);
3194 }
3195
3196 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003197 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003198}
3199
John Kessenich140f3df2015-06-26 16:58:36 -06003200spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3201{
3202 spv::Op convOp = spv::OpNop;
3203 spv::Id zero = 0;
3204 spv::Id one = 0;
3205
3206 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3207
3208 switch (op) {
3209 case glslang::EOpConvIntToBool:
3210 case glslang::EOpConvUintToBool:
3211 zero = builder.makeUintConstant(0);
3212 zero = makeSmearedConstant(zero, vectorSize);
3213 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3214
3215 case glslang::EOpConvFloatToBool:
3216 zero = builder.makeFloatConstant(0.0F);
3217 zero = makeSmearedConstant(zero, vectorSize);
3218 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3219
3220 case glslang::EOpConvDoubleToBool:
3221 zero = builder.makeDoubleConstant(0.0);
3222 zero = makeSmearedConstant(zero, vectorSize);
3223 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3224
3225 case glslang::EOpConvBoolToFloat:
3226 convOp = spv::OpSelect;
3227 zero = builder.makeFloatConstant(0.0);
3228 one = builder.makeFloatConstant(1.0);
3229 break;
3230 case glslang::EOpConvBoolToDouble:
3231 convOp = spv::OpSelect;
3232 zero = builder.makeDoubleConstant(0.0);
3233 one = builder.makeDoubleConstant(1.0);
3234 break;
3235 case glslang::EOpConvBoolToInt:
3236 zero = builder.makeIntConstant(0);
3237 one = builder.makeIntConstant(1);
3238 convOp = spv::OpSelect;
3239 break;
3240 case glslang::EOpConvBoolToUint:
3241 zero = builder.makeUintConstant(0);
3242 one = builder.makeUintConstant(1);
3243 convOp = spv::OpSelect;
3244 break;
3245
3246 case glslang::EOpConvIntToFloat:
3247 case glslang::EOpConvIntToDouble:
3248 convOp = spv::OpConvertSToF;
3249 break;
3250
3251 case glslang::EOpConvUintToFloat:
3252 case glslang::EOpConvUintToDouble:
3253 convOp = spv::OpConvertUToF;
3254 break;
3255
3256 case glslang::EOpConvDoubleToFloat:
3257 case glslang::EOpConvFloatToDouble:
3258 convOp = spv::OpFConvert;
3259 break;
3260
3261 case glslang::EOpConvFloatToInt:
3262 case glslang::EOpConvDoubleToInt:
3263 convOp = spv::OpConvertFToS;
3264 break;
3265
3266 case glslang::EOpConvUintToInt:
3267 case glslang::EOpConvIntToUint:
3268 convOp = spv::OpBitcast;
3269 break;
3270
3271 case glslang::EOpConvFloatToUint:
3272 case glslang::EOpConvDoubleToUint:
3273 convOp = spv::OpConvertFToU;
3274 break;
3275 default:
3276 break;
3277 }
3278
3279 spv::Id result = 0;
3280 if (convOp == spv::OpNop)
3281 return result;
3282
3283 if (convOp == spv::OpSelect) {
3284 zero = makeSmearedConstant(zero, vectorSize);
3285 one = makeSmearedConstant(one, vectorSize);
3286 result = builder.createTriOp(convOp, destType, operand, one, zero);
3287 } else
3288 result = builder.createUnaryOp(convOp, destType, operand);
3289
John Kessenich32cfd492016-02-02 12:37:46 -07003290 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003291}
3292
3293spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3294{
3295 if (vectorSize == 0)
3296 return constant;
3297
3298 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3299 std::vector<spv::Id> components;
3300 for (int c = 0; c < vectorSize; ++c)
3301 components.push_back(constant);
3302 return builder.makeCompositeConstant(vectorTypeId, components);
3303}
3304
John Kessenich426394d2015-07-23 10:22:48 -06003305// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003306spv::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 -06003307{
3308 spv::Op opCode = spv::OpNop;
3309
3310 switch (op) {
3311 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003312 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003313 opCode = spv::OpAtomicIAdd;
3314 break;
3315 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003316 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003317 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003318 break;
3319 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003320 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003321 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003322 break;
3323 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003324 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003325 opCode = spv::OpAtomicAnd;
3326 break;
3327 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003328 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003329 opCode = spv::OpAtomicOr;
3330 break;
3331 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003332 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003333 opCode = spv::OpAtomicXor;
3334 break;
3335 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003336 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003337 opCode = spv::OpAtomicExchange;
3338 break;
3339 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003340 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003341 opCode = spv::OpAtomicCompareExchange;
3342 break;
3343 case glslang::EOpAtomicCounterIncrement:
3344 opCode = spv::OpAtomicIIncrement;
3345 break;
3346 case glslang::EOpAtomicCounterDecrement:
3347 opCode = spv::OpAtomicIDecrement;
3348 break;
3349 case glslang::EOpAtomicCounter:
3350 opCode = spv::OpAtomicLoad;
3351 break;
3352 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003353 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003354 break;
3355 }
3356
3357 // Sort out the operands
3358 // - mapping from glslang -> SPV
3359 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003360 // - compare-exchange swaps the value and comparator
3361 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003362 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3363 auto opIt = operands.begin(); // walk the glslang operands
3364 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003365 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3366 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3367 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003368 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3369 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003370 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003371 spvAtomicOperands.push_back(*(opIt + 1));
3372 spvAtomicOperands.push_back(*opIt);
3373 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003374 }
John Kessenich426394d2015-07-23 10:22:48 -06003375
John Kessenich3e60a6f2015-09-14 22:45:16 -06003376 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003377 for (; opIt != operands.end(); ++opIt)
3378 spvAtomicOperands.push_back(*opIt);
3379
3380 return builder.createOp(opCode, typeId, spvAtomicOperands);
3381}
3382
John Kessenich5e4b1242015-08-06 22:53:06 -06003383spv::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 -06003384{
John Kessenich5e4b1242015-08-06 22:53:06 -06003385 bool isUnsigned = typeProxy == glslang::EbtUint;
3386 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3387
John Kessenich140f3df2015-06-26 16:58:36 -06003388 spv::Op opCode = spv::OpNop;
3389 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003390 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003391 spv::Id typeId0 = 0;
3392 if (consumedOperands > 0)
3393 typeId0 = builder.getTypeId(operands[0]);
3394 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003395
3396 switch (op) {
3397 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003398 if (isFloat)
3399 libCall = spv::GLSLstd450FMin;
3400 else if (isUnsigned)
3401 libCall = spv::GLSLstd450UMin;
3402 else
3403 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003404 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003405 break;
3406 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003407 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003408 break;
3409 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003410 if (isFloat)
3411 libCall = spv::GLSLstd450FMax;
3412 else if (isUnsigned)
3413 libCall = spv::GLSLstd450UMax;
3414 else
3415 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003416 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003417 break;
3418 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003419 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003420 break;
3421 case glslang::EOpDot:
3422 opCode = spv::OpDot;
3423 break;
3424 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003425 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003426 break;
3427
3428 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003429 if (isFloat)
3430 libCall = spv::GLSLstd450FClamp;
3431 else if (isUnsigned)
3432 libCall = spv::GLSLstd450UClamp;
3433 else
3434 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003435 builder.promoteScalar(precision, operands.front(), operands[1]);
3436 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003437 break;
3438 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08003439 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
3440 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07003441 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08003442 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07003443 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08003444 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07003445 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003446 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003447 break;
3448 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003449 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003450 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003451 break;
3452 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003453 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003454 builder.promoteScalar(precision, operands[0], operands[2]);
3455 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003456 break;
3457
3458 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003459 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003460 break;
3461 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003462 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003463 break;
3464 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003465 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003466 break;
3467 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003468 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003469 break;
3470 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003471 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003472 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003473 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003474 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003475 libCall = spv::GLSLstd450InterpolateAtSample;
3476 break;
3477 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003478 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003479 libCall = spv::GLSLstd450InterpolateAtOffset;
3480 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003481 case glslang::EOpAddCarry:
3482 opCode = spv::OpIAddCarry;
3483 typeId = builder.makeStructResultType(typeId0, typeId0);
3484 consumedOperands = 2;
3485 break;
3486 case glslang::EOpSubBorrow:
3487 opCode = spv::OpISubBorrow;
3488 typeId = builder.makeStructResultType(typeId0, typeId0);
3489 consumedOperands = 2;
3490 break;
3491 case glslang::EOpUMulExtended:
3492 opCode = spv::OpUMulExtended;
3493 typeId = builder.makeStructResultType(typeId0, typeId0);
3494 consumedOperands = 2;
3495 break;
3496 case glslang::EOpIMulExtended:
3497 opCode = spv::OpSMulExtended;
3498 typeId = builder.makeStructResultType(typeId0, typeId0);
3499 consumedOperands = 2;
3500 break;
3501 case glslang::EOpBitfieldExtract:
3502 if (isUnsigned)
3503 opCode = spv::OpBitFieldUExtract;
3504 else
3505 opCode = spv::OpBitFieldSExtract;
3506 break;
3507 case glslang::EOpBitfieldInsert:
3508 opCode = spv::OpBitFieldInsert;
3509 break;
3510
3511 case glslang::EOpFma:
3512 libCall = spv::GLSLstd450Fma;
3513 break;
3514 case glslang::EOpFrexp:
3515 libCall = spv::GLSLstd450FrexpStruct;
3516 if (builder.getNumComponents(operands[0]) == 1)
3517 frexpIntType = builder.makeIntegerType(32, true);
3518 else
3519 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3520 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3521 consumedOperands = 1;
3522 break;
3523 case glslang::EOpLdexp:
3524 libCall = spv::GLSLstd450Ldexp;
3525 break;
3526
John Kessenich140f3df2015-06-26 16:58:36 -06003527 default:
3528 return 0;
3529 }
3530
3531 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003532 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003533 // Use an extended instruction from the standard library.
3534 // Construct the call arguments, without modifying the original operands vector.
3535 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3536 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003537 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003538 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003539 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003540 case 0:
3541 // should all be handled by visitAggregate and createNoArgOperation
3542 assert(0);
3543 return 0;
3544 case 1:
3545 // should all be handled by createUnaryOperation
3546 assert(0);
3547 return 0;
3548 case 2:
3549 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3550 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003551 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003552 // anything 3 or over doesn't have l-value operands, so all should be consumed
3553 assert(consumedOperands == operands.size());
3554 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003555 break;
3556 }
3557 }
3558
John Kessenich55e7d112015-11-15 21:33:39 -07003559 // Decode the return types that were structures
3560 switch (op) {
3561 case glslang::EOpAddCarry:
3562 case glslang::EOpSubBorrow:
3563 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3564 id = builder.createCompositeExtract(id, typeId0, 0);
3565 break;
3566 case glslang::EOpUMulExtended:
3567 case glslang::EOpIMulExtended:
3568 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3569 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3570 break;
3571 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003572 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003573 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3574 id = builder.createCompositeExtract(id, typeId0, 0);
3575 break;
3576 default:
3577 break;
3578 }
3579
John Kessenich32cfd492016-02-02 12:37:46 -07003580 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003581}
3582
3583// Intrinsics with no arguments, no return value, and no precision.
3584spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3585{
3586 // TODO: get the barrier operands correct
3587
3588 switch (op) {
3589 case glslang::EOpEmitVertex:
3590 builder.createNoResultOp(spv::OpEmitVertex);
3591 return 0;
3592 case glslang::EOpEndPrimitive:
3593 builder.createNoResultOp(spv::OpEndPrimitive);
3594 return 0;
3595 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003596 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3597 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003598 return 0;
3599 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003600 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003601 return 0;
3602 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003603 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003604 return 0;
3605 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003606 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003607 return 0;
3608 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003609 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003610 return 0;
3611 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003612 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003613 return 0;
3614 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003615 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003616 return 0;
3617 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003618 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003619 return 0;
3620 }
3621}
3622
3623spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3624{
John Kessenich2f273362015-07-18 22:34:27 -06003625 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003626 spv::Id id;
3627 if (symbolValues.end() != iter) {
3628 id = iter->second;
3629 return id;
3630 }
3631
3632 // it was not found, create it
3633 id = createSpvVariable(symbol);
3634 symbolValues[symbol->getId()] = id;
3635
3636 if (! symbol->getType().isStruct()) {
3637 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003638 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003639 if (symbol->getType().getQualifier().hasSpecConstantId())
3640 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003641 if (symbol->getQualifier().hasLocation())
3642 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3643 if (symbol->getQualifier().hasIndex())
3644 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3645 if (symbol->getQualifier().hasComponent())
3646 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3647 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003648 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003649 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003650 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003651 if (symbol->getQualifier().hasXfbBuffer())
3652 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3653 if (symbol->getQualifier().hasXfbOffset())
3654 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3655 }
3656 }
3657
John Kesseniche0b6cad2015-12-24 10:30:13 -07003658 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003659 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003660 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003661 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003662 }
John Kessenich140f3df2015-06-26 16:58:36 -06003663 if (symbol->getQualifier().hasSet())
3664 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003665 else if (IsDescriptorResource(symbol->getType())) {
3666 // default to 0
3667 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3668 }
John Kessenich140f3df2015-06-26 16:58:36 -06003669 if (symbol->getQualifier().hasBinding())
3670 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003671 if (symbol->getQualifier().hasAttachment())
3672 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003673 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003674 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003675 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003676 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003677 if (symbol->getQualifier().hasXfbBuffer())
3678 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3679 }
3680
Rex Xu1da878f2016-02-21 20:59:01 +08003681 if (symbol->getType().isImage()) {
3682 std::vector<spv::Decoration> memory;
3683 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3684 for (unsigned int i = 0; i < memory.size(); ++i)
3685 addDecoration(id, memory[i]);
3686 }
3687
John Kessenich140f3df2015-06-26 16:58:36 -06003688 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003689 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003690 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003691 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003692
John Kessenich140f3df2015-06-26 16:58:36 -06003693 return id;
3694}
3695
John Kessenich55e7d112015-11-15 21:33:39 -07003696// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003697void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3698{
3699 if (dec != spv::BadValue)
3700 builder.addDecoration(id, dec);
3701}
3702
John Kessenich55e7d112015-11-15 21:33:39 -07003703// If 'dec' is valid, add a one-operand decoration to an object
3704void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3705{
3706 if (dec != spv::BadValue)
3707 builder.addDecoration(id, dec, value);
3708}
3709
3710// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003711void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3712{
3713 if (dec != spv::BadValue)
3714 builder.addMemberDecoration(id, (unsigned)member, dec);
3715}
3716
John Kessenich92187592016-02-01 13:45:25 -07003717// If 'dec' is valid, add a one-operand decoration to a struct member
3718void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3719{
3720 if (dec != spv::BadValue)
3721 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3722}
3723
John Kessenich55e7d112015-11-15 21:33:39 -07003724// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003725// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003726//
3727// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3728//
3729// Recursively walk the nodes. The nodes form a tree whose leaves are
3730// regular constants, which themselves are trees that createSpvConstant()
3731// recursively walks. So, this function walks the "top" of the tree:
3732// - emit specialization constant-building instructions for specConstant
3733// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04003734spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07003735{
John Kessenich7cc0e282016-03-20 00:46:02 -06003736 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07003737
qining4f4bb812016-04-03 23:55:17 -04003738 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07003739 if (! node.getQualifier().specConstant) {
3740 // hand off to the non-spec-constant path
3741 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3742 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04003743 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07003744 nextConst, false);
3745 }
3746
3747 // We now know we have a specialization constant to build
3748
qining4f4bb812016-04-03 23:55:17 -04003749 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3750 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3751 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3752 std::vector<spv::Id> dimConstId;
3753 for (int dim = 0; dim < 3; ++dim) {
3754 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3755 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3756 if (specConst)
3757 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3758 }
3759 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3760 }
3761
3762 // An AST node labelled as specialization constant should be a symbol node.
3763 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
3764 if (auto* sn = node.getAsSymbolNode()) {
3765 if (auto* sub_tree = sn->getConstSubtree()) {
3766 return createSpvConstantFromConstSubTree(sub_tree);
3767 } else if (auto* const_union_array = &sn->getConstArray()){
3768 int nextConst = 0;
3769 return createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
John Kessenich6c292d32016-02-15 20:58:50 -07003770 }
3771 }
qining4f4bb812016-04-03 23:55:17 -04003772
3773 // Neither a front-end constant node, nor a specialization constant node with constant union array or
3774 // constant sub tree as initializer.
3775 spv::MissingFunctionality("Neither a front-end constant nor a spec constant.");
3776 exit(1);
3777 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07003778}
3779
John Kessenich140f3df2015-06-26 16:58:36 -06003780// Use 'consts' as the flattened glslang source of scalar constants to recursively
3781// build the aggregate SPIR-V constant.
3782//
3783// If there are not enough elements present in 'consts', 0 will be substituted;
3784// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3785//
qining08408382016-03-21 09:51:37 -04003786spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003787{
3788 // vector of constants for SPIR-V
3789 std::vector<spv::Id> spvConsts;
3790
3791 // Type is used for struct and array constants
3792 spv::Id typeId = convertGlslangToSpvType(glslangType);
3793
3794 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003795 glslang::TType elementType(glslangType, 0);
3796 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04003797 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003798 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003799 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003800 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04003801 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003802 } else if (glslangType.getStruct()) {
3803 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3804 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04003805 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003806 } else if (glslangType.isVector()) {
3807 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3808 bool zero = nextConst >= consts.size();
3809 switch (glslangType.getBasicType()) {
3810 case glslang::EbtInt:
3811 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3812 break;
3813 case glslang::EbtUint:
3814 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3815 break;
3816 case glslang::EbtFloat:
3817 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3818 break;
3819 case glslang::EbtDouble:
3820 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3821 break;
3822 case glslang::EbtBool:
3823 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3824 break;
3825 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003826 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003827 break;
3828 }
3829 ++nextConst;
3830 }
3831 } else {
3832 // we have a non-aggregate (scalar) constant
3833 bool zero = nextConst >= consts.size();
3834 spv::Id scalar = 0;
3835 switch (glslangType.getBasicType()) {
3836 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003837 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003838 break;
3839 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003840 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003841 break;
3842 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003843 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003844 break;
3845 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003846 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003847 break;
3848 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003849 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003850 break;
3851 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003852 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003853 break;
3854 }
3855 ++nextConst;
3856 return scalar;
3857 }
3858
3859 return builder.makeCompositeConstant(typeId, spvConsts);
3860}
3861
qining13545202016-03-21 09:51:37 -04003862namespace {
qining5c61d8e2016-03-31 13:57:28 -04003863class SpecConstantOpModeGuard {
3864public:
3865 SpecConstantOpModeGuard(spv::Builder* builder)
qining13545202016-03-21 09:51:37 -04003866 : builder_(builder) {
3867 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining5c61d8e2016-03-31 13:57:28 -04003868 builder->setToSpecConstCodeGenMode();
qining13545202016-03-21 09:51:37 -04003869 }
qining5c61d8e2016-03-31 13:57:28 -04003870 ~SpecConstantOpModeGuard() {
qining13545202016-03-21 09:51:37 -04003871 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
3872 : builder_->setToNormalCodeGenMode();
3873 }
3874
qining5c61d8e2016-03-31 13:57:28 -04003875private:
qining13545202016-03-21 09:51:37 -04003876 spv::Builder* builder_;
3877 bool previous_flag_;
3878};
3879}
3880
qining08408382016-03-21 09:51:37 -04003881// Create constant ID from const initializer sub tree.
3882spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstSubTree(
qining5c61d8e2016-03-31 13:57:28 -04003883 glslang::TIntermTyped* subTree)
3884{
qining08408382016-03-21 09:51:37 -04003885 const glslang::TType& glslangType = subTree->getType();
3886 spv::Id typeId = convertGlslangToSpvType(glslangType);
3887 bool is_spec_const = subTree->getType().getQualifier().isSpecConstant();
3888 if (const glslang::TIntermAggregate* an = subTree->getAsAggregate()) {
3889 // Aggregate node, we should generate OpConstantComposite or
3890 // OpSpecConstantComposite instruction.
qining13545202016-03-21 09:51:37 -04003891
qining08408382016-03-21 09:51:37 -04003892 std::vector<spv::Id> const_constituents;
3893 for (auto NI = an->getSequence().begin(); NI != an->getSequence().end();
3894 NI++) {
3895 const_constituents.push_back(
3896 createSpvConstantFromConstSubTree((*NI)->getAsTyped()));
3897 }
3898 // Note that constructors are aggregate nodes, so expressions like:
3899 // float x = float(y) will become an aggregate node. If 'x' is declared
3900 // as a constant, the aggregate node representing 'float(y)' will be
3901 // processed here.
3902 if (builder.isVectorType(typeId) || builder.isMatrixType(typeId) ||
3903 builder.isAggregateType(typeId)) {
3904 return builder.makeCompositeConstant(typeId, const_constituents, is_spec_const);
3905 } else {
3906 assert(builder.isScalarType(typeId) && const_constituents.size() == 1);
3907 return const_constituents.front();
3908 }
3909
qining13545202016-03-21 09:51:37 -04003910 } else if (glslang::TIntermBinary* bn = subTree->getAsBinaryNode()) {
qining08408382016-03-21 09:51:37 -04003911 // Binary operation node, we should generate OpSpecConstantOp <binary op>
3912 // This case should only happen when Specialization Constants are involved.
qining08408382016-03-21 09:51:37 -04003913
qining13545202016-03-21 09:51:37 -04003914 // Spec constants defined with binary operations and other constants requires
3915 // OpSpecConstantOp instruction.
qining5c61d8e2016-03-31 13:57:28 -04003916 SpecConstantOpModeGuard set_to_spec_const_mode(&builder);
qining13545202016-03-21 09:51:37 -04003917
3918 bn->traverse(this);
3919 return accessChainLoad(bn->getType());
3920
3921 } else if (glslang::TIntermUnary* un = subTree->getAsUnaryNode()) {
qining08408382016-03-21 09:51:37 -04003922 // Unary operation node, similar to binary operation node, should only
3923 // happen when specialization constants are involved.
qining13545202016-03-21 09:51:37 -04003924
3925 // Spec constants defined with unary operations and other constants requires
3926 // OpSpecConstantOp instruction.
qining5c61d8e2016-03-31 13:57:28 -04003927 SpecConstantOpModeGuard set_to_spec_const_mode(&builder);
qining13545202016-03-21 09:51:37 -04003928
3929 un->traverse(this);
3930 return accessChainLoad(un->getType());
qining08408382016-03-21 09:51:37 -04003931
3932 } else if (const glslang::TIntermConstantUnion* cn = subTree->getAsConstantUnion()) {
3933 // ConstantUnion node, should redirect to
3934 // createSpvConstantFromConstUnionArray
3935 int nextConst = 0;
3936 return createSpvConstantFromConstUnionArray(
3937 glslangType, cn->getConstArray(), nextConst, is_spec_const);
3938
3939 } else if (const glslang::TIntermSymbol* sn = subTree->getAsSymbolNode()) {
3940 // Symbol node. Call getSymbolId(). This should cover both cases 1) the
3941 // symbol has already been assigned an ID, 2) need a new ID for this
3942 // symbol.
3943 return getSymbolId(sn);
3944
3945 } else {
3946 spv::MissingFunctionality(
3947 "createSpvConstantFromConstSubTree() not covered TIntermTyped* const "
3948 "initializer subtree.");
3949 return spv::NoResult;
3950 }
3951}
3952
John Kessenich7c1aa102015-10-15 13:29:11 -06003953// Return true if the node is a constant or symbol whose reading has no
3954// non-trivial observable cost or effect.
3955bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3956{
3957 // don't know what this is
3958 if (node == nullptr)
3959 return false;
3960
3961 // a constant is safe
3962 if (node->getAsConstantUnion() != nullptr)
3963 return true;
3964
3965 // not a symbol means non-trivial
3966 if (node->getAsSymbolNode() == nullptr)
3967 return false;
3968
3969 // a symbol, depends on what's being read
3970 switch (node->getType().getQualifier().storage) {
3971 case glslang::EvqTemporary:
3972 case glslang::EvqGlobal:
3973 case glslang::EvqIn:
3974 case glslang::EvqInOut:
3975 case glslang::EvqConst:
3976 case glslang::EvqConstReadOnly:
3977 case glslang::EvqUniform:
3978 return true;
3979 default:
3980 return false;
3981 }
3982}
3983
3984// A node is trivial if it is a single operation with no side effects.
3985// Error on the side of saying non-trivial.
3986// Return true if trivial.
3987bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3988{
3989 if (node == nullptr)
3990 return false;
3991
3992 // symbols and constants are trivial
3993 if (isTrivialLeaf(node))
3994 return true;
3995
3996 // otherwise, it needs to be a simple operation or one or two leaf nodes
3997
3998 // not a simple operation
3999 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
4000 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
4001 if (binaryNode == nullptr && unaryNode == nullptr)
4002 return false;
4003
4004 // not on leaf nodes
4005 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
4006 return false;
4007
4008 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
4009 return false;
4010 }
4011
4012 switch (node->getAsOperator()->getOp()) {
4013 case glslang::EOpLogicalNot:
4014 case glslang::EOpConvIntToBool:
4015 case glslang::EOpConvUintToBool:
4016 case glslang::EOpConvFloatToBool:
4017 case glslang::EOpConvDoubleToBool:
4018 case glslang::EOpEqual:
4019 case glslang::EOpNotEqual:
4020 case glslang::EOpLessThan:
4021 case glslang::EOpGreaterThan:
4022 case glslang::EOpLessThanEqual:
4023 case glslang::EOpGreaterThanEqual:
4024 case glslang::EOpIndexDirect:
4025 case glslang::EOpIndexDirectStruct:
4026 case glslang::EOpLogicalXor:
4027 case glslang::EOpAny:
4028 case glslang::EOpAll:
4029 return true;
4030 default:
4031 return false;
4032 }
4033}
4034
4035// Emit short-circuiting code, where 'right' is never evaluated unless
4036// the left side is true (for &&) or false (for ||).
4037spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
4038{
4039 spv::Id boolTypeId = builder.makeBoolType();
4040
4041 // emit left operand
4042 builder.clearAccessChain();
4043 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004044 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004045
4046 // Operands to accumulate OpPhi operands
4047 std::vector<spv::Id> phiOperands;
4048 // accumulate left operand's phi information
4049 phiOperands.push_back(leftId);
4050 phiOperands.push_back(builder.getBuildPoint()->getId());
4051
4052 // Make the two kinds of operation symmetric with a "!"
4053 // || => emit "if (! left) result = right"
4054 // && => emit "if ( left) result = right"
4055 //
4056 // TODO: this runtime "not" for || could be avoided by adding functionality
4057 // to 'builder' to have an "else" without an "then"
4058 if (op == glslang::EOpLogicalOr)
4059 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
4060
4061 // make an "if" based on the left value
4062 spv::Builder::If ifBuilder(leftId, builder);
4063
4064 // emit right operand as the "then" part of the "if"
4065 builder.clearAccessChain();
4066 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08004067 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06004068
4069 // accumulate left operand's phi information
4070 phiOperands.push_back(rightId);
4071 phiOperands.push_back(builder.getBuildPoint()->getId());
4072
4073 // finish the "if"
4074 ifBuilder.makeEndIf();
4075
4076 // phi together the two results
4077 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
4078}
4079
John Kessenich140f3df2015-06-26 16:58:36 -06004080}; // end anonymous namespace
4081
4082namespace glslang {
4083
John Kessenich68d78fd2015-07-12 19:28:10 -06004084void GetSpirvVersion(std::string& version)
4085{
John Kessenich9e55f632015-07-15 10:03:39 -06004086 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06004087 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07004088 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06004089 version = buf;
4090}
4091
John Kessenich140f3df2015-06-26 16:58:36 -06004092// Write SPIR-V out to a binary file
4093void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4094{
4095 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004096 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004097 for (int i = 0; i < (int)spirv.size(); ++i) {
4098 unsigned int word = spirv[i];
4099 out.write((const char*)&word, 4);
4100 }
4101 out.close();
4102}
4103
4104//
4105// Set up the glslang traversal
4106//
4107void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4108{
4109 TIntermNode* root = intermediate.getTreeRoot();
4110
4111 if (root == 0)
4112 return;
4113
4114 glslang::GetThreadPoolAllocator().push();
4115
4116 TGlslangToSpvTraverser it(&intermediate);
4117
4118 root->traverse(&it);
4119
4120 it.dumpSpv(spirv);
4121
4122 glslang::GetThreadPoolAllocator().pop();
4123}
4124
4125}; // end namespace glslang