blob: 1c6abec994ba53ea519a6318f28b7ffe3f38c9b7 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
55#include <string>
56#include <map>
57#include <list>
58#include <vector>
59#include <stack>
60#include <fstream>
61
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
69//
70// The main holder of information for translating glslang to SPIR-V.
71//
72// Derives from the AST walking base class.
73//
74class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
75public:
76 TGlslangToSpvTraverser(const glslang::TIntermediate*);
77 virtual ~TGlslangToSpvTraverser();
78
79 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
80 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
81 void visitConstantUnion(glslang::TIntermConstantUnion*);
82 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
83 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
84 void visitSymbol(glslang::TIntermSymbol* symbol);
85 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
86 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
87 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
88
John Kessenich7ba63412015-12-20 17:37:07 -070089 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060090
91protected:
John Kessenich5e801132016-02-15 11:09:46 -070092 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -070093 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -070094 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -060095 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
96 spv::Id getSampledType(const glslang::TSampler&);
97 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070098 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -070099 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700100 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800101 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700102 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700103 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
104 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
105 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
108 void makeFunctions(const glslang::TIntermSequence&);
109 void makeGlobalInitializers(const glslang::TIntermSequence&);
110 void visitFunctions(const glslang::TIntermSequence&);
111 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800112 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600113 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
114 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600115 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
116
117 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700118 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800119 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -0700120 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600121 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
122 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800123 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600124 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createNoArgOperation(glslang::TOperator op);
126 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
127 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700128 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600129 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700130 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700131 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
132 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600133 bool isTrivialLeaf(const glslang::TIntermTyped* node);
134 bool isTrivial(const glslang::TIntermTyped* node);
135 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600136
137 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700138 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600139 int sequenceDepth;
140
141 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
142 spv::Builder builder;
143 bool inMain;
144 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700145 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700146 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600147 const glslang::TIntermediate* glslangIntermediate;
148 spv::Id stdBuiltins;
149
John Kessenich2f273362015-07-18 22:34:27 -0600150 std::unordered_map<int, spv::Id> symbolValues;
151 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
152 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700153 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600154 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600155 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600156};
157
158//
159// Helper functions for translating glslang representations to SPIR-V enumerants.
160//
161
162// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700163spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600164{
John Kessenich66e2faf2016-03-12 18:34:36 -0700165 switch (source) {
166 case glslang::EShSourceGlsl:
167 switch (profile) {
168 case ENoProfile:
169 case ECoreProfile:
170 case ECompatibilityProfile:
171 return spv::SourceLanguageGLSL;
172 case EEsProfile:
173 return spv::SourceLanguageESSL;
174 default:
175 return spv::SourceLanguageUnknown;
176 }
177 case glslang::EShSourceHlsl:
178 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600179 default:
180 return spv::SourceLanguageUnknown;
181 }
182}
183
184// Translate glslang language (stage) to SPIR-V execution model.
185spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
186{
187 switch (stage) {
188 case EShLangVertex: return spv::ExecutionModelVertex;
189 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
190 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
191 case EShLangGeometry: return spv::ExecutionModelGeometry;
192 case EShLangFragment: return spv::ExecutionModelFragment;
193 case EShLangCompute: return spv::ExecutionModelGLCompute;
194 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700195 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600196 return spv::ExecutionModelFragment;
197 }
198}
199
200// Translate glslang type to SPIR-V storage class.
201spv::StorageClass TranslateStorageClass(const glslang::TType& type)
202{
203 if (type.getQualifier().isPipeInput())
204 return spv::StorageClassInput;
205 else if (type.getQualifier().isPipeOutput())
206 return spv::StorageClassOutput;
207 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700208 if (type.getQualifier().layoutPushConstant)
209 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600210 if (type.getBasicType() == glslang::EbtBlock)
211 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800212 else if (type.getBasicType() == glslang::EbtAtomicUint)
213 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600214 else
215 return spv::StorageClassUniformConstant;
216 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
217 } else {
218 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700219 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
220 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600221 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
222 case glslang::EvqTemporary: return spv::StorageClassFunction;
223 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700224 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600225 return spv::StorageClassFunction;
226 }
227 }
228}
229
230// Translate glslang sampler type to SPIR-V dimensionality.
231spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
232{
233 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700234 case glslang::Esd1D: return spv::Dim1D;
235 case glslang::Esd2D: return spv::Dim2D;
236 case glslang::Esd3D: return spv::Dim3D;
237 case glslang::EsdCube: return spv::DimCube;
238 case glslang::EsdRect: return spv::DimRect;
239 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700240 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600241 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700242 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600243 return spv::Dim2D;
244 }
245}
246
247// Translate glslang type to SPIR-V precision decorations.
248spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
249{
250 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700251 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600252 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600253 default:
254 return spv::NoPrecision;
255 }
256}
257
258// Translate glslang type to SPIR-V block decorations.
259spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
260{
261 if (type.getBasicType() == glslang::EbtBlock) {
262 switch (type.getQualifier().storage) {
263 case glslang::EvqUniform: return spv::DecorationBlock;
264 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
265 case glslang::EvqVaryingIn: return spv::DecorationBlock;
266 case glslang::EvqVaryingOut: return spv::DecorationBlock;
267 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700268 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600269 break;
270 }
271 }
272
273 return (spv::Decoration)spv::BadValue;
274}
275
Rex Xu1da878f2016-02-21 20:59:01 +0800276// Translate glslang type to SPIR-V memory decorations.
277void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
278{
279 if (qualifier.coherent)
280 memory.push_back(spv::DecorationCoherent);
281 if (qualifier.volatil)
282 memory.push_back(spv::DecorationVolatile);
283 if (qualifier.restrict)
284 memory.push_back(spv::DecorationRestrict);
285 if (qualifier.readonly)
286 memory.push_back(spv::DecorationNonWritable);
287 if (qualifier.writeonly)
288 memory.push_back(spv::DecorationNonReadable);
289}
290
John Kessenich140f3df2015-06-26 16:58:36 -0600291// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700292spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600293{
294 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700295 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600296 case glslang::ElmRowMajor:
297 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700298 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600299 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700300 default:
301 // opaque layouts don't need a majorness
302 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600303 }
304 } else {
305 switch (type.getBasicType()) {
306 default:
307 return (spv::Decoration)spv::BadValue;
308 break;
309 case glslang::EbtBlock:
310 switch (type.getQualifier().storage) {
311 case glslang::EvqUniform:
312 case glslang::EvqBuffer:
313 switch (type.getQualifier().layoutPacking) {
314 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600315 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
316 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600317 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600318 }
319 case glslang::EvqVaryingIn:
320 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700321 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return (spv::Decoration)spv::BadValue;
323 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700324 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600325 return (spv::Decoration)spv::BadValue;
326 }
327 }
328 }
329}
330
331// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700332// Returns spv::Decoration(spv::BadValue) when no decoration
333// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700334spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600335{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700336 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700337 // Smooth decoration doesn't exist in SPIR-V 1.0
338 return (spv::Decoration)spv::BadValue;
339 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700340 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700341 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700342 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600343 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700344 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600345 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700346 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600347 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700348 else if (qualifier.sample) {
349 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600350 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700351 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600352 return (spv::Decoration)spv::BadValue;
353}
354
John Kessenich92187592016-02-01 13:45:25 -0700355// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700356spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600357{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700358 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600359 return spv::DecorationInvariant;
360 else
361 return (spv::Decoration)spv::BadValue;
362}
363
364// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700365spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600366{
367 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700368 case glslang::EbvPointSize:
369 switch (glslangIntermediate->getStage()) {
370 case EShLangGeometry:
371 builder.addCapability(spv::CapabilityGeometryPointSize);
372 break;
373 case EShLangTessControl:
374 case EShLangTessEvaluation:
375 builder.addCapability(spv::CapabilityTessellationPointSize);
376 break;
baldurk9cc6cd32016-02-10 20:04:20 +0100377 default:
378 break;
John Kessenich92187592016-02-01 13:45:25 -0700379 }
380 return spv::BuiltInPointSize;
381
382 case glslang::EbvClipDistance:
383 builder.addCapability(spv::CapabilityClipDistance);
384 return spv::BuiltInClipDistance;
385
386 case glslang::EbvCullDistance:
387 builder.addCapability(spv::CapabilityCullDistance);
388 return spv::BuiltInCullDistance;
389
390 case glslang::EbvViewportIndex:
qining3d7b89a2016-03-07 21:32:15 -0500391 builder.addCapability(spv::CapabilityMultiViewport);
John Kessenich92187592016-02-01 13:45:25 -0700392 return spv::BuiltInViewportIndex;
393
John Kessenich5e801132016-02-15 11:09:46 -0700394 case glslang::EbvSampleId:
395 builder.addCapability(spv::CapabilitySampleRateShading);
396 return spv::BuiltInSampleId;
397
398 case glslang::EbvSamplePosition:
399 builder.addCapability(spv::CapabilitySampleRateShading);
400 return spv::BuiltInSamplePosition;
401
402 case glslang::EbvSampleMask:
403 builder.addCapability(spv::CapabilitySampleRateShading);
404 return spv::BuiltInSampleMask;
405
John Kessenich140f3df2015-06-26 16:58:36 -0600406 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600407 case glslang::EbvVertexId: return spv::BuiltInVertexId;
408 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700409 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
410 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600411 case glslang::EbvBaseVertex:
412 case glslang::EbvBaseInstance:
413 case glslang::EbvDrawId:
414 // TODO: Add SPIR-V builtin ID.
415 spv::MissingFunctionality("Draw parameters");
416 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600417 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
418 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
419 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600420 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
421 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
422 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
423 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
424 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
425 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
426 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600427 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
428 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
429 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
430 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
431 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
432 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
433 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
434 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
435 default: return (spv::BuiltIn)spv::BadValue;
436 }
437}
438
Rex Xufc618912015-09-09 16:42:49 +0800439// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700440spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800441{
442 assert(type.getBasicType() == glslang::EbtSampler);
443
John Kessenich5d0fa972016-02-15 11:57:00 -0700444 // Check for capabilities
445 switch (type.getQualifier().layoutFormat) {
446 case glslang::ElfRg32f:
447 case glslang::ElfRg16f:
448 case glslang::ElfR11fG11fB10f:
449 case glslang::ElfR16f:
450 case glslang::ElfRgba16:
451 case glslang::ElfRgb10A2:
452 case glslang::ElfRg16:
453 case glslang::ElfRg8:
454 case glslang::ElfR16:
455 case glslang::ElfR8:
456 case glslang::ElfRgba16Snorm:
457 case glslang::ElfRg16Snorm:
458 case glslang::ElfRg8Snorm:
459 case glslang::ElfR16Snorm:
460 case glslang::ElfR8Snorm:
461
462 case glslang::ElfRg32i:
463 case glslang::ElfRg16i:
464 case glslang::ElfRg8i:
465 case glslang::ElfR16i:
466 case glslang::ElfR8i:
467
468 case glslang::ElfRgb10a2ui:
469 case glslang::ElfRg32ui:
470 case glslang::ElfRg16ui:
471 case glslang::ElfRg8ui:
472 case glslang::ElfR16ui:
473 case glslang::ElfR8ui:
474 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
475 break;
476
477 default:
478 break;
479 }
480
481 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800482 switch (type.getQualifier().layoutFormat) {
483 case glslang::ElfNone: return spv::ImageFormatUnknown;
484 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
485 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
486 case glslang::ElfR32f: return spv::ImageFormatR32f;
487 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
488 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
489 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
490 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
491 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
492 case glslang::ElfR16f: return spv::ImageFormatR16f;
493 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
494 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
495 case glslang::ElfRg16: return spv::ImageFormatRg16;
496 case glslang::ElfRg8: return spv::ImageFormatRg8;
497 case glslang::ElfR16: return spv::ImageFormatR16;
498 case glslang::ElfR8: return spv::ImageFormatR8;
499 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
500 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
501 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
502 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
503 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
504 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
505 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
506 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
507 case glslang::ElfR32i: return spv::ImageFormatR32i;
508 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
509 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
510 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
511 case glslang::ElfR16i: return spv::ImageFormatR16i;
512 case glslang::ElfR8i: return spv::ImageFormatR8i;
513 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
514 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
515 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
516 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
517 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
518 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
519 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
520 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
521 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
522 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
523 default: return (spv::ImageFormat)spv::BadValue;
524 }
525}
526
John Kessenich6c292d32016-02-15 20:58:50 -0700527// Return whether or not the given type is something that should be tied to a
528// descriptor set.
529bool IsDescriptorResource(const glslang::TType& type)
530{
John Kessenichf7497e22016-03-08 21:36:22 -0700531 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700532 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700533 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700534
535 // non block...
536 // basically samplerXXX/subpass/sampler/texture are all included
537 // if they are the global-scope-class, not the function parameter
538 // (or local, if they ever exist) class.
539 if (type.getBasicType() == glslang::EbtSampler)
540 return type.getQualifier().isUniformOrBuffer();
541
542 // None of the above.
543 return false;
544}
545
John Kesseniche0b6cad2015-12-24 10:30:13 -0700546void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
547{
548 if (child.layoutMatrix == glslang::ElmNone)
549 child.layoutMatrix = parent.layoutMatrix;
550
551 if (parent.invariant)
552 child.invariant = true;
553 if (parent.nopersp)
554 child.nopersp = true;
555 if (parent.flat)
556 child.flat = true;
557 if (parent.centroid)
558 child.centroid = true;
559 if (parent.patch)
560 child.patch = true;
561 if (parent.sample)
562 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800563 if (parent.coherent)
564 child.coherent = true;
565 if (parent.volatil)
566 child.volatil = true;
567 if (parent.restrict)
568 child.restrict = true;
569 if (parent.readonly)
570 child.readonly = true;
571 if (parent.writeonly)
572 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700573}
574
575bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
576{
John Kessenich7b9fa252016-01-21 18:56:57 -0700577 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700578 // - struct members can inherit from a struct declaration
579 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
580 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700581 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700582}
583
John Kessenich140f3df2015-06-26 16:58:36 -0600584//
585// Implement the TGlslangToSpvTraverser class.
586//
587
588TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
589 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700590 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600591 inMain(false), mainTerminated(false), linkageOnly(false),
592 glslangIntermediate(glslangIntermediate)
593{
594 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
595
596 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700597 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600598 stdBuiltins = builder.import("GLSL.std.450");
599 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenich4d65ee32016-03-12 18:17:47 -0700600 shaderEntry = builder.makeEntrypoint(glslangIntermediate->getEntryPoint().c_str());
601 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPoint().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600602
603 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600604 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
605 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600606 builder.addSourceExtension(it->c_str());
607
608 // Add the top-level modes for this shader.
609
John Kessenich92187592016-02-01 13:45:25 -0700610 if (glslangIntermediate->getXfbMode()) {
611 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600612 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700613 }
John Kessenich140f3df2015-06-26 16:58:36 -0600614
615 unsigned int mode;
616 switch (glslangIntermediate->getStage()) {
617 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600618 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600619 break;
620
621 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600622 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600623 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
624 break;
625
626 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600627 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600628 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700629 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
630 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
631 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600632 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600633 }
634 if (mode != spv::BadValue)
635 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
636
John Kesseniche6903322015-10-13 16:29:02 -0600637 switch (glslangIntermediate->getVertexSpacing()) {
638 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
639 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
640 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
641 default: mode = spv::BadValue; break;
642 }
643 if (mode != spv::BadValue)
644 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
645
646 switch (glslangIntermediate->getVertexOrder()) {
647 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
648 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
649 default: mode = spv::BadValue; break;
650 }
651 if (mode != spv::BadValue)
652 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
653
654 if (glslangIntermediate->getPointMode())
655 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600656 break;
657
658 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600659 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600660 switch (glslangIntermediate->getInputPrimitive()) {
661 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
662 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
663 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700664 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600665 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
666 default: mode = spv::BadValue; break;
667 }
668 if (mode != spv::BadValue)
669 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600670
John Kessenich140f3df2015-06-26 16:58:36 -0600671 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
672
673 switch (glslangIntermediate->getOutputPrimitive()) {
674 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
675 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
676 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
677 default: mode = spv::BadValue; break;
678 }
679 if (mode != spv::BadValue)
680 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
681 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
682 break;
683
684 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600685 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600686 if (glslangIntermediate->getPixelCenterInteger())
687 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600688
John Kessenich140f3df2015-06-26 16:58:36 -0600689 if (glslangIntermediate->getOriginUpperLeft())
690 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600691 else
692 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600693
694 if (glslangIntermediate->getEarlyFragmentTests())
695 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
696
697 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600698 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
699 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
700 default: mode = spv::BadValue; break;
701 }
702 if (mode != spv::BadValue)
703 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
704
705 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
706 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600707 break;
708
709 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600710 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600711 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
712 glslangIntermediate->getLocalSize(1),
713 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600714 break;
715
716 default:
717 break;
718 }
719
720}
721
John Kessenich7ba63412015-12-20 17:37:07 -0700722// Finish everything and dump
723void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
724{
725 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +0100726 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
727 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -0700728
qiningda397332016-03-09 19:54:03 -0500729 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -0700730 builder.dump(out);
731}
732
John Kessenich140f3df2015-06-26 16:58:36 -0600733TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
734{
735 if (! mainTerminated) {
736 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
737 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600738 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600739 }
740}
741
742//
743// Implement the traversal functions.
744//
745// Return true from interior nodes to have the external traversal
746// continue on to children. Return false if children were
747// already processed.
748//
749
750//
751// Symbols can turn into
752// - uniform/input reads
753// - output writes
754// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
755// - something simple that degenerates into the last bullet
756//
757void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
758{
759 // getSymbolId() will set up all the IO decorations on the first call.
760 // Formal function parameters were mapped during makeFunctions().
761 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700762
763 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
764 if (builder.isPointer(id)) {
765 spv::StorageClass sc = builder.getStorageClass(id);
766 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
767 iOSet.insert(id);
768 }
769
770 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700771 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600772 // Prepare to generate code for the access
773
774 // L-value chains will be computed left to right. We're on the symbol now,
775 // which is the left-most part of the access chain, so now is "clear" time,
776 // followed by setting the base.
777 builder.clearAccessChain();
778
779 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700780 // except for
781 // A) "const in" arguments to a function, which are an intermediate object.
782 // See comments in handleUserFunctionCall().
783 // B) Specialization constants (normal constant don't even come in as a variable),
784 // These are also pure R-values.
785 glslang::TQualifier qualifier = symbol->getQualifier();
786 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
787 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600788 builder.setAccessChainRValue(id);
789 else
790 builder.setAccessChainLValue(id);
791 }
792}
793
794bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
795{
796 // First, handle special cases
797 switch (node->getOp()) {
798 case glslang::EOpAssign:
799 case glslang::EOpAddAssign:
800 case glslang::EOpSubAssign:
801 case glslang::EOpMulAssign:
802 case glslang::EOpVectorTimesMatrixAssign:
803 case glslang::EOpVectorTimesScalarAssign:
804 case glslang::EOpMatrixTimesScalarAssign:
805 case glslang::EOpMatrixTimesMatrixAssign:
806 case glslang::EOpDivAssign:
807 case glslang::EOpModAssign:
808 case glslang::EOpAndAssign:
809 case glslang::EOpInclusiveOrAssign:
810 case glslang::EOpExclusiveOrAssign:
811 case glslang::EOpLeftShiftAssign:
812 case glslang::EOpRightShiftAssign:
813 // A bin-op assign "a += b" means the same thing as "a = a + b"
814 // where a is evaluated before b. For a simple assignment, GLSL
815 // says to evaluate the left before the right. So, always, left
816 // node then right node.
817 {
818 // get the left l-value, save it away
819 builder.clearAccessChain();
820 node->getLeft()->traverse(this);
821 spv::Builder::AccessChain lValue = builder.getAccessChain();
822
823 // evaluate the right
824 builder.clearAccessChain();
825 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700826 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600827
828 if (node->getOp() != glslang::EOpAssign) {
829 // the left is also an r-value
830 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700831 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600832
833 // do the operation
834 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
835 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
836 node->getType().getBasicType());
837
838 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700839 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600840 }
841
842 // store the result
843 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800844 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600845
846 // assignments are expressions having an rValue after they are evaluated...
847 builder.clearAccessChain();
848 builder.setAccessChainRValue(rValue);
849 }
850 return false;
851 case glslang::EOpIndexDirect:
852 case glslang::EOpIndexDirectStruct:
853 {
854 // Get the left part of the access chain.
855 node->getLeft()->traverse(this);
856
857 // Add the next element in the chain
858
John Kessenich55e7d112015-11-15 21:33:39 -0700859 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600860 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
861 // This may be, e.g., an anonymous block-member selection, which generally need
862 // index remapping due to hidden members in anonymous blocks.
863 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700864 assert(remapper.size() > 0);
865 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600866 }
867
868 if (! node->getLeft()->getType().isArray() &&
869 node->getLeft()->getType().isVector() &&
870 node->getOp() == glslang::EOpIndexDirect) {
871 // This is essentially a hard-coded vector swizzle of size 1,
872 // so short circuit the access-chain stuff with a swizzle.
873 std::vector<unsigned> swizzle;
874 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600875 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600876 } else {
877 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600878 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600879 }
880 }
881 return false;
882 case glslang::EOpIndexIndirect:
883 {
884 // Structure or array or vector indirection.
885 // Will use native SPIR-V access-chain for struct and array indirection;
886 // matrices are arrays of vectors, so will also work for a matrix.
887 // Will use the access chain's 'component' for variable index into a vector.
888
889 // This adapter is building access chains left to right.
890 // Set up the access chain to the left.
891 node->getLeft()->traverse(this);
892
893 // save it so that computing the right side doesn't trash it
894 spv::Builder::AccessChain partial = builder.getAccessChain();
895
896 // compute the next index in the chain
897 builder.clearAccessChain();
898 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700899 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600900
901 // restore the saved access chain
902 builder.setAccessChain(partial);
903
904 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600905 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600906 else
John Kessenichfa668da2015-09-13 14:46:30 -0600907 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600908 }
909 return false;
910 case glslang::EOpVectorSwizzle:
911 {
912 node->getLeft()->traverse(this);
913 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
914 std::vector<unsigned> swizzle;
915 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
916 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600917 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600918 }
919 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600920 case glslang::EOpLogicalOr:
921 case glslang::EOpLogicalAnd:
922 {
923
924 // These may require short circuiting, but can sometimes be done as straight
925 // binary operations. The right operand must be short circuited if it has
926 // side effects, and should probably be if it is complex.
927 if (isTrivial(node->getRight()->getAsTyped()))
928 break; // handle below as a normal binary operation
929 // otherwise, we need to do dynamic short circuiting on the right operand
930 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
931 builder.clearAccessChain();
932 builder.setAccessChainRValue(result);
933 }
934 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600935 default:
936 break;
937 }
938
939 // Assume generic binary op...
940
John Kessenich32cfd492016-02-02 12:37:46 -0700941 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600942 builder.clearAccessChain();
943 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700944 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600945
John Kessenich32cfd492016-02-02 12:37:46 -0700946 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600947 builder.clearAccessChain();
948 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700949 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600950
John Kessenich32cfd492016-02-02 12:37:46 -0700951 // get result
952 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
953 convertGlslangToSpvType(node->getType()), left, right,
954 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600955
John Kessenich50e57562015-12-21 21:21:11 -0700956 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600957 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700958 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700959 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600960 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600961 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600962 return false;
963 }
John Kessenich140f3df2015-06-26 16:58:36 -0600964}
965
966bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
967{
John Kessenichfc51d282015-08-19 13:34:18 -0600968 spv::Id result = spv::NoResult;
969
970 // try texturing first
971 result = createImageTextureFunctionCall(node);
972 if (result != spv::NoResult) {
973 builder.clearAccessChain();
974 builder.setAccessChainRValue(result);
975
976 return false; // done with this node
977 }
978
979 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600980
981 if (node->getOp() == glslang::EOpArrayLength) {
982 // Quite special; won't want to evaluate the operand.
983
984 // Normal .length() would have been constant folded by the front-end.
985 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600986 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600987 assert(node->getOperand()->getType().isRuntimeSizedArray());
988 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
989 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600990 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
991 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600992
993 builder.clearAccessChain();
994 builder.setAccessChainRValue(length);
995
996 return false;
997 }
998
John Kessenichfc51d282015-08-19 13:34:18 -0600999 // Start by evaluating the operand
1000
John Kessenich140f3df2015-06-26 16:58:36 -06001001 builder.clearAccessChain();
1002 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001003
Rex Xufc618912015-09-09 16:42:49 +08001004 spv::Id operand = spv::NoResult;
1005
1006 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1007 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001008 node->getOp() == glslang::EOpAtomicCounter ||
1009 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001010 operand = builder.accessChainGetLValue(); // Special case l-value operands
1011 else
John Kessenich32cfd492016-02-02 12:37:46 -07001012 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001013
1014 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1015
1016 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001017 if (! result)
1018 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -06001019
1020 // if not, then possibly an operation
1021 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -07001022 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001023
1024 if (result) {
1025 builder.clearAccessChain();
1026 builder.setAccessChainRValue(result);
1027
1028 return false; // done with this node
1029 }
1030
1031 // it must be a special case, check...
1032 switch (node->getOp()) {
1033 case glslang::EOpPostIncrement:
1034 case glslang::EOpPostDecrement:
1035 case glslang::EOpPreIncrement:
1036 case glslang::EOpPreDecrement:
1037 {
1038 // we need the integer value "1" or the floating point "1.0" to add/subtract
1039 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1040 builder.makeFloatConstant(1.0F) :
1041 builder.makeIntConstant(1);
1042 glslang::TOperator op;
1043 if (node->getOp() == glslang::EOpPreIncrement ||
1044 node->getOp() == glslang::EOpPostIncrement)
1045 op = glslang::EOpAdd;
1046 else
1047 op = glslang::EOpSub;
1048
1049 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1050 convertGlslangToSpvType(node->getType()), operand, one,
1051 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001052 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001053
1054 // The result of operation is always stored, but conditionally the
1055 // consumed result. The consumed result is always an r-value.
1056 builder.accessChainStore(result);
1057 builder.clearAccessChain();
1058 if (node->getOp() == glslang::EOpPreIncrement ||
1059 node->getOp() == glslang::EOpPreDecrement)
1060 builder.setAccessChainRValue(result);
1061 else
1062 builder.setAccessChainRValue(operand);
1063 }
1064
1065 return false;
1066
1067 case glslang::EOpEmitStreamVertex:
1068 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1069 return false;
1070 case glslang::EOpEndStreamPrimitive:
1071 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1072 return false;
1073
1074 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001075 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001076 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001077 }
John Kessenich140f3df2015-06-26 16:58:36 -06001078}
1079
1080bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1081{
John Kessenichfc51d282015-08-19 13:34:18 -06001082 spv::Id result = spv::NoResult;
1083
1084 // try texturing
1085 result = createImageTextureFunctionCall(node);
1086 if (result != spv::NoResult) {
1087 builder.clearAccessChain();
1088 builder.setAccessChainRValue(result);
1089
1090 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001091 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001092 // "imageStore" is a special case, which has no result
1093 return false;
1094 }
John Kessenichfc51d282015-08-19 13:34:18 -06001095
John Kessenich140f3df2015-06-26 16:58:36 -06001096 glslang::TOperator binOp = glslang::EOpNull;
1097 bool reduceComparison = true;
1098 bool isMatrix = false;
1099 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001100 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001101
1102 assert(node->getOp());
1103
1104 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1105
1106 switch (node->getOp()) {
1107 case glslang::EOpSequence:
1108 {
1109 if (preVisit)
1110 ++sequenceDepth;
1111 else
1112 --sequenceDepth;
1113
1114 if (sequenceDepth == 1) {
1115 // If this is the parent node of all the functions, we want to see them
1116 // early, so all call points have actual SPIR-V functions to reference.
1117 // In all cases, still let the traverser visit the children for us.
1118 makeFunctions(node->getAsAggregate()->getSequence());
1119
1120 // Also, we want all globals initializers to go into the entry of main(), before
1121 // anything else gets there, so visit out of order, doing them all now.
1122 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1123
1124 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1125 // so do them manually.
1126 visitFunctions(node->getAsAggregate()->getSequence());
1127
1128 return false;
1129 }
1130
1131 return true;
1132 }
1133 case glslang::EOpLinkerObjects:
1134 {
1135 if (visit == glslang::EvPreVisit)
1136 linkageOnly = true;
1137 else
1138 linkageOnly = false;
1139
1140 return true;
1141 }
1142 case glslang::EOpComma:
1143 {
1144 // processing from left to right naturally leaves the right-most
1145 // lying around in the access chain
1146 glslang::TIntermSequence& glslangOperands = node->getSequence();
1147 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1148 glslangOperands[i]->traverse(this);
1149
1150 return false;
1151 }
1152 case glslang::EOpFunction:
1153 if (visit == glslang::EvPreVisit) {
1154 if (isShaderEntrypoint(node)) {
1155 inMain = true;
1156 builder.setBuildPoint(shaderEntry->getLastBlock());
1157 } else {
1158 handleFunctionEntry(node);
1159 }
1160 } else {
1161 if (inMain)
1162 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001163 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001164 inMain = false;
1165 }
1166
1167 return true;
1168 case glslang::EOpParameters:
1169 // Parameters will have been consumed by EOpFunction processing, but not
1170 // the body, so we still visited the function node's children, making this
1171 // child redundant.
1172 return false;
1173 case glslang::EOpFunctionCall:
1174 {
1175 if (node->isUserDefined())
1176 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001177 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1178 if (result) {
1179 builder.clearAccessChain();
1180 builder.setAccessChainRValue(result);
1181 } else
1182 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001183
1184 return false;
1185 }
1186 case glslang::EOpConstructMat2x2:
1187 case glslang::EOpConstructMat2x3:
1188 case glslang::EOpConstructMat2x4:
1189 case glslang::EOpConstructMat3x2:
1190 case glslang::EOpConstructMat3x3:
1191 case glslang::EOpConstructMat3x4:
1192 case glslang::EOpConstructMat4x2:
1193 case glslang::EOpConstructMat4x3:
1194 case glslang::EOpConstructMat4x4:
1195 case glslang::EOpConstructDMat2x2:
1196 case glslang::EOpConstructDMat2x3:
1197 case glslang::EOpConstructDMat2x4:
1198 case glslang::EOpConstructDMat3x2:
1199 case glslang::EOpConstructDMat3x3:
1200 case glslang::EOpConstructDMat3x4:
1201 case glslang::EOpConstructDMat4x2:
1202 case glslang::EOpConstructDMat4x3:
1203 case glslang::EOpConstructDMat4x4:
1204 isMatrix = true;
1205 // fall through
1206 case glslang::EOpConstructFloat:
1207 case glslang::EOpConstructVec2:
1208 case glslang::EOpConstructVec3:
1209 case glslang::EOpConstructVec4:
1210 case glslang::EOpConstructDouble:
1211 case glslang::EOpConstructDVec2:
1212 case glslang::EOpConstructDVec3:
1213 case glslang::EOpConstructDVec4:
1214 case glslang::EOpConstructBool:
1215 case glslang::EOpConstructBVec2:
1216 case glslang::EOpConstructBVec3:
1217 case glslang::EOpConstructBVec4:
1218 case glslang::EOpConstructInt:
1219 case glslang::EOpConstructIVec2:
1220 case glslang::EOpConstructIVec3:
1221 case glslang::EOpConstructIVec4:
1222 case glslang::EOpConstructUint:
1223 case glslang::EOpConstructUVec2:
1224 case glslang::EOpConstructUVec3:
1225 case glslang::EOpConstructUVec4:
1226 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001227 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001228 {
1229 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001230 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001231 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1232 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001233 if (node->getOp() == glslang::EOpConstructTextureSampler)
1234 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1235 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001236 std::vector<spv::Id> constituents;
1237 for (int c = 0; c < (int)arguments.size(); ++c)
1238 constituents.push_back(arguments[c]);
1239 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001240 } else if (isMatrix)
1241 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1242 else
1243 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001244
1245 builder.clearAccessChain();
1246 builder.setAccessChainRValue(constructed);
1247
1248 return false;
1249 }
1250
1251 // These six are component-wise compares with component-wise results.
1252 // Forward on to createBinaryOperation(), requesting a vector result.
1253 case glslang::EOpLessThan:
1254 case glslang::EOpGreaterThan:
1255 case glslang::EOpLessThanEqual:
1256 case glslang::EOpGreaterThanEqual:
1257 case glslang::EOpVectorEqual:
1258 case glslang::EOpVectorNotEqual:
1259 {
1260 // Map the operation to a binary
1261 binOp = node->getOp();
1262 reduceComparison = false;
1263 switch (node->getOp()) {
1264 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1265 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1266 default: binOp = node->getOp(); break;
1267 }
1268
1269 break;
1270 }
1271 case glslang::EOpMul:
1272 // compontent-wise matrix multiply
1273 binOp = glslang::EOpMul;
1274 break;
1275 case glslang::EOpOuterProduct:
1276 // two vectors multiplied to make a matrix
1277 binOp = glslang::EOpOuterProduct;
1278 break;
1279 case glslang::EOpDot:
1280 {
1281 // for scalar dot product, use multiply
1282 glslang::TIntermSequence& glslangOperands = node->getSequence();
1283 if (! glslangOperands[0]->getAsTyped()->isVector())
1284 binOp = glslang::EOpMul;
1285 break;
1286 }
1287 case glslang::EOpMod:
1288 // when an aggregate, this is the floating-point mod built-in function,
1289 // which can be emitted by the one in createBinaryOperation()
1290 binOp = glslang::EOpMod;
1291 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001292 case glslang::EOpEmitVertex:
1293 case glslang::EOpEndPrimitive:
1294 case glslang::EOpBarrier:
1295 case glslang::EOpMemoryBarrier:
1296 case glslang::EOpMemoryBarrierAtomicCounter:
1297 case glslang::EOpMemoryBarrierBuffer:
1298 case glslang::EOpMemoryBarrierImage:
1299 case glslang::EOpMemoryBarrierShared:
1300 case glslang::EOpGroupMemoryBarrier:
1301 noReturnValue = true;
1302 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1303 break;
1304
John Kessenich426394d2015-07-23 10:22:48 -06001305 case glslang::EOpAtomicAdd:
1306 case glslang::EOpAtomicMin:
1307 case glslang::EOpAtomicMax:
1308 case glslang::EOpAtomicAnd:
1309 case glslang::EOpAtomicOr:
1310 case glslang::EOpAtomicXor:
1311 case glslang::EOpAtomicExchange:
1312 case glslang::EOpAtomicCompSwap:
1313 atomic = true;
1314 break;
1315
John Kessenich140f3df2015-06-26 16:58:36 -06001316 default:
1317 break;
1318 }
1319
1320 //
1321 // See if it maps to a regular operation.
1322 //
John Kessenich140f3df2015-06-26 16:58:36 -06001323 if (binOp != glslang::EOpNull) {
1324 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1325 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1326 assert(left && right);
1327
1328 builder.clearAccessChain();
1329 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001330 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001331
1332 builder.clearAccessChain();
1333 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001334 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001335
1336 result = createBinaryOperation(binOp, precision,
1337 convertGlslangToSpvType(node->getType()), leftId, rightId,
1338 left->getType().getBasicType(), reduceComparison);
1339
1340 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001341 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001342 builder.clearAccessChain();
1343 builder.setAccessChainRValue(result);
1344
1345 return false;
1346 }
1347
John Kessenich426394d2015-07-23 10:22:48 -06001348 //
1349 // Create the list of operands.
1350 //
John Kessenich140f3df2015-06-26 16:58:36 -06001351 glslang::TIntermSequence& glslangOperands = node->getSequence();
1352 std::vector<spv::Id> operands;
1353 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1354 builder.clearAccessChain();
1355 glslangOperands[arg]->traverse(this);
1356
1357 // special case l-value operands; there are just a few
1358 bool lvalue = false;
1359 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001360 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001361 case glslang::EOpModf:
1362 if (arg == 1)
1363 lvalue = true;
1364 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001365 case glslang::EOpInterpolateAtSample:
1366 case glslang::EOpInterpolateAtOffset:
1367 if (arg == 0)
1368 lvalue = true;
1369 break;
Rex Xud4782c12015-09-06 16:30:11 +08001370 case glslang::EOpAtomicAdd:
1371 case glslang::EOpAtomicMin:
1372 case glslang::EOpAtomicMax:
1373 case glslang::EOpAtomicAnd:
1374 case glslang::EOpAtomicOr:
1375 case glslang::EOpAtomicXor:
1376 case glslang::EOpAtomicExchange:
1377 case glslang::EOpAtomicCompSwap:
1378 if (arg == 0)
1379 lvalue = true;
1380 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001381 case glslang::EOpAddCarry:
1382 case glslang::EOpSubBorrow:
1383 if (arg == 2)
1384 lvalue = true;
1385 break;
1386 case glslang::EOpUMulExtended:
1387 case glslang::EOpIMulExtended:
1388 if (arg >= 2)
1389 lvalue = true;
1390 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001391 default:
1392 break;
1393 }
1394 if (lvalue)
1395 operands.push_back(builder.accessChainGetLValue());
1396 else
John Kessenich32cfd492016-02-02 12:37:46 -07001397 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001398 }
John Kessenich426394d2015-07-23 10:22:48 -06001399
1400 if (atomic) {
1401 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001402 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001403 } else {
1404 // Pass through to generic operations.
1405 switch (glslangOperands.size()) {
1406 case 0:
1407 result = createNoArgOperation(node->getOp());
1408 break;
1409 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001410 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001411 break;
1412 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001413 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001414 break;
1415 }
John Kessenich140f3df2015-06-26 16:58:36 -06001416 }
1417
1418 if (noReturnValue)
1419 return false;
1420
1421 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001422 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001423 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001424 } else {
1425 builder.clearAccessChain();
1426 builder.setAccessChainRValue(result);
1427 return false;
1428 }
1429}
1430
1431bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1432{
1433 // This path handles both if-then-else and ?:
1434 // The if-then-else has a node type of void, while
1435 // ?: has a non-void node type
1436 spv::Id result = 0;
1437 if (node->getBasicType() != glslang::EbtVoid) {
1438 // don't handle this as just on-the-fly temporaries, because there will be two names
1439 // and better to leave SSA to later passes
1440 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1441 }
1442
1443 // emit the condition before doing anything with selection
1444 node->getCondition()->traverse(this);
1445
1446 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001447 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001448
1449 if (node->getTrueBlock()) {
1450 // emit the "then" statement
1451 node->getTrueBlock()->traverse(this);
1452 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001453 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001454 }
1455
1456 if (node->getFalseBlock()) {
1457 ifBuilder.makeBeginElse();
1458 // emit the "else" statement
1459 node->getFalseBlock()->traverse(this);
1460 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001461 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001462 }
1463
1464 ifBuilder.makeEndIf();
1465
1466 if (result) {
1467 // GLSL only has r-values as the result of a :?, but
1468 // if we have an l-value, that can be more efficient if it will
1469 // become the base of a complex r-value expression, because the
1470 // next layer copies r-values into memory to use the access-chain mechanism
1471 builder.clearAccessChain();
1472 builder.setAccessChainLValue(result);
1473 }
1474
1475 return false;
1476}
1477
1478bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1479{
1480 // emit and get the condition before doing anything with switch
1481 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001482 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001483
1484 // browse the children to sort out code segments
1485 int defaultSegment = -1;
1486 std::vector<TIntermNode*> codeSegments;
1487 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1488 std::vector<int> caseValues;
1489 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1490 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1491 TIntermNode* child = *c;
1492 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001493 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001494 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001495 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001496 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1497 } else
1498 codeSegments.push_back(child);
1499 }
1500
1501 // handle the case where the last code segment is missing, due to no code
1502 // statements between the last case and the end of the switch statement
1503 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1504 (int)codeSegments.size() == defaultSegment)
1505 codeSegments.push_back(nullptr);
1506
1507 // make the switch statement
1508 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001509 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001510
1511 // emit all the code in the segments
1512 breakForLoop.push(false);
1513 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1514 builder.nextSwitchSegment(segmentBlocks, s);
1515 if (codeSegments[s])
1516 codeSegments[s]->traverse(this);
1517 else
1518 builder.addSwitchBreak();
1519 }
1520 breakForLoop.pop();
1521
1522 builder.endSwitch(segmentBlocks);
1523
1524 return false;
1525}
1526
1527void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1528{
1529 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001530 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001531
1532 builder.clearAccessChain();
1533 builder.setAccessChainRValue(constant);
1534}
1535
1536bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1537{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001538 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001539 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001540 // Spec requires back edges to target header blocks, and every header block
1541 // must dominate its merge block. Make a header block first to ensure these
1542 // conditions are met. By definition, it will contain OpLoopMerge, followed
1543 // by a block-ending branch. But we don't want to put any other body/test
1544 // instructions in it, since the body/test may have arbitrary instructions,
1545 // including merges of its own.
1546 builder.setBuildPoint(&blocks.head);
1547 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001548 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001549 spv::Block& test = builder.makeNewBlock();
1550 builder.createBranch(&test);
1551
1552 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001553 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001554 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001555 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001556 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1557
1558 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001559 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001560 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001561 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001562 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001563 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001564
1565 builder.setBuildPoint(&blocks.continue_target);
1566 if (node->getTerminal())
1567 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001568 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001569 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001570 builder.createBranch(&blocks.body);
1571
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001572 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001573 builder.setBuildPoint(&blocks.body);
1574 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001575 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001576 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001577 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001578
1579 builder.setBuildPoint(&blocks.continue_target);
1580 if (node->getTerminal())
1581 node->getTerminal()->traverse(this);
1582 if (node->getTest()) {
1583 node->getTest()->traverse(this);
1584 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001585 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001586 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001587 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001588 // TODO: unless there was a break/return/discard instruction
1589 // somewhere in the body, this is an infinite loop, so we should
1590 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001591 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001592 }
John Kessenich140f3df2015-06-26 16:58:36 -06001593 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001594 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001595 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001596 return false;
1597}
1598
1599bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1600{
1601 if (node->getExpression())
1602 node->getExpression()->traverse(this);
1603
1604 switch (node->getFlowOp()) {
1605 case glslang::EOpKill:
1606 builder.makeDiscard();
1607 break;
1608 case glslang::EOpBreak:
1609 if (breakForLoop.top())
1610 builder.createLoopExit();
1611 else
1612 builder.addSwitchBreak();
1613 break;
1614 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001615 builder.createLoopContinue();
1616 break;
1617 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001618 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001619 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001620 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001621 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001622
1623 builder.clearAccessChain();
1624 break;
1625
1626 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001627 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001628 break;
1629 }
1630
1631 return false;
1632}
1633
1634spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1635{
1636 // First, steer off constants, which are not SPIR-V variables, but
1637 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001638 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001639 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001640 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001641 }
1642
1643 // Now, handle actual variables
1644 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1645 spv::Id spvType = convertGlslangToSpvType(node->getType());
1646
1647 const char* name = node->getName().c_str();
1648 if (glslang::IsAnonymous(name))
1649 name = "";
1650
1651 return builder.createVariable(storageClass, spvType, name);
1652}
1653
1654// Return type Id of the sampled type.
1655spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1656{
1657 switch (sampler.type) {
1658 case glslang::EbtFloat: return builder.makeFloatType(32);
1659 case glslang::EbtInt: return builder.makeIntType(32);
1660 case glslang::EbtUint: return builder.makeUintType(32);
1661 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001662 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001663 return builder.makeFloatType(32);
1664 }
1665}
1666
John Kessenich3ac051e2015-12-20 11:29:16 -07001667// Convert from a glslang type to an SPV type, by calling into a
1668// recursive version of this function. This establishes the inherited
1669// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001670spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1671{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001672 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001673}
1674
1675// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001676// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001677spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001678{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001679 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001680
1681 switch (type.getBasicType()) {
1682 case glslang::EbtVoid:
1683 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001684 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001685 break;
1686 case glslang::EbtFloat:
1687 spvType = builder.makeFloatType(32);
1688 break;
1689 case glslang::EbtDouble:
1690 spvType = builder.makeFloatType(64);
1691 break;
1692 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001693 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1694 // a 32-bit int where non-0 means true.
1695 if (explicitLayout != glslang::ElpNone)
1696 spvType = builder.makeUintType(32);
1697 else
1698 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001699 break;
1700 case glslang::EbtInt:
1701 spvType = builder.makeIntType(32);
1702 break;
1703 case glslang::EbtUint:
1704 spvType = builder.makeUintType(32);
1705 break;
John Kessenich426394d2015-07-23 10:22:48 -06001706 case glslang::EbtAtomicUint:
1707 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1708 spvType = builder.makeUintType(32);
1709 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001710 case glslang::EbtSampler:
1711 {
1712 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001713 if (sampler.sampler) {
1714 // pure sampler
1715 spvType = builder.makeSamplerType();
1716 } else {
1717 // an image is present, make its type
1718 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1719 sampler.image ? 2 : 1, TranslateImageFormat(type));
1720 if (sampler.combined) {
1721 // already has both image and sampler, make the combined type
1722 spvType = builder.makeSampledImageType(spvType);
1723 }
John Kessenich55e7d112015-11-15 21:33:39 -07001724 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001725 }
John Kessenich140f3df2015-06-26 16:58:36 -06001726 break;
1727 case glslang::EbtStruct:
1728 case glslang::EbtBlock:
1729 {
1730 // If we've seen this struct type, return it
1731 const glslang::TTypeList* glslangStruct = type.getStruct();
1732 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001733
1734 // Try to share structs for different layouts, but not yet for other
1735 // kinds of qualification (primarily not yet including interpolant qualification).
1736 if (! HasNonLayoutQualifiers(qualifier))
1737 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1738 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001739 break;
1740
1741 // else, we haven't seen it...
1742
1743 // Create a vector of struct types for SPIR-V to consume
1744 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1745 if (type.getBasicType() == glslang::EbtBlock)
1746 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001747 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001748 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1749 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1750 if (glslangType.hiddenMember()) {
1751 ++memberDelta;
1752 if (type.getBasicType() == glslang::EbtBlock)
1753 memberRemapper[glslangStruct][i] = -1;
1754 } else {
1755 if (type.getBasicType() == glslang::EbtBlock)
1756 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001757 // modify just this child's view of the qualifier
1758 glslang::TQualifier subQualifier = glslangType.getQualifier();
1759 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001760
1761 // manually inherit location; it's more complex
1762 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1763 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1764 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001765 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001766
1767 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001768 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001769 }
1770 }
1771
1772 // Make the SPIR-V type
1773 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001774 if (! HasNonLayoutQualifiers(qualifier))
1775 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001776
1777 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001778 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001779 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001780 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1781 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1782 int member = i;
1783 if (type.getBasicType() == glslang::EbtBlock)
1784 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001785
John Kesseniche0b6cad2015-12-24 10:30:13 -07001786 // modify just this child's view of the qualifier
1787 glslang::TQualifier subQualifier = glslangType.getQualifier();
1788 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001789
John Kessenich140f3df2015-06-26 16:58:36 -06001790 // using -1 above to indicate a hidden member
1791 if (member >= 0) {
1792 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001793 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001794 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001795 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1796 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001797
Rex Xu1da878f2016-02-21 20:59:01 +08001798 if (qualifier.storage == glslang::EvqBuffer) {
1799 std::vector<spv::Decoration> memory;
1800 TranslateMemoryDecoration(subQualifier, memory);
1801 for (unsigned int i = 0; i < memory.size(); ++i)
1802 addMemberDecoration(spvType, member, memory[i]);
1803 }
1804
John Kessenich09677482016-02-19 12:21:50 -07001805 // compute location decoration; tricky based on whether inheritance is at play
1806 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1807 // probably move to the linker stage of the front end proper, and just have the
1808 // answer sitting already distributed throughout the individual member locations.
1809 int location = -1; // will only decorate if present or inherited
1810 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1811 location = subQualifier.layoutLocation;
1812 else if (qualifier.hasLocation()) // inheritance
1813 location = qualifier.layoutLocation + locationOffset;
1814 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001815 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001816 if (location >= 0)
1817 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1818
1819 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001820 if (glslangType.getQualifier().hasComponent())
1821 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1822 if (glslangType.getQualifier().hasXfbOffset())
1823 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001824 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001825 // figure out what to do with offset, which is accumulating
1826 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001827 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001828 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001829 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001830 offset = nextOffset;
1831 }
John Kessenich140f3df2015-06-26 16:58:36 -06001832
John Kessenichf85e8062015-12-19 13:57:10 -07001833 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001834 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001835
John Kessenich140f3df2015-06-26 16:58:36 -06001836 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001837 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1838 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001839 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001840 }
1841 }
1842
1843 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001844 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001845 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07001846 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07001847 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001848 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001849 }
John Kessenich140f3df2015-06-26 16:58:36 -06001850 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001851 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001852 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001853 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001854 if (type.getQualifier().hasXfbBuffer())
1855 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1856 }
1857 }
1858 break;
1859 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001860 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001861 break;
1862 }
1863
1864 if (type.isMatrix())
1865 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1866 else {
1867 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1868 if (type.getVectorSize() > 1)
1869 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1870 }
1871
1872 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001873 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1874
John Kessenichc9a80832015-09-12 12:17:44 -06001875 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001876 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001877 // We need to decorate array strides for types needing explicit layout, except blocks.
1878 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001879 // Use a dummy glslang type for querying internal strides of
1880 // arrays of arrays, but using just a one-dimensional array.
1881 glslang::TType simpleArrayType(type, 0); // deference type of the array
1882 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1883 simpleArrayType.getArraySizes().dereference();
1884
1885 // Will compute the higher-order strides here, rather than making a whole
1886 // pile of types and doing repetitive recursion on their contents.
1887 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1888 }
John Kessenichf8842e52016-01-04 19:22:56 -07001889
1890 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001891 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001892 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001893 if (stride > 0)
1894 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001895 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001896 }
1897 } else {
1898 // single-dimensional array, and don't yet have stride
1899
John Kessenichf8842e52016-01-04 19:22:56 -07001900 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001901 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1902 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001903 }
John Kessenich31ed4832015-09-09 17:51:38 -06001904
John Kessenichc9a80832015-09-12 12:17:44 -06001905 // Do the outer dimension, which might not be known for a runtime-sized array
1906 if (type.isRuntimeSizedArray()) {
1907 spvType = builder.makeRuntimeArray(spvType);
1908 } else {
1909 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001910 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001911 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001912 if (stride > 0)
1913 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001914 }
1915
1916 return spvType;
1917}
1918
John Kessenich6c292d32016-02-15 20:58:50 -07001919// Turn the expression forming the array size into an id.
1920// This is not quite trivial, because of specialization constants.
1921// Sometimes, a raw constant is turned into an Id, and sometimes
1922// a specialization constant expression is.
1923spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1924{
1925 // First, see if this is sized with a node, meaning a specialization constant:
1926 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1927 if (specNode != nullptr) {
1928 builder.clearAccessChain();
1929 specNode->traverse(this);
1930 return accessChainLoad(specNode->getAsTyped()->getType());
1931 }
1932
1933 // Otherwise, need a compile-time (front end) size, get it:
1934 int size = arraySizes.getDimSize(dim);
1935 assert(size > 0);
1936 return builder.makeUintConstant(size);
1937}
1938
John Kessenich103bef92016-02-08 21:38:15 -07001939// Wrap the builder's accessChainLoad to:
1940// - localize handling of RelaxedPrecision
1941// - use the SPIR-V inferred type instead of another conversion of the glslang type
1942// (avoids unnecessary work and possible type punning for structures)
1943// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001944spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1945{
John Kessenich103bef92016-02-08 21:38:15 -07001946 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1947 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1948
1949 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001950 if (type.getBasicType() == glslang::EbtBool) {
1951 if (builder.isScalarType(nominalTypeId)) {
1952 // Conversion for bool
1953 spv::Id boolType = builder.makeBoolType();
1954 if (nominalTypeId != boolType)
1955 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1956 } else if (builder.isVectorType(nominalTypeId)) {
1957 // Conversion for bvec
1958 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1959 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1960 if (nominalTypeId != bvecType)
1961 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1962 }
1963 }
John Kessenich103bef92016-02-08 21:38:15 -07001964
1965 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001966}
1967
Rex Xu27253232016-02-23 17:51:09 +08001968// Wrap the builder's accessChainStore to:
1969// - do conversion of concrete to abstract type
1970void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
1971{
1972 // Need to convert to abstract types when necessary
1973 if (type.getBasicType() == glslang::EbtBool) {
1974 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1975
1976 if (builder.isScalarType(nominalTypeId)) {
1977 // Conversion for bool
1978 spv::Id boolType = builder.makeBoolType();
1979 if (nominalTypeId != boolType) {
1980 spv::Id zero = builder.makeUintConstant(0);
1981 spv::Id one = builder.makeUintConstant(1);
1982 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1983 }
1984 } else if (builder.isVectorType(nominalTypeId)) {
1985 // Conversion for bvec
1986 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1987 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1988 if (nominalTypeId != bvecType) {
1989 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
1990 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
1991 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1992 }
1993 }
1994 }
1995
1996 builder.accessChainStore(rvalue);
1997}
1998
John Kessenichf85e8062015-12-19 13:57:10 -07001999// Decide whether or not this type should be
2000// decorated with offsets and strides, and if so
2001// whether std140 or std430 rules should be applied.
2002glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002003{
John Kessenichf85e8062015-12-19 13:57:10 -07002004 // has to be a block
2005 if (type.getBasicType() != glslang::EbtBlock)
2006 return glslang::ElpNone;
2007
2008 // has to be a uniform or buffer block
2009 if (type.getQualifier().storage != glslang::EvqUniform &&
2010 type.getQualifier().storage != glslang::EvqBuffer)
2011 return glslang::ElpNone;
2012
2013 // return the layout to use
2014 switch (type.getQualifier().layoutPacking) {
2015 case glslang::ElpStd140:
2016 case glslang::ElpStd430:
2017 return type.getQualifier().layoutPacking;
2018 default:
2019 return glslang::ElpNone;
2020 }
John Kessenich31ed4832015-09-09 17:51:38 -06002021}
2022
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002023// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002024int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002025{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002026 int size;
John Kessenich49987892015-12-29 17:11:44 -07002027 int stride;
2028 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002029
2030 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002031}
2032
John Kessenich49987892015-12-29 17:11:44 -07002033// 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 -07002034// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002035int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002036{
John Kessenich49987892015-12-29 17:11:44 -07002037 glslang::TType elementType;
2038 elementType.shallowCopy(matrixType);
2039 elementType.clearArraySizes();
2040
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002041 int size;
John Kessenich49987892015-12-29 17:11:44 -07002042 int stride;
2043 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2044
2045 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002046}
2047
John Kessenich5e4b1242015-08-06 22:53:06 -06002048// Given a member type of a struct, realign the current offset for it, and compute
2049// the next (not yet aligned) offset for the next member, which will get aligned
2050// on the next call.
2051// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2052// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2053// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002054void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002055 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002056{
2057 // this will get a positive value when deemed necessary
2058 nextOffset = -1;
2059
John Kessenich5e4b1242015-08-06 22:53:06 -06002060 // override anything in currentOffset with user-set offset
2061 if (memberType.getQualifier().hasOffset())
2062 currentOffset = memberType.getQualifier().layoutOffset;
2063
2064 // It could be that current linker usage in glslang updated all the layoutOffset,
2065 // in which case the following code does not matter. But, that's not quite right
2066 // once cross-compilation unit GLSL validation is done, as the original user
2067 // settings are needed in layoutOffset, and then the following will come into play.
2068
John Kessenichf85e8062015-12-19 13:57:10 -07002069 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002070 if (! memberType.getQualifier().hasOffset())
2071 currentOffset = -1;
2072
2073 return;
2074 }
2075
John Kessenichf85e8062015-12-19 13:57:10 -07002076 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002077 if (currentOffset < 0)
2078 currentOffset = 0;
2079
2080 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2081 // but possibly not yet correctly aligned.
2082
2083 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002084 int dummyStride;
2085 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002086 glslang::RoundToPow2(currentOffset, memberAlignment);
2087 nextOffset = currentOffset + memberSize;
2088}
2089
John Kessenich140f3df2015-06-26 16:58:36 -06002090bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2091{
John Kessenich4d65ee32016-03-12 18:17:47 -07002092 // have to ignore mangling and just look at the base name
2093 int firstOpen = node->getName().find('(');
2094 return node->getName().compare(0, firstOpen, glslangIntermediate->getEntryPoint()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002095}
2096
2097// Make all the functions, skeletally, without actually visiting their bodies.
2098void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2099{
2100 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2101 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2102 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2103 continue;
2104
2105 // We're on a user function. Set up the basic interface for the function now,
2106 // so that it's available to call.
2107 // Translating the body will happen later.
2108 //
2109 // Typically (except for a "const in" parameter), an address will be passed to the
2110 // function. What it is an address of varies:
2111 //
2112 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2113 // so that write needs to be to a copy, hence the address of a copy works.
2114 //
2115 // - "const in" parameters can just be the r-value, as no writes need occur.
2116 //
2117 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2118 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2119
2120 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002121 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002122 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2123
2124 for (int p = 0; p < (int)parameters.size(); ++p) {
2125 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2126 spv::Id typeId = convertGlslangToSpvType(paramType);
2127 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2128 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2129 else
2130 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002131 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002132 paramTypes.push_back(typeId);
2133 }
2134
2135 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002136 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2137 convertGlslangToSpvType(glslFunction->getType()),
2138 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002139
2140 // Track function to emit/call later
2141 functionMap[glslFunction->getName().c_str()] = function;
2142
2143 // Set the parameter id's
2144 for (int p = 0; p < (int)parameters.size(); ++p) {
2145 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2146 // give a name too
2147 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2148 }
2149 }
2150}
2151
2152// Process all the initializers, while skipping the functions and link objects
2153void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2154{
2155 builder.setBuildPoint(shaderEntry->getLastBlock());
2156 for (int i = 0; i < (int)initializers.size(); ++i) {
2157 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2158 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2159
2160 // We're on a top-level node that's not a function. Treat as an initializer, whose
2161 // code goes into the beginning of main.
2162 initializer->traverse(this);
2163 }
2164 }
2165}
2166
2167// Process all the functions, while skipping initializers.
2168void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2169{
2170 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2171 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2172 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2173 node->traverse(this);
2174 }
2175}
2176
2177void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2178{
2179 // SPIR-V functions should already be in the functionMap from the prepass
2180 // that called makeFunctions().
2181 spv::Function* function = functionMap[node->getName().c_str()];
2182 spv::Block* functionBlock = function->getEntryBlock();
2183 builder.setBuildPoint(functionBlock);
2184}
2185
Rex Xu04db3f52015-09-16 11:44:02 +08002186void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002187{
Rex Xufc618912015-09-09 16:42:49 +08002188 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002189
2190 glslang::TSampler sampler = {};
2191 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002192 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002193 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2194 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2195 }
2196
John Kessenich140f3df2015-06-26 16:58:36 -06002197 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2198 builder.clearAccessChain();
2199 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002200
2201 // Special case l-value operands
2202 bool lvalue = false;
2203 switch (node.getOp()) {
2204 case glslang::EOpImageAtomicAdd:
2205 case glslang::EOpImageAtomicMin:
2206 case glslang::EOpImageAtomicMax:
2207 case glslang::EOpImageAtomicAnd:
2208 case glslang::EOpImageAtomicOr:
2209 case glslang::EOpImageAtomicXor:
2210 case glslang::EOpImageAtomicExchange:
2211 case glslang::EOpImageAtomicCompSwap:
2212 if (i == 0)
2213 lvalue = true;
2214 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002215 case glslang::EOpSparseImageLoad:
2216 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2217 lvalue = true;
2218 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002219 case glslang::EOpSparseTexture:
2220 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2221 lvalue = true;
2222 break;
2223 case glslang::EOpSparseTextureClamp:
2224 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2225 lvalue = true;
2226 break;
2227 case glslang::EOpSparseTextureLod:
2228 case glslang::EOpSparseTextureOffset:
2229 if (i == 3)
2230 lvalue = true;
2231 break;
2232 case glslang::EOpSparseTextureFetch:
2233 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2234 lvalue = true;
2235 break;
2236 case glslang::EOpSparseTextureFetchOffset:
2237 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2238 lvalue = true;
2239 break;
2240 case glslang::EOpSparseTextureLodOffset:
2241 case glslang::EOpSparseTextureGrad:
2242 case glslang::EOpSparseTextureOffsetClamp:
2243 if (i == 4)
2244 lvalue = true;
2245 break;
2246 case glslang::EOpSparseTextureGradOffset:
2247 case glslang::EOpSparseTextureGradClamp:
2248 if (i == 5)
2249 lvalue = true;
2250 break;
2251 case glslang::EOpSparseTextureGradOffsetClamp:
2252 if (i == 6)
2253 lvalue = true;
2254 break;
2255 case glslang::EOpSparseTextureGather:
2256 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2257 lvalue = true;
2258 break;
2259 case glslang::EOpSparseTextureGatherOffset:
2260 case glslang::EOpSparseTextureGatherOffsets:
2261 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2262 lvalue = true;
2263 break;
Rex Xufc618912015-09-09 16:42:49 +08002264 default:
2265 break;
2266 }
2267
Rex Xu6b86d492015-09-16 17:48:22 +08002268 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002269 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002270 else
John Kessenich32cfd492016-02-02 12:37:46 -07002271 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002272 }
2273}
2274
John Kessenichfc51d282015-08-19 13:34:18 -06002275void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002276{
John Kessenichfc51d282015-08-19 13:34:18 -06002277 builder.clearAccessChain();
2278 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002279 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002280}
John Kessenich140f3df2015-06-26 16:58:36 -06002281
John Kessenichfc51d282015-08-19 13:34:18 -06002282spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2283{
Rex Xufc618912015-09-09 16:42:49 +08002284 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002285 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002286 }
2287
John Kessenichfc51d282015-08-19 13:34:18 -06002288 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002289 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2290 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2291 std::vector<spv::Id> arguments;
2292 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002293 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002294 else
2295 translateArguments(*node->getAsUnaryNode(), arguments);
2296 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2297
2298 spv::Builder::TextureParameters params = { };
2299 params.sampler = arguments[0];
2300
Rex Xu04db3f52015-09-16 11:44:02 +08002301 glslang::TCrackedTextureOp cracked;
2302 node->crackTexture(sampler, cracked);
2303
John Kessenichfc51d282015-08-19 13:34:18 -06002304 // Check for queries
2305 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002306 // a sampled image needs to have the image extracted first
2307 if (builder.isSampledImage(params.sampler))
2308 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002309 switch (node->getOp()) {
2310 case glslang::EOpImageQuerySize:
2311 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002312 if (arguments.size() > 1) {
2313 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002314 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002315 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002316 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002317 case glslang::EOpImageQuerySamples:
2318 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002319 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002320 case glslang::EOpTextureQueryLod:
2321 params.coords = arguments[1];
2322 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2323 case glslang::EOpTextureQueryLevels:
2324 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002325 case glslang::EOpSparseTexelsResident:
2326 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002327 default:
2328 assert(0);
2329 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002330 }
John Kessenich140f3df2015-06-26 16:58:36 -06002331 }
2332
Rex Xufc618912015-09-09 16:42:49 +08002333 // Check for image functions other than queries
2334 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002335 std::vector<spv::Id> operands;
2336 auto opIt = arguments.begin();
2337 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002338
2339 // Handle subpass operations
2340 // TODO: GLSL should change to have the "MS" only on the type rather than the
2341 // built-in function.
2342 if (cracked.subpass) {
2343 // add on the (0,0) coordinate
2344 spv::Id zero = builder.makeIntConstant(0);
2345 std::vector<spv::Id> comps;
2346 comps.push_back(zero);
2347 comps.push_back(zero);
2348 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2349 if (sampler.ms) {
2350 operands.push_back(spv::ImageOperandsSampleMask);
2351 operands.push_back(*(opIt++));
2352 }
2353 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2354 }
2355
John Kessenich56bab042015-09-16 10:54:31 -06002356 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002357 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002358 if (sampler.ms) {
2359 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002360 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002361 }
John Kessenich5d0fa972016-02-15 11:57:00 -07002362 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2363 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
Rex Xu5eafa472016-02-19 22:24:03 +08002364 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich56bab042015-09-16 10:54:31 -06002365 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002366 if (sampler.ms) {
2367 operands.push_back(*(opIt + 1));
2368 operands.push_back(spv::ImageOperandsSampleMask);
2369 operands.push_back(*opIt);
2370 } else
2371 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002372 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002373 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2374 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002375 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08002376 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
2377 builder.addCapability(spv::CapabilitySparseResidency);
2378 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2379 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
2380
2381 if (sampler.ms) {
2382 operands.push_back(spv::ImageOperandsSampleMask);
2383 operands.push_back(*opIt++);
2384 }
2385
2386 // Create the return type that was a special structure
2387 spv::Id texelOut = *opIt;
2388 spv::Id typeId0 = convertGlslangToSpvType(node->getType());
2389 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
2390 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
2391
2392 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
2393
2394 // Decode the return type
2395 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
2396 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07002397 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002398 // Process image atomic operations
2399
2400 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2401 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002402 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002403
Rex Xufc618912015-09-09 16:42:49 +08002404 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002405 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002406
2407 std::vector<spv::Id> operands;
2408 operands.push_back(pointer);
2409 for (; opIt != arguments.end(); ++opIt)
2410 operands.push_back(*opIt);
2411
Rex Xu04db3f52015-09-16 11:44:02 +08002412 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002413 }
2414 }
2415
2416 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002417 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002418 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2419
John Kessenichfc51d282015-08-19 13:34:18 -06002420 // check for bias argument
2421 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002422 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002423 int nonBiasArgCount = 2;
2424 if (cracked.offset)
2425 ++nonBiasArgCount;
2426 if (cracked.grad)
2427 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002428 if (cracked.lodClamp)
2429 ++nonBiasArgCount;
2430 if (sparse)
2431 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002432
2433 if ((int)arguments.size() > nonBiasArgCount)
2434 bias = true;
2435 }
2436
John Kessenichfc51d282015-08-19 13:34:18 -06002437 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002438
John Kessenichfc51d282015-08-19 13:34:18 -06002439 params.coords = arguments[1];
2440 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002441 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002442
2443 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002444 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002445 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002446 ++extraArgs;
2447 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002448 params.Dref = arguments[2];
2449 ++extraArgs;
2450 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002451 std::vector<spv::Id> indexes;
2452 int comp;
2453 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002454 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002455 else
2456 comp = builder.getNumComponents(params.coords) - 1;
2457 indexes.push_back(comp);
2458 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2459 }
2460 if (cracked.lod) {
2461 params.lod = arguments[2];
2462 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002463 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2464 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2465 noImplicitLod = true;
2466 }
2467 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002468 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002469 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002470 }
2471 if (cracked.grad) {
2472 params.gradX = arguments[2 + extraArgs];
2473 params.gradY = arguments[3 + extraArgs];
2474 extraArgs += 2;
2475 }
John Kessenich55e7d112015-11-15 21:33:39 -07002476 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002477 params.offset = arguments[2 + extraArgs];
2478 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002479 } else if (cracked.offsets) {
2480 params.offsets = arguments[2 + extraArgs];
2481 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002482 }
Rex Xu48edadf2015-12-31 16:11:41 +08002483 if (cracked.lodClamp) {
2484 params.lodClamp = arguments[2 + extraArgs];
2485 ++extraArgs;
2486 }
2487 if (sparse) {
2488 params.texelOut = arguments[2 + extraArgs];
2489 ++extraArgs;
2490 }
John Kessenichfc51d282015-08-19 13:34:18 -06002491 if (bias) {
2492 params.bias = arguments[2 + extraArgs];
2493 ++extraArgs;
2494 }
John Kessenich55e7d112015-11-15 21:33:39 -07002495 if (cracked.gather && ! sampler.shadow) {
2496 // default component is 0, if missing, otherwise an argument
2497 if (2 + extraArgs < (int)arguments.size()) {
2498 params.comp = arguments[2 + extraArgs];
2499 ++extraArgs;
2500 } else {
2501 params.comp = builder.makeIntConstant(0);
2502 }
2503 }
John Kessenichfc51d282015-08-19 13:34:18 -06002504
John Kessenich019f08f2016-02-15 15:40:42 -07002505 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002506}
2507
2508spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2509{
2510 // Grab the function's pointer from the previously created function
2511 spv::Function* function = functionMap[node->getName().c_str()];
2512 if (! function)
2513 return 0;
2514
2515 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2516 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2517
2518 // See comments in makeFunctions() for details about the semantics for parameter passing.
2519 //
2520 // These imply we need a four step process:
2521 // 1. Evaluate the arguments
2522 // 2. Allocate and make copies of in, out, and inout arguments
2523 // 3. Make the call
2524 // 4. Copy back the results
2525
2526 // 1. Evaluate the arguments
2527 std::vector<spv::Builder::AccessChain> lValues;
2528 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002529 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002530 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2531 // build l-value
2532 builder.clearAccessChain();
2533 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002534 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002535 // keep outputs as l-values, evaluate input-only as r-values
2536 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2537 // save l-value
2538 lValues.push_back(builder.getAccessChain());
2539 } else {
2540 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002541 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002542 }
2543 }
2544
2545 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2546 // copy the original into that space.
2547 //
2548 // Also, build up the list of actual arguments to pass in for the call
2549 int lValueCount = 0;
2550 int rValueCount = 0;
2551 std::vector<spv::Id> spvArgs;
2552 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2553 spv::Id arg;
2554 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2555 // need space to hold the copy
2556 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2557 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2558 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2559 // need to copy the input into output space
2560 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002561 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002562 builder.createStore(copy, arg);
2563 }
2564 ++lValueCount;
2565 } else {
2566 arg = rValues[rValueCount];
2567 ++rValueCount;
2568 }
2569 spvArgs.push_back(arg);
2570 }
2571
2572 // 3. Make the call.
2573 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002574 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002575
2576 // 4. Copy back out an "out" arguments.
2577 lValueCount = 0;
2578 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2579 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2580 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2581 spv::Id copy = builder.createLoad(spvArgs[a]);
2582 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002583 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002584 }
2585 ++lValueCount;
2586 }
2587 }
2588
2589 return result;
2590}
2591
2592// Translate AST operation to SPV operation, already having SPV-based operands/types.
2593spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2594 spv::Id typeId, spv::Id left, spv::Id right,
2595 glslang::TBasicType typeProxy, bool reduceComparison)
2596{
2597 bool isUnsigned = typeProxy == glslang::EbtUint;
2598 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2599
2600 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002601 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002602 bool comparison = false;
2603
2604 switch (op) {
2605 case glslang::EOpAdd:
2606 case glslang::EOpAddAssign:
2607 if (isFloat)
2608 binOp = spv::OpFAdd;
2609 else
2610 binOp = spv::OpIAdd;
2611 break;
2612 case glslang::EOpSub:
2613 case glslang::EOpSubAssign:
2614 if (isFloat)
2615 binOp = spv::OpFSub;
2616 else
2617 binOp = spv::OpISub;
2618 break;
2619 case glslang::EOpMul:
2620 case glslang::EOpMulAssign:
2621 if (isFloat)
2622 binOp = spv::OpFMul;
2623 else
2624 binOp = spv::OpIMul;
2625 break;
2626 case glslang::EOpVectorTimesScalar:
2627 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002628 if (isFloat) {
2629 if (builder.isVector(right))
2630 std::swap(left, right);
2631 assert(builder.isScalar(right));
2632 needMatchingVectors = false;
2633 binOp = spv::OpVectorTimesScalar;
2634 } else
2635 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002636 break;
2637 case glslang::EOpVectorTimesMatrix:
2638 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002639 binOp = spv::OpVectorTimesMatrix;
2640 break;
2641 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002642 binOp = spv::OpMatrixTimesVector;
2643 break;
2644 case glslang::EOpMatrixTimesScalar:
2645 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002646 binOp = spv::OpMatrixTimesScalar;
2647 break;
2648 case glslang::EOpMatrixTimesMatrix:
2649 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002650 binOp = spv::OpMatrixTimesMatrix;
2651 break;
2652 case glslang::EOpOuterProduct:
2653 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002654 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002655 break;
2656
2657 case glslang::EOpDiv:
2658 case glslang::EOpDivAssign:
2659 if (isFloat)
2660 binOp = spv::OpFDiv;
2661 else if (isUnsigned)
2662 binOp = spv::OpUDiv;
2663 else
2664 binOp = spv::OpSDiv;
2665 break;
2666 case glslang::EOpMod:
2667 case glslang::EOpModAssign:
2668 if (isFloat)
2669 binOp = spv::OpFMod;
2670 else if (isUnsigned)
2671 binOp = spv::OpUMod;
2672 else
2673 binOp = spv::OpSMod;
2674 break;
2675 case glslang::EOpRightShift:
2676 case glslang::EOpRightShiftAssign:
2677 if (isUnsigned)
2678 binOp = spv::OpShiftRightLogical;
2679 else
2680 binOp = spv::OpShiftRightArithmetic;
2681 break;
2682 case glslang::EOpLeftShift:
2683 case glslang::EOpLeftShiftAssign:
2684 binOp = spv::OpShiftLeftLogical;
2685 break;
2686 case glslang::EOpAnd:
2687 case glslang::EOpAndAssign:
2688 binOp = spv::OpBitwiseAnd;
2689 break;
2690 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002691 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002692 binOp = spv::OpLogicalAnd;
2693 break;
2694 case glslang::EOpInclusiveOr:
2695 case glslang::EOpInclusiveOrAssign:
2696 binOp = spv::OpBitwiseOr;
2697 break;
2698 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002699 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002700 binOp = spv::OpLogicalOr;
2701 break;
2702 case glslang::EOpExclusiveOr:
2703 case glslang::EOpExclusiveOrAssign:
2704 binOp = spv::OpBitwiseXor;
2705 break;
2706 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002707 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002708 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002709 break;
2710
2711 case glslang::EOpLessThan:
2712 case glslang::EOpGreaterThan:
2713 case glslang::EOpLessThanEqual:
2714 case glslang::EOpGreaterThanEqual:
2715 case glslang::EOpEqual:
2716 case glslang::EOpNotEqual:
2717 case glslang::EOpVectorEqual:
2718 case glslang::EOpVectorNotEqual:
2719 comparison = true;
2720 break;
2721 default:
2722 break;
2723 }
2724
John Kessenich7c1aa102015-10-15 13:29:11 -06002725 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002726 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002727 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002728 if (builder.isMatrix(left) || builder.isMatrix(right))
2729 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002730
2731 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002732 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002733 builder.promoteScalar(precision, left, right);
2734
John Kessenich32cfd492016-02-02 12:37:46 -07002735 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002736 }
2737
2738 if (! comparison)
2739 return 0;
2740
John Kessenich7c1aa102015-10-15 13:29:11 -06002741 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002742
2743 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2744 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2745
John Kessenich22118352015-12-21 20:54:09 -07002746 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002747 }
2748
2749 switch (op) {
2750 case glslang::EOpLessThan:
2751 if (isFloat)
2752 binOp = spv::OpFOrdLessThan;
2753 else if (isUnsigned)
2754 binOp = spv::OpULessThan;
2755 else
2756 binOp = spv::OpSLessThan;
2757 break;
2758 case glslang::EOpGreaterThan:
2759 if (isFloat)
2760 binOp = spv::OpFOrdGreaterThan;
2761 else if (isUnsigned)
2762 binOp = spv::OpUGreaterThan;
2763 else
2764 binOp = spv::OpSGreaterThan;
2765 break;
2766 case glslang::EOpLessThanEqual:
2767 if (isFloat)
2768 binOp = spv::OpFOrdLessThanEqual;
2769 else if (isUnsigned)
2770 binOp = spv::OpULessThanEqual;
2771 else
2772 binOp = spv::OpSLessThanEqual;
2773 break;
2774 case glslang::EOpGreaterThanEqual:
2775 if (isFloat)
2776 binOp = spv::OpFOrdGreaterThanEqual;
2777 else if (isUnsigned)
2778 binOp = spv::OpUGreaterThanEqual;
2779 else
2780 binOp = spv::OpSGreaterThanEqual;
2781 break;
2782 case glslang::EOpEqual:
2783 case glslang::EOpVectorEqual:
2784 if (isFloat)
2785 binOp = spv::OpFOrdEqual;
2786 else
2787 binOp = spv::OpIEqual;
2788 break;
2789 case glslang::EOpNotEqual:
2790 case glslang::EOpVectorNotEqual:
2791 if (isFloat)
2792 binOp = spv::OpFOrdNotEqual;
2793 else
2794 binOp = spv::OpINotEqual;
2795 break;
2796 default:
2797 break;
2798 }
2799
John Kessenich32cfd492016-02-02 12:37:46 -07002800 if (binOp != spv::OpNop)
2801 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002802
2803 return 0;
2804}
2805
John Kessenich04bb8a02015-12-12 12:28:14 -07002806//
2807// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2808// These can be any of:
2809//
2810// matrix * scalar
2811// scalar * matrix
2812// matrix * matrix linear algebraic
2813// matrix * vector
2814// vector * matrix
2815// matrix * matrix componentwise
2816// matrix op matrix op in {+, -, /}
2817// matrix op scalar op in {+, -, /}
2818// scalar op matrix op in {+, -, /}
2819//
2820spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2821{
2822 bool firstClass = true;
2823
2824 // First, handle first-class matrix operations (* and matrix/scalar)
2825 switch (op) {
2826 case spv::OpFDiv:
2827 if (builder.isMatrix(left) && builder.isScalar(right)) {
2828 // turn matrix / scalar into a multiply...
2829 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2830 op = spv::OpMatrixTimesScalar;
2831 } else
2832 firstClass = false;
2833 break;
2834 case spv::OpMatrixTimesScalar:
2835 if (builder.isMatrix(right))
2836 std::swap(left, right);
2837 assert(builder.isScalar(right));
2838 break;
2839 case spv::OpVectorTimesMatrix:
2840 assert(builder.isVector(left));
2841 assert(builder.isMatrix(right));
2842 break;
2843 case spv::OpMatrixTimesVector:
2844 assert(builder.isMatrix(left));
2845 assert(builder.isVector(right));
2846 break;
2847 case spv::OpMatrixTimesMatrix:
2848 assert(builder.isMatrix(left));
2849 assert(builder.isMatrix(right));
2850 break;
2851 default:
2852 firstClass = false;
2853 break;
2854 }
2855
John Kessenich32cfd492016-02-02 12:37:46 -07002856 if (firstClass)
2857 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002858
2859 // Handle component-wise +, -, *, and / for all combinations of type.
2860 // The result type of all of them is the same type as the (a) matrix operand.
2861 // The algorithm is to:
2862 // - break the matrix(es) into vectors
2863 // - smear any scalar to a vector
2864 // - do vector operations
2865 // - make a matrix out the vector results
2866 switch (op) {
2867 case spv::OpFAdd:
2868 case spv::OpFSub:
2869 case spv::OpFDiv:
2870 case spv::OpFMul:
2871 {
2872 // one time set up...
2873 bool leftMat = builder.isMatrix(left);
2874 bool rightMat = builder.isMatrix(right);
2875 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2876 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2877 spv::Id scalarType = builder.getScalarTypeId(typeId);
2878 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2879 std::vector<spv::Id> results;
2880 spv::Id smearVec = spv::NoResult;
2881 if (builder.isScalar(left))
2882 smearVec = builder.smearScalar(precision, left, vecType);
2883 else if (builder.isScalar(right))
2884 smearVec = builder.smearScalar(precision, right, vecType);
2885
2886 // do each vector op
2887 for (unsigned int c = 0; c < numCols; ++c) {
2888 std::vector<unsigned int> indexes;
2889 indexes.push_back(c);
2890 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2891 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2892 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2893 builder.setPrecision(results.back(), precision);
2894 }
2895
2896 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002897 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002898 }
2899 default:
2900 assert(0);
2901 return spv::NoResult;
2902 }
2903}
2904
Rex Xu04db3f52015-09-16 11:44:02 +08002905spv::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 -06002906{
2907 spv::Op unaryOp = spv::OpNop;
2908 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002909 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002910 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002911
2912 switch (op) {
2913 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002914 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002915 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002916 if (builder.isMatrixType(typeId))
2917 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2918 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002919 unaryOp = spv::OpSNegate;
2920 break;
2921
2922 case glslang::EOpLogicalNot:
2923 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002924 unaryOp = spv::OpLogicalNot;
2925 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002926 case glslang::EOpBitwiseNot:
2927 unaryOp = spv::OpNot;
2928 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002929
John Kessenich140f3df2015-06-26 16:58:36 -06002930 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002931 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002932 break;
2933 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002934 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002935 break;
2936 case glslang::EOpTranspose:
2937 unaryOp = spv::OpTranspose;
2938 break;
2939
2940 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002941 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002942 break;
2943 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002944 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002945 break;
2946 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002947 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002948 break;
2949 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002950 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002951 break;
2952 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002953 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002954 break;
2955 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002956 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002957 break;
2958 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002959 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002960 break;
2961 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002962 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002963 break;
2964
2965 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002966 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002967 break;
2968 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002969 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002970 break;
2971 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002972 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002973 break;
2974 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002975 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002976 break;
2977 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002978 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002979 break;
2980 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002981 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002982 break;
2983
2984 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002985 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002986 break;
2987 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002988 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002989 break;
2990
2991 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002992 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002993 break;
2994 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002995 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002996 break;
2997 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002998 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002999 break;
3000 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003001 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003002 break;
3003 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003004 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003005 break;
3006 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003007 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003008 break;
3009
3010 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003011 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003012 break;
3013 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003014 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003015 break;
3016 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003017 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003018 break;
3019 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003020 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003021 break;
3022 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003023 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003024 break;
3025 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003026 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003027 break;
3028
3029 case glslang::EOpIsNan:
3030 unaryOp = spv::OpIsNan;
3031 break;
3032 case glslang::EOpIsInf:
3033 unaryOp = spv::OpIsInf;
3034 break;
3035
Rex Xucbc426e2015-12-15 16:03:10 +08003036 case glslang::EOpFloatBitsToInt:
3037 case glslang::EOpFloatBitsToUint:
3038 case glslang::EOpIntBitsToFloat:
3039 case glslang::EOpUintBitsToFloat:
3040 unaryOp = spv::OpBitcast;
3041 break;
3042
John Kessenich140f3df2015-06-26 16:58:36 -06003043 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003044 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003045 break;
3046 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003047 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003048 break;
3049 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003050 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 break;
3052 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003053 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003054 break;
3055 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003056 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003057 break;
3058 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003059 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003060 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003061 case glslang::EOpPackSnorm4x8:
3062 libCall = spv::GLSLstd450PackSnorm4x8;
3063 break;
3064 case glslang::EOpUnpackSnorm4x8:
3065 libCall = spv::GLSLstd450UnpackSnorm4x8;
3066 break;
3067 case glslang::EOpPackUnorm4x8:
3068 libCall = spv::GLSLstd450PackUnorm4x8;
3069 break;
3070 case glslang::EOpUnpackUnorm4x8:
3071 libCall = spv::GLSLstd450UnpackUnorm4x8;
3072 break;
3073 case glslang::EOpPackDouble2x32:
3074 libCall = spv::GLSLstd450PackDouble2x32;
3075 break;
3076 case glslang::EOpUnpackDouble2x32:
3077 libCall = spv::GLSLstd450UnpackDouble2x32;
3078 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003079
3080 case glslang::EOpDPdx:
3081 unaryOp = spv::OpDPdx;
3082 break;
3083 case glslang::EOpDPdy:
3084 unaryOp = spv::OpDPdy;
3085 break;
3086 case glslang::EOpFwidth:
3087 unaryOp = spv::OpFwidth;
3088 break;
3089 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003090 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003091 unaryOp = spv::OpDPdxFine;
3092 break;
3093 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003094 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003095 unaryOp = spv::OpDPdyFine;
3096 break;
3097 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003098 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003099 unaryOp = spv::OpFwidthFine;
3100 break;
3101 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003102 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003103 unaryOp = spv::OpDPdxCoarse;
3104 break;
3105 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003106 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003107 unaryOp = spv::OpDPdyCoarse;
3108 break;
3109 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003110 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003111 unaryOp = spv::OpFwidthCoarse;
3112 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003113 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003114 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003115 libCall = spv::GLSLstd450InterpolateAtCentroid;
3116 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003117 case glslang::EOpAny:
3118 unaryOp = spv::OpAny;
3119 break;
3120 case glslang::EOpAll:
3121 unaryOp = spv::OpAll;
3122 break;
3123
3124 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003125 if (isFloat)
3126 libCall = spv::GLSLstd450FAbs;
3127 else
3128 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003129 break;
3130 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003131 if (isFloat)
3132 libCall = spv::GLSLstd450FSign;
3133 else
3134 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003135 break;
3136
John Kessenichfc51d282015-08-19 13:34:18 -06003137 case glslang::EOpAtomicCounterIncrement:
3138 case glslang::EOpAtomicCounterDecrement:
3139 case glslang::EOpAtomicCounter:
3140 {
3141 // Handle all of the atomics in one place, in createAtomicOperation()
3142 std::vector<spv::Id> operands;
3143 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003144 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003145 }
3146
John Kessenichfc51d282015-08-19 13:34:18 -06003147 case glslang::EOpBitFieldReverse:
3148 unaryOp = spv::OpBitReverse;
3149 break;
3150 case glslang::EOpBitCount:
3151 unaryOp = spv::OpBitCount;
3152 break;
3153 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003154 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003155 break;
3156 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003157 if (isUnsigned)
3158 libCall = spv::GLSLstd450FindUMsb;
3159 else
3160 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003161 break;
3162
John Kessenich140f3df2015-06-26 16:58:36 -06003163 default:
3164 return 0;
3165 }
3166
3167 spv::Id id;
3168 if (libCall >= 0) {
3169 std::vector<spv::Id> args;
3170 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003171 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003172 } else
3173 id = builder.createUnaryOp(unaryOp, typeId, operand);
3174
John Kessenich32cfd492016-02-02 12:37:46 -07003175 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003176}
3177
John Kessenich7a53f762016-01-20 11:19:27 -07003178// Create a unary operation on a matrix
3179spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3180{
3181 // Handle unary operations vector by vector.
3182 // The result type is the same type as the original type.
3183 // The algorithm is to:
3184 // - break the matrix into vectors
3185 // - apply the operation to each vector
3186 // - make a matrix out the vector results
3187
3188 // get the types sorted out
3189 int numCols = builder.getNumColumns(operand);
3190 int numRows = builder.getNumRows(operand);
3191 spv::Id scalarType = builder.getScalarTypeId(typeId);
3192 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3193 std::vector<spv::Id> results;
3194
3195 // do each vector op
3196 for (int c = 0; c < numCols; ++c) {
3197 std::vector<unsigned int> indexes;
3198 indexes.push_back(c);
3199 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3200 results.push_back(builder.createUnaryOp(op, vecType, vec));
3201 builder.setPrecision(results.back(), precision);
3202 }
3203
3204 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003205 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003206}
3207
John Kessenich140f3df2015-06-26 16:58:36 -06003208spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3209{
3210 spv::Op convOp = spv::OpNop;
3211 spv::Id zero = 0;
3212 spv::Id one = 0;
3213
3214 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3215
3216 switch (op) {
3217 case glslang::EOpConvIntToBool:
3218 case glslang::EOpConvUintToBool:
3219 zero = builder.makeUintConstant(0);
3220 zero = makeSmearedConstant(zero, vectorSize);
3221 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3222
3223 case glslang::EOpConvFloatToBool:
3224 zero = builder.makeFloatConstant(0.0F);
3225 zero = makeSmearedConstant(zero, vectorSize);
3226 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3227
3228 case glslang::EOpConvDoubleToBool:
3229 zero = builder.makeDoubleConstant(0.0);
3230 zero = makeSmearedConstant(zero, vectorSize);
3231 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3232
3233 case glslang::EOpConvBoolToFloat:
3234 convOp = spv::OpSelect;
3235 zero = builder.makeFloatConstant(0.0);
3236 one = builder.makeFloatConstant(1.0);
3237 break;
3238 case glslang::EOpConvBoolToDouble:
3239 convOp = spv::OpSelect;
3240 zero = builder.makeDoubleConstant(0.0);
3241 one = builder.makeDoubleConstant(1.0);
3242 break;
3243 case glslang::EOpConvBoolToInt:
3244 zero = builder.makeIntConstant(0);
3245 one = builder.makeIntConstant(1);
3246 convOp = spv::OpSelect;
3247 break;
3248 case glslang::EOpConvBoolToUint:
3249 zero = builder.makeUintConstant(0);
3250 one = builder.makeUintConstant(1);
3251 convOp = spv::OpSelect;
3252 break;
3253
3254 case glslang::EOpConvIntToFloat:
3255 case glslang::EOpConvIntToDouble:
3256 convOp = spv::OpConvertSToF;
3257 break;
3258
3259 case glslang::EOpConvUintToFloat:
3260 case glslang::EOpConvUintToDouble:
3261 convOp = spv::OpConvertUToF;
3262 break;
3263
3264 case glslang::EOpConvDoubleToFloat:
3265 case glslang::EOpConvFloatToDouble:
3266 convOp = spv::OpFConvert;
3267 break;
3268
3269 case glslang::EOpConvFloatToInt:
3270 case glslang::EOpConvDoubleToInt:
3271 convOp = spv::OpConvertFToS;
3272 break;
3273
3274 case glslang::EOpConvUintToInt:
3275 case glslang::EOpConvIntToUint:
3276 convOp = spv::OpBitcast;
3277 break;
3278
3279 case glslang::EOpConvFloatToUint:
3280 case glslang::EOpConvDoubleToUint:
3281 convOp = spv::OpConvertFToU;
3282 break;
3283 default:
3284 break;
3285 }
3286
3287 spv::Id result = 0;
3288 if (convOp == spv::OpNop)
3289 return result;
3290
3291 if (convOp == spv::OpSelect) {
3292 zero = makeSmearedConstant(zero, vectorSize);
3293 one = makeSmearedConstant(one, vectorSize);
3294 result = builder.createTriOp(convOp, destType, operand, one, zero);
3295 } else
3296 result = builder.createUnaryOp(convOp, destType, operand);
3297
John Kessenich32cfd492016-02-02 12:37:46 -07003298 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003299}
3300
3301spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3302{
3303 if (vectorSize == 0)
3304 return constant;
3305
3306 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3307 std::vector<spv::Id> components;
3308 for (int c = 0; c < vectorSize; ++c)
3309 components.push_back(constant);
3310 return builder.makeCompositeConstant(vectorTypeId, components);
3311}
3312
John Kessenich426394d2015-07-23 10:22:48 -06003313// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003314spv::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 -06003315{
3316 spv::Op opCode = spv::OpNop;
3317
3318 switch (op) {
3319 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003320 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003321 opCode = spv::OpAtomicIAdd;
3322 break;
3323 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003324 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003325 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003326 break;
3327 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003328 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003329 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003330 break;
3331 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003332 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003333 opCode = spv::OpAtomicAnd;
3334 break;
3335 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003336 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003337 opCode = spv::OpAtomicOr;
3338 break;
3339 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003340 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003341 opCode = spv::OpAtomicXor;
3342 break;
3343 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003344 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003345 opCode = spv::OpAtomicExchange;
3346 break;
3347 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003348 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003349 opCode = spv::OpAtomicCompareExchange;
3350 break;
3351 case glslang::EOpAtomicCounterIncrement:
3352 opCode = spv::OpAtomicIIncrement;
3353 break;
3354 case glslang::EOpAtomicCounterDecrement:
3355 opCode = spv::OpAtomicIDecrement;
3356 break;
3357 case glslang::EOpAtomicCounter:
3358 opCode = spv::OpAtomicLoad;
3359 break;
3360 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003361 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003362 break;
3363 }
3364
3365 // Sort out the operands
3366 // - mapping from glslang -> SPV
3367 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003368 // - compare-exchange swaps the value and comparator
3369 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003370 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3371 auto opIt = operands.begin(); // walk the glslang operands
3372 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003373 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3374 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3375 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003376 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3377 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003378 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003379 spvAtomicOperands.push_back(*(opIt + 1));
3380 spvAtomicOperands.push_back(*opIt);
3381 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003382 }
John Kessenich426394d2015-07-23 10:22:48 -06003383
John Kessenich3e60a6f2015-09-14 22:45:16 -06003384 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003385 for (; opIt != operands.end(); ++opIt)
3386 spvAtomicOperands.push_back(*opIt);
3387
3388 return builder.createOp(opCode, typeId, spvAtomicOperands);
3389}
3390
John Kessenich5e4b1242015-08-06 22:53:06 -06003391spv::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 -06003392{
John Kessenich5e4b1242015-08-06 22:53:06 -06003393 bool isUnsigned = typeProxy == glslang::EbtUint;
3394 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3395
John Kessenich140f3df2015-06-26 16:58:36 -06003396 spv::Op opCode = spv::OpNop;
3397 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003398 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003399 spv::Id typeId0 = 0;
3400 if (consumedOperands > 0)
3401 typeId0 = builder.getTypeId(operands[0]);
3402 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003403
3404 switch (op) {
3405 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 if (isFloat)
3407 libCall = spv::GLSLstd450FMin;
3408 else if (isUnsigned)
3409 libCall = spv::GLSLstd450UMin;
3410 else
3411 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003412 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003413 break;
3414 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003415 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003416 break;
3417 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003418 if (isFloat)
3419 libCall = spv::GLSLstd450FMax;
3420 else if (isUnsigned)
3421 libCall = spv::GLSLstd450UMax;
3422 else
3423 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003424 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003425 break;
3426 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003427 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003428 break;
3429 case glslang::EOpDot:
3430 opCode = spv::OpDot;
3431 break;
3432 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003433 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003434 break;
3435
3436 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003437 if (isFloat)
3438 libCall = spv::GLSLstd450FClamp;
3439 else if (isUnsigned)
3440 libCall = spv::GLSLstd450UClamp;
3441 else
3442 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003443 builder.promoteScalar(precision, operands.front(), operands[1]);
3444 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003445 break;
3446 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003447 if (isFloat)
3448 libCall = spv::GLSLstd450FMix;
John Kessenich6c292d32016-02-15 20:58:50 -07003449 else {
3450 opCode = spv::OpSelect;
3451 spv::MissingFunctionality("translating integer mix to OpSelect");
3452 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003453 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003454 break;
3455 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003456 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003457 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003458 break;
3459 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003460 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003461 builder.promoteScalar(precision, operands[0], operands[2]);
3462 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003463 break;
3464
3465 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003466 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003467 break;
3468 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003469 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003470 break;
3471 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003472 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003473 break;
3474 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003475 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003476 break;
3477 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003478 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003479 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003480 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003481 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003482 libCall = spv::GLSLstd450InterpolateAtSample;
3483 break;
3484 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003485 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003486 libCall = spv::GLSLstd450InterpolateAtOffset;
3487 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003488 case glslang::EOpAddCarry:
3489 opCode = spv::OpIAddCarry;
3490 typeId = builder.makeStructResultType(typeId0, typeId0);
3491 consumedOperands = 2;
3492 break;
3493 case glslang::EOpSubBorrow:
3494 opCode = spv::OpISubBorrow;
3495 typeId = builder.makeStructResultType(typeId0, typeId0);
3496 consumedOperands = 2;
3497 break;
3498 case glslang::EOpUMulExtended:
3499 opCode = spv::OpUMulExtended;
3500 typeId = builder.makeStructResultType(typeId0, typeId0);
3501 consumedOperands = 2;
3502 break;
3503 case glslang::EOpIMulExtended:
3504 opCode = spv::OpSMulExtended;
3505 typeId = builder.makeStructResultType(typeId0, typeId0);
3506 consumedOperands = 2;
3507 break;
3508 case glslang::EOpBitfieldExtract:
3509 if (isUnsigned)
3510 opCode = spv::OpBitFieldUExtract;
3511 else
3512 opCode = spv::OpBitFieldSExtract;
3513 break;
3514 case glslang::EOpBitfieldInsert:
3515 opCode = spv::OpBitFieldInsert;
3516 break;
3517
3518 case glslang::EOpFma:
3519 libCall = spv::GLSLstd450Fma;
3520 break;
3521 case glslang::EOpFrexp:
3522 libCall = spv::GLSLstd450FrexpStruct;
3523 if (builder.getNumComponents(operands[0]) == 1)
3524 frexpIntType = builder.makeIntegerType(32, true);
3525 else
3526 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3527 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3528 consumedOperands = 1;
3529 break;
3530 case glslang::EOpLdexp:
3531 libCall = spv::GLSLstd450Ldexp;
3532 break;
3533
John Kessenich140f3df2015-06-26 16:58:36 -06003534 default:
3535 return 0;
3536 }
3537
3538 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003539 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003540 // Use an extended instruction from the standard library.
3541 // Construct the call arguments, without modifying the original operands vector.
3542 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3543 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003544 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003545 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003546 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003547 case 0:
3548 // should all be handled by visitAggregate and createNoArgOperation
3549 assert(0);
3550 return 0;
3551 case 1:
3552 // should all be handled by createUnaryOperation
3553 assert(0);
3554 return 0;
3555 case 2:
3556 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3557 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003558 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003559 // anything 3 or over doesn't have l-value operands, so all should be consumed
3560 assert(consumedOperands == operands.size());
3561 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003562 break;
3563 }
3564 }
3565
John Kessenich55e7d112015-11-15 21:33:39 -07003566 // Decode the return types that were structures
3567 switch (op) {
3568 case glslang::EOpAddCarry:
3569 case glslang::EOpSubBorrow:
3570 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3571 id = builder.createCompositeExtract(id, typeId0, 0);
3572 break;
3573 case glslang::EOpUMulExtended:
3574 case glslang::EOpIMulExtended:
3575 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3576 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3577 break;
3578 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003579 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003580 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3581 id = builder.createCompositeExtract(id, typeId0, 0);
3582 break;
3583 default:
3584 break;
3585 }
3586
John Kessenich32cfd492016-02-02 12:37:46 -07003587 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003588}
3589
3590// Intrinsics with no arguments, no return value, and no precision.
3591spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3592{
3593 // TODO: get the barrier operands correct
3594
3595 switch (op) {
3596 case glslang::EOpEmitVertex:
3597 builder.createNoResultOp(spv::OpEmitVertex);
3598 return 0;
3599 case glslang::EOpEndPrimitive:
3600 builder.createNoResultOp(spv::OpEndPrimitive);
3601 return 0;
3602 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003603 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3604 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003605 return 0;
3606 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003607 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003608 return 0;
3609 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003610 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003611 return 0;
3612 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003613 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003614 return 0;
3615 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003616 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003617 return 0;
3618 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003619 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003620 return 0;
3621 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003622 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003623 return 0;
3624 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003625 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003626 return 0;
3627 }
3628}
3629
3630spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3631{
John Kessenich2f273362015-07-18 22:34:27 -06003632 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003633 spv::Id id;
3634 if (symbolValues.end() != iter) {
3635 id = iter->second;
3636 return id;
3637 }
3638
3639 // it was not found, create it
3640 id = createSpvVariable(symbol);
3641 symbolValues[symbol->getId()] = id;
3642
3643 if (! symbol->getType().isStruct()) {
3644 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003645 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003646 if (symbol->getType().getQualifier().hasSpecConstantId())
3647 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003648 if (symbol->getQualifier().hasLocation())
3649 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3650 if (symbol->getQualifier().hasIndex())
3651 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3652 if (symbol->getQualifier().hasComponent())
3653 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3654 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003655 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003656 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003657 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003658 if (symbol->getQualifier().hasXfbBuffer())
3659 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3660 if (symbol->getQualifier().hasXfbOffset())
3661 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3662 }
3663 }
3664
John Kesseniche0b6cad2015-12-24 10:30:13 -07003665 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07003666 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07003667 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003668 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003669 }
John Kessenich140f3df2015-06-26 16:58:36 -06003670 if (symbol->getQualifier().hasSet())
3671 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003672 else if (IsDescriptorResource(symbol->getType())) {
3673 // default to 0
3674 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3675 }
John Kessenich140f3df2015-06-26 16:58:36 -06003676 if (symbol->getQualifier().hasBinding())
3677 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003678 if (symbol->getQualifier().hasAttachment())
3679 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003680 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003681 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003682 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003683 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003684 if (symbol->getQualifier().hasXfbBuffer())
3685 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3686 }
3687
Rex Xu1da878f2016-02-21 20:59:01 +08003688 if (symbol->getType().isImage()) {
3689 std::vector<spv::Decoration> memory;
3690 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
3691 for (unsigned int i = 0; i < memory.size(); ++i)
3692 addDecoration(id, memory[i]);
3693 }
3694
John Kessenich140f3df2015-06-26 16:58:36 -06003695 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003696 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003697 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003698 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003699
John Kessenich140f3df2015-06-26 16:58:36 -06003700 return id;
3701}
3702
John Kessenich55e7d112015-11-15 21:33:39 -07003703// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003704void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3705{
3706 if (dec != spv::BadValue)
3707 builder.addDecoration(id, dec);
3708}
3709
John Kessenich55e7d112015-11-15 21:33:39 -07003710// If 'dec' is valid, add a one-operand decoration to an object
3711void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3712{
3713 if (dec != spv::BadValue)
3714 builder.addDecoration(id, dec, value);
3715}
3716
3717// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003718void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3719{
3720 if (dec != spv::BadValue)
3721 builder.addMemberDecoration(id, (unsigned)member, dec);
3722}
3723
John Kessenich92187592016-02-01 13:45:25 -07003724// If 'dec' is valid, add a one-operand decoration to a struct member
3725void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3726{
3727 if (dec != spv::BadValue)
3728 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3729}
3730
John Kessenich55e7d112015-11-15 21:33:39 -07003731// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003732// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003733//
3734// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3735//
3736// Recursively walk the nodes. The nodes form a tree whose leaves are
3737// regular constants, which themselves are trees that createSpvConstant()
3738// recursively walks. So, this function walks the "top" of the tree:
3739// - emit specialization constant-building instructions for specConstant
3740// - when running into a non-spec-constant, switch to createSpvConstant()
3741spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3742{
3743 assert(node.getQualifier().storage == glslang::EvqConst);
3744
John Kessenich6c292d32016-02-15 20:58:50 -07003745 if (! node.getQualifier().specConstant) {
3746 // hand off to the non-spec-constant path
3747 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3748 int nextConst = 0;
3749 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3750 nextConst, false);
3751 }
3752
3753 // We now know we have a specialization constant to build
3754
3755 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3756 // this is a direct literal assigned to a layout(constant_id=) declaration
3757 int nextConst = 0;
3758 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3759 nextConst, true);
3760 } else {
3761 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3762 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3763 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3764 std::vector<spv::Id> dimConstId;
3765 for (int dim = 0; dim < 3; ++dim) {
3766 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3767 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3768 if (specConst)
3769 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3770 }
3771 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3772 } else {
3773 spv::MissingFunctionality("specialization-constant expression trees");
3774 return spv::NoResult;
3775 }
3776 }
John Kessenich55e7d112015-11-15 21:33:39 -07003777}
3778
John Kessenich140f3df2015-06-26 16:58:36 -06003779// Use 'consts' as the flattened glslang source of scalar constants to recursively
3780// build the aggregate SPIR-V constant.
3781//
3782// If there are not enough elements present in 'consts', 0 will be substituted;
3783// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3784//
John Kessenich55e7d112015-11-15 21:33:39 -07003785spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003786{
3787 // vector of constants for SPIR-V
3788 std::vector<spv::Id> spvConsts;
3789
3790 // Type is used for struct and array constants
3791 spv::Id typeId = convertGlslangToSpvType(glslangType);
3792
3793 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003794 glslang::TType elementType(glslangType, 0);
3795 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003796 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003797 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003798 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003799 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003800 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003801 } else if (glslangType.getStruct()) {
3802 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3803 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003804 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003805 } else if (glslangType.isVector()) {
3806 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3807 bool zero = nextConst >= consts.size();
3808 switch (glslangType.getBasicType()) {
3809 case glslang::EbtInt:
3810 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3811 break;
3812 case glslang::EbtUint:
3813 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3814 break;
3815 case glslang::EbtFloat:
3816 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3817 break;
3818 case glslang::EbtDouble:
3819 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3820 break;
3821 case glslang::EbtBool:
3822 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3823 break;
3824 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003825 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003826 break;
3827 }
3828 ++nextConst;
3829 }
3830 } else {
3831 // we have a non-aggregate (scalar) constant
3832 bool zero = nextConst >= consts.size();
3833 spv::Id scalar = 0;
3834 switch (glslangType.getBasicType()) {
3835 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003836 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003837 break;
3838 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003839 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003840 break;
3841 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003842 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003843 break;
3844 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003845 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003846 break;
3847 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003848 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003849 break;
3850 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003851 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003852 break;
3853 }
3854 ++nextConst;
3855 return scalar;
3856 }
3857
3858 return builder.makeCompositeConstant(typeId, spvConsts);
3859}
3860
John Kessenich7c1aa102015-10-15 13:29:11 -06003861// Return true if the node is a constant or symbol whose reading has no
3862// non-trivial observable cost or effect.
3863bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3864{
3865 // don't know what this is
3866 if (node == nullptr)
3867 return false;
3868
3869 // a constant is safe
3870 if (node->getAsConstantUnion() != nullptr)
3871 return true;
3872
3873 // not a symbol means non-trivial
3874 if (node->getAsSymbolNode() == nullptr)
3875 return false;
3876
3877 // a symbol, depends on what's being read
3878 switch (node->getType().getQualifier().storage) {
3879 case glslang::EvqTemporary:
3880 case glslang::EvqGlobal:
3881 case glslang::EvqIn:
3882 case glslang::EvqInOut:
3883 case glslang::EvqConst:
3884 case glslang::EvqConstReadOnly:
3885 case glslang::EvqUniform:
3886 return true;
3887 default:
3888 return false;
3889 }
3890}
3891
3892// A node is trivial if it is a single operation with no side effects.
3893// Error on the side of saying non-trivial.
3894// Return true if trivial.
3895bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3896{
3897 if (node == nullptr)
3898 return false;
3899
3900 // symbols and constants are trivial
3901 if (isTrivialLeaf(node))
3902 return true;
3903
3904 // otherwise, it needs to be a simple operation or one or two leaf nodes
3905
3906 // not a simple operation
3907 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3908 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3909 if (binaryNode == nullptr && unaryNode == nullptr)
3910 return false;
3911
3912 // not on leaf nodes
3913 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3914 return false;
3915
3916 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3917 return false;
3918 }
3919
3920 switch (node->getAsOperator()->getOp()) {
3921 case glslang::EOpLogicalNot:
3922 case glslang::EOpConvIntToBool:
3923 case glslang::EOpConvUintToBool:
3924 case glslang::EOpConvFloatToBool:
3925 case glslang::EOpConvDoubleToBool:
3926 case glslang::EOpEqual:
3927 case glslang::EOpNotEqual:
3928 case glslang::EOpLessThan:
3929 case glslang::EOpGreaterThan:
3930 case glslang::EOpLessThanEqual:
3931 case glslang::EOpGreaterThanEqual:
3932 case glslang::EOpIndexDirect:
3933 case glslang::EOpIndexDirectStruct:
3934 case glslang::EOpLogicalXor:
3935 case glslang::EOpAny:
3936 case glslang::EOpAll:
3937 return true;
3938 default:
3939 return false;
3940 }
3941}
3942
3943// Emit short-circuiting code, where 'right' is never evaluated unless
3944// the left side is true (for &&) or false (for ||).
3945spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3946{
3947 spv::Id boolTypeId = builder.makeBoolType();
3948
3949 // emit left operand
3950 builder.clearAccessChain();
3951 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003952 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003953
3954 // Operands to accumulate OpPhi operands
3955 std::vector<spv::Id> phiOperands;
3956 // accumulate left operand's phi information
3957 phiOperands.push_back(leftId);
3958 phiOperands.push_back(builder.getBuildPoint()->getId());
3959
3960 // Make the two kinds of operation symmetric with a "!"
3961 // || => emit "if (! left) result = right"
3962 // && => emit "if ( left) result = right"
3963 //
3964 // TODO: this runtime "not" for || could be avoided by adding functionality
3965 // to 'builder' to have an "else" without an "then"
3966 if (op == glslang::EOpLogicalOr)
3967 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3968
3969 // make an "if" based on the left value
3970 spv::Builder::If ifBuilder(leftId, builder);
3971
3972 // emit right operand as the "then" part of the "if"
3973 builder.clearAccessChain();
3974 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08003975 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06003976
3977 // accumulate left operand's phi information
3978 phiOperands.push_back(rightId);
3979 phiOperands.push_back(builder.getBuildPoint()->getId());
3980
3981 // finish the "if"
3982 ifBuilder.makeEndIf();
3983
3984 // phi together the two results
3985 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3986}
3987
John Kessenich140f3df2015-06-26 16:58:36 -06003988}; // end anonymous namespace
3989
3990namespace glslang {
3991
John Kessenich68d78fd2015-07-12 19:28:10 -06003992void GetSpirvVersion(std::string& version)
3993{
John Kessenich9e55f632015-07-15 10:03:39 -06003994 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003995 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003996 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003997 version = buf;
3998}
3999
John Kessenich140f3df2015-06-26 16:58:36 -06004000// Write SPIR-V out to a binary file
4001void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
4002{
4003 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06004004 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06004005 for (int i = 0; i < (int)spirv.size(); ++i) {
4006 unsigned int word = spirv[i];
4007 out.write((const char*)&word, 4);
4008 }
4009 out.close();
4010}
4011
4012//
4013// Set up the glslang traversal
4014//
4015void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
4016{
4017 TIntermNode* root = intermediate.getTreeRoot();
4018
4019 if (root == 0)
4020 return;
4021
4022 glslang::GetThreadPoolAllocator().push();
4023
4024 TGlslangToSpvTraverser it(&intermediate);
4025
4026 root->traverse(&it);
4027
4028 it.dumpSpv(spirv);
4029
4030 glslang::GetThreadPoolAllocator().pop();
4031}
4032
4033}; // end namespace glslang