blob: 81f7cc1c65124adfb82e90056e4eebba06765832 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
55#include <string>
56#include <map>
57#include <list>
58#include <vector>
59#include <stack>
60#include <fstream>
61
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
69//
70// The main holder of information for translating glslang to SPIR-V.
71//
72// Derives from the AST walking base class.
73//
74class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
75public:
76 TGlslangToSpvTraverser(const glslang::TIntermediate*);
77 virtual ~TGlslangToSpvTraverser();
78
79 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
80 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
81 void visitConstantUnion(glslang::TIntermConstantUnion*);
82 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
83 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
84 void visitSymbol(glslang::TIntermSymbol* symbol);
85 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
86 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
87 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
88
John Kessenich7ba63412015-12-20 17:37:07 -070089 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060090
91protected:
John Kessenich5e801132016-02-15 11:09:46 -070092 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -070093 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -070094 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -060095 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
96 spv::Id getSampledType(const glslang::TSampler&);
97 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070098 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -070099 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700100 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800101 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenichf85e8062015-12-19 13:57:10 -0700102 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700103 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
104 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
105 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
108 void makeFunctions(const glslang::TIntermSequence&);
109 void makeGlobalInitializers(const glslang::TIntermSequence&);
110 void visitFunctions(const glslang::TIntermSequence&);
111 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800112 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600113 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
114 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600115 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
116
117 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700118 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800119 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -0700120 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600121 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
122 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800123 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600124 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600125 spv::Id createNoArgOperation(glslang::TOperator op);
126 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
127 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700128 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600129 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700130 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700131 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
132 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600133 bool isTrivialLeaf(const glslang::TIntermTyped* node);
134 bool isTrivial(const glslang::TIntermTyped* node);
135 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600136
137 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700138 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600139 int sequenceDepth;
140
141 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
142 spv::Builder builder;
143 bool inMain;
144 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700145 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700146 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600147 const glslang::TIntermediate* glslangIntermediate;
148 spv::Id stdBuiltins;
149
John Kessenich2f273362015-07-18 22:34:27 -0600150 std::unordered_map<int, spv::Id> symbolValues;
151 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
152 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700153 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600154 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600155 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600156};
157
158//
159// Helper functions for translating glslang representations to SPIR-V enumerants.
160//
161
162// Translate glslang profile to SPIR-V source language.
163spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
164{
165 switch (profile) {
166 case ENoProfile:
167 case ECoreProfile:
168 case ECompatibilityProfile:
169 return spv::SourceLanguageGLSL;
170 case EEsProfile:
171 return spv::SourceLanguageESSL;
172 default:
173 return spv::SourceLanguageUnknown;
174 }
175}
176
177// Translate glslang language (stage) to SPIR-V execution model.
178spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
179{
180 switch (stage) {
181 case EShLangVertex: return spv::ExecutionModelVertex;
182 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
183 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
184 case EShLangGeometry: return spv::ExecutionModelGeometry;
185 case EShLangFragment: return spv::ExecutionModelFragment;
186 case EShLangCompute: return spv::ExecutionModelGLCompute;
187 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700188 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600189 return spv::ExecutionModelFragment;
190 }
191}
192
193// Translate glslang type to SPIR-V storage class.
194spv::StorageClass TranslateStorageClass(const glslang::TType& type)
195{
196 if (type.getQualifier().isPipeInput())
197 return spv::StorageClassInput;
198 else if (type.getQualifier().isPipeOutput())
199 return spv::StorageClassOutput;
200 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700201 if (type.getQualifier().layoutPushConstant)
202 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600203 if (type.getBasicType() == glslang::EbtBlock)
204 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800205 else if (type.getBasicType() == glslang::EbtAtomicUint)
206 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600207 else
208 return spv::StorageClassUniformConstant;
209 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
210 } else {
211 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700212 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
213 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600214 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
215 case glslang::EvqTemporary: return spv::StorageClassFunction;
216 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700217 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600218 return spv::StorageClassFunction;
219 }
220 }
221}
222
223// Translate glslang sampler type to SPIR-V dimensionality.
224spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
225{
226 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700227 case glslang::Esd1D: return spv::Dim1D;
228 case glslang::Esd2D: return spv::Dim2D;
229 case glslang::Esd3D: return spv::Dim3D;
230 case glslang::EsdCube: return spv::DimCube;
231 case glslang::EsdRect: return spv::DimRect;
232 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700233 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600234 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700235 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600236 return spv::Dim2D;
237 }
238}
239
240// Translate glslang type to SPIR-V precision decorations.
241spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
242{
243 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700244 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600245 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600246 default:
247 return spv::NoPrecision;
248 }
249}
250
251// Translate glslang type to SPIR-V block decorations.
252spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
253{
254 if (type.getBasicType() == glslang::EbtBlock) {
255 switch (type.getQualifier().storage) {
256 case glslang::EvqUniform: return spv::DecorationBlock;
257 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
258 case glslang::EvqVaryingIn: return spv::DecorationBlock;
259 case glslang::EvqVaryingOut: return spv::DecorationBlock;
260 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700261 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600262 break;
263 }
264 }
265
266 return (spv::Decoration)spv::BadValue;
267}
268
269// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700270spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600271{
272 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700273 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600274 case glslang::ElmRowMajor:
275 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700276 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600277 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700278 default:
279 // opaque layouts don't need a majorness
280 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600281 }
282 } else {
283 switch (type.getBasicType()) {
284 default:
285 return (spv::Decoration)spv::BadValue;
286 break;
287 case glslang::EbtBlock:
288 switch (type.getQualifier().storage) {
289 case glslang::EvqUniform:
290 case glslang::EvqBuffer:
291 switch (type.getQualifier().layoutPacking) {
292 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600293 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
294 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600295 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600296 }
297 case glslang::EvqVaryingIn:
298 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700299 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600300 return (spv::Decoration)spv::BadValue;
301 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700302 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600303 return (spv::Decoration)spv::BadValue;
304 }
305 }
306 }
307}
308
309// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700310// Returns spv::Decoration(spv::BadValue) when no decoration
311// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700312spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600313{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700314 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700315 // Smooth decoration doesn't exist in SPIR-V 1.0
316 return (spv::Decoration)spv::BadValue;
317 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700318 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700319 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700320 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600321 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700322 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600323 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700324 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600325 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700326 else if (qualifier.sample) {
327 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600328 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700329 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600330 return (spv::Decoration)spv::BadValue;
331}
332
John Kessenich92187592016-02-01 13:45:25 -0700333// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700334spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600335{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700336 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600337 return spv::DecorationInvariant;
338 else
339 return (spv::Decoration)spv::BadValue;
340}
341
342// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700343spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600344{
345 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700346 case glslang::EbvPointSize:
347 switch (glslangIntermediate->getStage()) {
348 case EShLangGeometry:
349 builder.addCapability(spv::CapabilityGeometryPointSize);
350 break;
351 case EShLangTessControl:
352 case EShLangTessEvaluation:
353 builder.addCapability(spv::CapabilityTessellationPointSize);
354 break;
355 }
356 return spv::BuiltInPointSize;
357
358 case glslang::EbvClipDistance:
359 builder.addCapability(spv::CapabilityClipDistance);
360 return spv::BuiltInClipDistance;
361
362 case glslang::EbvCullDistance:
363 builder.addCapability(spv::CapabilityCullDistance);
364 return spv::BuiltInCullDistance;
365
366 case glslang::EbvViewportIndex:
367 // TODO: builder.addCapability(spv::CapabilityMultiViewport);
368 return spv::BuiltInViewportIndex;
369
John Kessenich5e801132016-02-15 11:09:46 -0700370 case glslang::EbvSampleId:
371 builder.addCapability(spv::CapabilitySampleRateShading);
372 return spv::BuiltInSampleId;
373
374 case glslang::EbvSamplePosition:
375 builder.addCapability(spv::CapabilitySampleRateShading);
376 return spv::BuiltInSamplePosition;
377
378 case glslang::EbvSampleMask:
379 builder.addCapability(spv::CapabilitySampleRateShading);
380 return spv::BuiltInSampleMask;
381
John Kessenich140f3df2015-06-26 16:58:36 -0600382 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600383 case glslang::EbvVertexId: return spv::BuiltInVertexId;
384 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700385 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
386 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600387 case glslang::EbvBaseVertex:
388 case glslang::EbvBaseInstance:
389 case glslang::EbvDrawId:
390 // TODO: Add SPIR-V builtin ID.
391 spv::MissingFunctionality("Draw parameters");
392 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600393 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
394 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
395 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600396 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
397 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
398 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
399 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
400 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
401 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
402 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600403 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
404 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
405 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
406 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
407 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
408 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
409 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
410 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
411 default: return (spv::BuiltIn)spv::BadValue;
412 }
413}
414
Rex Xufc618912015-09-09 16:42:49 +0800415// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700416spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800417{
418 assert(type.getBasicType() == glslang::EbtSampler);
419
John Kessenich5d0fa972016-02-15 11:57:00 -0700420 // Check for capabilities
421 switch (type.getQualifier().layoutFormat) {
422 case glslang::ElfRg32f:
423 case glslang::ElfRg16f:
424 case glslang::ElfR11fG11fB10f:
425 case glslang::ElfR16f:
426 case glslang::ElfRgba16:
427 case glslang::ElfRgb10A2:
428 case glslang::ElfRg16:
429 case glslang::ElfRg8:
430 case glslang::ElfR16:
431 case glslang::ElfR8:
432 case glslang::ElfRgba16Snorm:
433 case glslang::ElfRg16Snorm:
434 case glslang::ElfRg8Snorm:
435 case glslang::ElfR16Snorm:
436 case glslang::ElfR8Snorm:
437
438 case glslang::ElfRg32i:
439 case glslang::ElfRg16i:
440 case glslang::ElfRg8i:
441 case glslang::ElfR16i:
442 case glslang::ElfR8i:
443
444 case glslang::ElfRgb10a2ui:
445 case glslang::ElfRg32ui:
446 case glslang::ElfRg16ui:
447 case glslang::ElfRg8ui:
448 case glslang::ElfR16ui:
449 case glslang::ElfR8ui:
450 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
451 break;
452
453 default:
454 break;
455 }
456
457 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800458 switch (type.getQualifier().layoutFormat) {
459 case glslang::ElfNone: return spv::ImageFormatUnknown;
460 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
461 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
462 case glslang::ElfR32f: return spv::ImageFormatR32f;
463 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
464 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
465 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
466 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
467 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
468 case glslang::ElfR16f: return spv::ImageFormatR16f;
469 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
470 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
471 case glslang::ElfRg16: return spv::ImageFormatRg16;
472 case glslang::ElfRg8: return spv::ImageFormatRg8;
473 case glslang::ElfR16: return spv::ImageFormatR16;
474 case glslang::ElfR8: return spv::ImageFormatR8;
475 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
476 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
477 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
478 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
479 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
480 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
481 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
482 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
483 case glslang::ElfR32i: return spv::ImageFormatR32i;
484 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
485 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
486 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
487 case glslang::ElfR16i: return spv::ImageFormatR16i;
488 case glslang::ElfR8i: return spv::ImageFormatR8i;
489 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
490 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
491 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
492 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
493 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
494 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
495 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
496 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
497 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
498 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
499 default: return (spv::ImageFormat)spv::BadValue;
500 }
501}
502
John Kessenich6c292d32016-02-15 20:58:50 -0700503// Return whether or not the given type is something that should be tied to a
504// descriptor set.
505bool IsDescriptorResource(const glslang::TType& type)
506{
507 // uniform and buffer blocks are included
508 if (type.getBasicType() == glslang::EbtBlock)
509 return type.getQualifier().isUniformOrBuffer();
510
511 // non block...
512 // basically samplerXXX/subpass/sampler/texture are all included
513 // if they are the global-scope-class, not the function parameter
514 // (or local, if they ever exist) class.
515 if (type.getBasicType() == glslang::EbtSampler)
516 return type.getQualifier().isUniformOrBuffer();
517
518 // None of the above.
519 return false;
520}
521
John Kesseniche0b6cad2015-12-24 10:30:13 -0700522void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
523{
524 if (child.layoutMatrix == glslang::ElmNone)
525 child.layoutMatrix = parent.layoutMatrix;
526
527 if (parent.invariant)
528 child.invariant = true;
529 if (parent.nopersp)
530 child.nopersp = true;
531 if (parent.flat)
532 child.flat = true;
533 if (parent.centroid)
534 child.centroid = true;
535 if (parent.patch)
536 child.patch = true;
537 if (parent.sample)
538 child.sample = true;
539}
540
541bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
542{
John Kessenich7b9fa252016-01-21 18:56:57 -0700543 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700544 // - struct members can inherit from a struct declaration
545 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
546 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700547 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700548}
549
John Kessenich140f3df2015-06-26 16:58:36 -0600550//
551// Implement the TGlslangToSpvTraverser class.
552//
553
554TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
555 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700556 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600557 inMain(false), mainTerminated(false), linkageOnly(false),
558 glslangIntermediate(glslangIntermediate)
559{
560 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
561
562 builder.clearAccessChain();
563 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
564 stdBuiltins = builder.import("GLSL.std.450");
565 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
566 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700567 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600568
569 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600570 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
571 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600572 builder.addSourceExtension(it->c_str());
573
574 // Add the top-level modes for this shader.
575
John Kessenich92187592016-02-01 13:45:25 -0700576 if (glslangIntermediate->getXfbMode()) {
577 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600578 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700579 }
John Kessenich140f3df2015-06-26 16:58:36 -0600580
581 unsigned int mode;
582 switch (glslangIntermediate->getStage()) {
583 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600584 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600585 break;
586
587 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600588 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600589 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
590 break;
591
592 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600593 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600594 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700595 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
596 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
597 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600598 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600599 }
600 if (mode != spv::BadValue)
601 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
602
John Kesseniche6903322015-10-13 16:29:02 -0600603 switch (glslangIntermediate->getVertexSpacing()) {
604 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
605 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
606 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
607 default: mode = spv::BadValue; break;
608 }
609 if (mode != spv::BadValue)
610 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
611
612 switch (glslangIntermediate->getVertexOrder()) {
613 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
614 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
615 default: mode = spv::BadValue; break;
616 }
617 if (mode != spv::BadValue)
618 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
619
620 if (glslangIntermediate->getPointMode())
621 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600622 break;
623
624 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600625 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600626 switch (glslangIntermediate->getInputPrimitive()) {
627 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
628 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
629 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700630 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600631 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
632 default: mode = spv::BadValue; break;
633 }
634 if (mode != spv::BadValue)
635 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600636
John Kessenich140f3df2015-06-26 16:58:36 -0600637 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
638
639 switch (glslangIntermediate->getOutputPrimitive()) {
640 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
641 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
642 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
643 default: mode = spv::BadValue; break;
644 }
645 if (mode != spv::BadValue)
646 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
647 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
648 break;
649
650 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600651 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600652 if (glslangIntermediate->getPixelCenterInteger())
653 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600654
John Kessenich140f3df2015-06-26 16:58:36 -0600655 if (glslangIntermediate->getOriginUpperLeft())
656 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600657 else
658 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600659
660 if (glslangIntermediate->getEarlyFragmentTests())
661 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
662
663 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600664 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
665 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
666 default: mode = spv::BadValue; break;
667 }
668 if (mode != spv::BadValue)
669 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
670
671 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
672 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600673 break;
674
675 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600676 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600677 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
678 glslangIntermediate->getLocalSize(1),
679 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600680 break;
681
682 default:
683 break;
684 }
685
686}
687
John Kessenich7ba63412015-12-20 17:37:07 -0700688// Finish everything and dump
689void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
690{
691 // finish off the entry-point SPV instruction by adding the Input/Output <id>
692 for (auto it : iOSet)
693 entryPoint->addIdOperand(it);
694
695 builder.dump(out);
696}
697
John Kessenich140f3df2015-06-26 16:58:36 -0600698TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
699{
700 if (! mainTerminated) {
701 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
702 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600703 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600704 }
705}
706
707//
708// Implement the traversal functions.
709//
710// Return true from interior nodes to have the external traversal
711// continue on to children. Return false if children were
712// already processed.
713//
714
715//
716// Symbols can turn into
717// - uniform/input reads
718// - output writes
719// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
720// - something simple that degenerates into the last bullet
721//
722void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
723{
724 // getSymbolId() will set up all the IO decorations on the first call.
725 // Formal function parameters were mapped during makeFunctions().
726 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700727
728 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
729 if (builder.isPointer(id)) {
730 spv::StorageClass sc = builder.getStorageClass(id);
731 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
732 iOSet.insert(id);
733 }
734
735 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700736 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600737 // Prepare to generate code for the access
738
739 // L-value chains will be computed left to right. We're on the symbol now,
740 // which is the left-most part of the access chain, so now is "clear" time,
741 // followed by setting the base.
742 builder.clearAccessChain();
743
744 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700745 // except for
746 // A) "const in" arguments to a function, which are an intermediate object.
747 // See comments in handleUserFunctionCall().
748 // B) Specialization constants (normal constant don't even come in as a variable),
749 // These are also pure R-values.
750 glslang::TQualifier qualifier = symbol->getQualifier();
751 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
752 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600753 builder.setAccessChainRValue(id);
754 else
755 builder.setAccessChainLValue(id);
756 }
757}
758
759bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
760{
761 // First, handle special cases
762 switch (node->getOp()) {
763 case glslang::EOpAssign:
764 case glslang::EOpAddAssign:
765 case glslang::EOpSubAssign:
766 case glslang::EOpMulAssign:
767 case glslang::EOpVectorTimesMatrixAssign:
768 case glslang::EOpVectorTimesScalarAssign:
769 case glslang::EOpMatrixTimesScalarAssign:
770 case glslang::EOpMatrixTimesMatrixAssign:
771 case glslang::EOpDivAssign:
772 case glslang::EOpModAssign:
773 case glslang::EOpAndAssign:
774 case glslang::EOpInclusiveOrAssign:
775 case glslang::EOpExclusiveOrAssign:
776 case glslang::EOpLeftShiftAssign:
777 case glslang::EOpRightShiftAssign:
778 // A bin-op assign "a += b" means the same thing as "a = a + b"
779 // where a is evaluated before b. For a simple assignment, GLSL
780 // says to evaluate the left before the right. So, always, left
781 // node then right node.
782 {
783 // get the left l-value, save it away
784 builder.clearAccessChain();
785 node->getLeft()->traverse(this);
786 spv::Builder::AccessChain lValue = builder.getAccessChain();
787
788 // evaluate the right
789 builder.clearAccessChain();
790 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700791 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600792
793 if (node->getOp() != glslang::EOpAssign) {
794 // the left is also an r-value
795 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700796 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600797
798 // do the operation
799 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
800 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
801 node->getType().getBasicType());
802
803 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700804 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600805 }
806
807 // store the result
808 builder.setAccessChain(lValue);
Rex Xu27253232016-02-23 17:51:09 +0800809 accessChainStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -0600810
811 // assignments are expressions having an rValue after they are evaluated...
812 builder.clearAccessChain();
813 builder.setAccessChainRValue(rValue);
814 }
815 return false;
816 case glslang::EOpIndexDirect:
817 case glslang::EOpIndexDirectStruct:
818 {
819 // Get the left part of the access chain.
820 node->getLeft()->traverse(this);
821
822 // Add the next element in the chain
823
John Kessenich55e7d112015-11-15 21:33:39 -0700824 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600825 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
826 // This may be, e.g., an anonymous block-member selection, which generally need
827 // index remapping due to hidden members in anonymous blocks.
828 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700829 assert(remapper.size() > 0);
830 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600831 }
832
833 if (! node->getLeft()->getType().isArray() &&
834 node->getLeft()->getType().isVector() &&
835 node->getOp() == glslang::EOpIndexDirect) {
836 // This is essentially a hard-coded vector swizzle of size 1,
837 // so short circuit the access-chain stuff with a swizzle.
838 std::vector<unsigned> swizzle;
839 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600840 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600841 } else {
842 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600843 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600844 }
845 }
846 return false;
847 case glslang::EOpIndexIndirect:
848 {
849 // Structure or array or vector indirection.
850 // Will use native SPIR-V access-chain for struct and array indirection;
851 // matrices are arrays of vectors, so will also work for a matrix.
852 // Will use the access chain's 'component' for variable index into a vector.
853
854 // This adapter is building access chains left to right.
855 // Set up the access chain to the left.
856 node->getLeft()->traverse(this);
857
858 // save it so that computing the right side doesn't trash it
859 spv::Builder::AccessChain partial = builder.getAccessChain();
860
861 // compute the next index in the chain
862 builder.clearAccessChain();
863 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700864 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600865
866 // restore the saved access chain
867 builder.setAccessChain(partial);
868
869 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600870 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600871 else
John Kessenichfa668da2015-09-13 14:46:30 -0600872 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600873 }
874 return false;
875 case glslang::EOpVectorSwizzle:
876 {
877 node->getLeft()->traverse(this);
878 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
879 std::vector<unsigned> swizzle;
880 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
881 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600882 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600883 }
884 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600885 case glslang::EOpLogicalOr:
886 case glslang::EOpLogicalAnd:
887 {
888
889 // These may require short circuiting, but can sometimes be done as straight
890 // binary operations. The right operand must be short circuited if it has
891 // side effects, and should probably be if it is complex.
892 if (isTrivial(node->getRight()->getAsTyped()))
893 break; // handle below as a normal binary operation
894 // otherwise, we need to do dynamic short circuiting on the right operand
895 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
896 builder.clearAccessChain();
897 builder.setAccessChainRValue(result);
898 }
899 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600900 default:
901 break;
902 }
903
904 // Assume generic binary op...
905
John Kessenich32cfd492016-02-02 12:37:46 -0700906 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600907 builder.clearAccessChain();
908 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700909 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600910
John Kessenich32cfd492016-02-02 12:37:46 -0700911 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600912 builder.clearAccessChain();
913 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700914 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600915
John Kessenich32cfd492016-02-02 12:37:46 -0700916 // get result
917 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
918 convertGlslangToSpvType(node->getType()), left, right,
919 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600920
John Kessenich50e57562015-12-21 21:21:11 -0700921 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600922 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700923 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700924 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600925 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600926 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600927 return false;
928 }
John Kessenich140f3df2015-06-26 16:58:36 -0600929}
930
931bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
932{
John Kessenichfc51d282015-08-19 13:34:18 -0600933 spv::Id result = spv::NoResult;
934
935 // try texturing first
936 result = createImageTextureFunctionCall(node);
937 if (result != spv::NoResult) {
938 builder.clearAccessChain();
939 builder.setAccessChainRValue(result);
940
941 return false; // done with this node
942 }
943
944 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600945
946 if (node->getOp() == glslang::EOpArrayLength) {
947 // Quite special; won't want to evaluate the operand.
948
949 // Normal .length() would have been constant folded by the front-end.
950 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600951 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600952 assert(node->getOperand()->getType().isRuntimeSizedArray());
953 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
954 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600955 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
956 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600957
958 builder.clearAccessChain();
959 builder.setAccessChainRValue(length);
960
961 return false;
962 }
963
John Kessenichfc51d282015-08-19 13:34:18 -0600964 // Start by evaluating the operand
965
John Kessenich140f3df2015-06-26 16:58:36 -0600966 builder.clearAccessChain();
967 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800968
Rex Xufc618912015-09-09 16:42:49 +0800969 spv::Id operand = spv::NoResult;
970
971 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
972 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800973 node->getOp() == glslang::EOpAtomicCounter ||
974 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800975 operand = builder.accessChainGetLValue(); // Special case l-value operands
976 else
John Kessenich32cfd492016-02-02 12:37:46 -0700977 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600978
979 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
980
981 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600982 if (! result)
983 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600984
985 // if not, then possibly an operation
986 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700987 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600988
989 if (result) {
990 builder.clearAccessChain();
991 builder.setAccessChainRValue(result);
992
993 return false; // done with this node
994 }
995
996 // it must be a special case, check...
997 switch (node->getOp()) {
998 case glslang::EOpPostIncrement:
999 case glslang::EOpPostDecrement:
1000 case glslang::EOpPreIncrement:
1001 case glslang::EOpPreDecrement:
1002 {
1003 // we need the integer value "1" or the floating point "1.0" to add/subtract
1004 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1005 builder.makeFloatConstant(1.0F) :
1006 builder.makeIntConstant(1);
1007 glslang::TOperator op;
1008 if (node->getOp() == glslang::EOpPreIncrement ||
1009 node->getOp() == glslang::EOpPostIncrement)
1010 op = glslang::EOpAdd;
1011 else
1012 op = glslang::EOpSub;
1013
1014 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1015 convertGlslangToSpvType(node->getType()), operand, one,
1016 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001017 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001018
1019 // The result of operation is always stored, but conditionally the
1020 // consumed result. The consumed result is always an r-value.
1021 builder.accessChainStore(result);
1022 builder.clearAccessChain();
1023 if (node->getOp() == glslang::EOpPreIncrement ||
1024 node->getOp() == glslang::EOpPreDecrement)
1025 builder.setAccessChainRValue(result);
1026 else
1027 builder.setAccessChainRValue(operand);
1028 }
1029
1030 return false;
1031
1032 case glslang::EOpEmitStreamVertex:
1033 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1034 return false;
1035 case glslang::EOpEndStreamPrimitive:
1036 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1037 return false;
1038
1039 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001040 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001041 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001042 }
John Kessenich140f3df2015-06-26 16:58:36 -06001043}
1044
1045bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1046{
John Kessenichfc51d282015-08-19 13:34:18 -06001047 spv::Id result = spv::NoResult;
1048
1049 // try texturing
1050 result = createImageTextureFunctionCall(node);
1051 if (result != spv::NoResult) {
1052 builder.clearAccessChain();
1053 builder.setAccessChainRValue(result);
1054
1055 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001056 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001057 // "imageStore" is a special case, which has no result
1058 return false;
1059 }
John Kessenichfc51d282015-08-19 13:34:18 -06001060
John Kessenich140f3df2015-06-26 16:58:36 -06001061 glslang::TOperator binOp = glslang::EOpNull;
1062 bool reduceComparison = true;
1063 bool isMatrix = false;
1064 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001065 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001066
1067 assert(node->getOp());
1068
1069 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1070
1071 switch (node->getOp()) {
1072 case glslang::EOpSequence:
1073 {
1074 if (preVisit)
1075 ++sequenceDepth;
1076 else
1077 --sequenceDepth;
1078
1079 if (sequenceDepth == 1) {
1080 // If this is the parent node of all the functions, we want to see them
1081 // early, so all call points have actual SPIR-V functions to reference.
1082 // In all cases, still let the traverser visit the children for us.
1083 makeFunctions(node->getAsAggregate()->getSequence());
1084
1085 // Also, we want all globals initializers to go into the entry of main(), before
1086 // anything else gets there, so visit out of order, doing them all now.
1087 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1088
1089 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1090 // so do them manually.
1091 visitFunctions(node->getAsAggregate()->getSequence());
1092
1093 return false;
1094 }
1095
1096 return true;
1097 }
1098 case glslang::EOpLinkerObjects:
1099 {
1100 if (visit == glslang::EvPreVisit)
1101 linkageOnly = true;
1102 else
1103 linkageOnly = false;
1104
1105 return true;
1106 }
1107 case glslang::EOpComma:
1108 {
1109 // processing from left to right naturally leaves the right-most
1110 // lying around in the access chain
1111 glslang::TIntermSequence& glslangOperands = node->getSequence();
1112 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1113 glslangOperands[i]->traverse(this);
1114
1115 return false;
1116 }
1117 case glslang::EOpFunction:
1118 if (visit == glslang::EvPreVisit) {
1119 if (isShaderEntrypoint(node)) {
1120 inMain = true;
1121 builder.setBuildPoint(shaderEntry->getLastBlock());
1122 } else {
1123 handleFunctionEntry(node);
1124 }
1125 } else {
1126 if (inMain)
1127 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001128 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001129 inMain = false;
1130 }
1131
1132 return true;
1133 case glslang::EOpParameters:
1134 // Parameters will have been consumed by EOpFunction processing, but not
1135 // the body, so we still visited the function node's children, making this
1136 // child redundant.
1137 return false;
1138 case glslang::EOpFunctionCall:
1139 {
1140 if (node->isUserDefined())
1141 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001142 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1143 if (result) {
1144 builder.clearAccessChain();
1145 builder.setAccessChainRValue(result);
1146 } else
1147 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001148
1149 return false;
1150 }
1151 case glslang::EOpConstructMat2x2:
1152 case glslang::EOpConstructMat2x3:
1153 case glslang::EOpConstructMat2x4:
1154 case glslang::EOpConstructMat3x2:
1155 case glslang::EOpConstructMat3x3:
1156 case glslang::EOpConstructMat3x4:
1157 case glslang::EOpConstructMat4x2:
1158 case glslang::EOpConstructMat4x3:
1159 case glslang::EOpConstructMat4x4:
1160 case glslang::EOpConstructDMat2x2:
1161 case glslang::EOpConstructDMat2x3:
1162 case glslang::EOpConstructDMat2x4:
1163 case glslang::EOpConstructDMat3x2:
1164 case glslang::EOpConstructDMat3x3:
1165 case glslang::EOpConstructDMat3x4:
1166 case glslang::EOpConstructDMat4x2:
1167 case glslang::EOpConstructDMat4x3:
1168 case glslang::EOpConstructDMat4x4:
1169 isMatrix = true;
1170 // fall through
1171 case glslang::EOpConstructFloat:
1172 case glslang::EOpConstructVec2:
1173 case glslang::EOpConstructVec3:
1174 case glslang::EOpConstructVec4:
1175 case glslang::EOpConstructDouble:
1176 case glslang::EOpConstructDVec2:
1177 case glslang::EOpConstructDVec3:
1178 case glslang::EOpConstructDVec4:
1179 case glslang::EOpConstructBool:
1180 case glslang::EOpConstructBVec2:
1181 case glslang::EOpConstructBVec3:
1182 case glslang::EOpConstructBVec4:
1183 case glslang::EOpConstructInt:
1184 case glslang::EOpConstructIVec2:
1185 case glslang::EOpConstructIVec3:
1186 case glslang::EOpConstructIVec4:
1187 case glslang::EOpConstructUint:
1188 case glslang::EOpConstructUVec2:
1189 case glslang::EOpConstructUVec3:
1190 case glslang::EOpConstructUVec4:
1191 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001192 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001193 {
1194 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001195 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001196 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1197 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001198 if (node->getOp() == glslang::EOpConstructTextureSampler)
1199 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1200 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001201 std::vector<spv::Id> constituents;
1202 for (int c = 0; c < (int)arguments.size(); ++c)
1203 constituents.push_back(arguments[c]);
1204 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001205 } else if (isMatrix)
1206 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1207 else
1208 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001209
1210 builder.clearAccessChain();
1211 builder.setAccessChainRValue(constructed);
1212
1213 return false;
1214 }
1215
1216 // These six are component-wise compares with component-wise results.
1217 // Forward on to createBinaryOperation(), requesting a vector result.
1218 case glslang::EOpLessThan:
1219 case glslang::EOpGreaterThan:
1220 case glslang::EOpLessThanEqual:
1221 case glslang::EOpGreaterThanEqual:
1222 case glslang::EOpVectorEqual:
1223 case glslang::EOpVectorNotEqual:
1224 {
1225 // Map the operation to a binary
1226 binOp = node->getOp();
1227 reduceComparison = false;
1228 switch (node->getOp()) {
1229 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1230 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1231 default: binOp = node->getOp(); break;
1232 }
1233
1234 break;
1235 }
1236 case glslang::EOpMul:
1237 // compontent-wise matrix multiply
1238 binOp = glslang::EOpMul;
1239 break;
1240 case glslang::EOpOuterProduct:
1241 // two vectors multiplied to make a matrix
1242 binOp = glslang::EOpOuterProduct;
1243 break;
1244 case glslang::EOpDot:
1245 {
1246 // for scalar dot product, use multiply
1247 glslang::TIntermSequence& glslangOperands = node->getSequence();
1248 if (! glslangOperands[0]->getAsTyped()->isVector())
1249 binOp = glslang::EOpMul;
1250 break;
1251 }
1252 case glslang::EOpMod:
1253 // when an aggregate, this is the floating-point mod built-in function,
1254 // which can be emitted by the one in createBinaryOperation()
1255 binOp = glslang::EOpMod;
1256 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001257 case glslang::EOpEmitVertex:
1258 case glslang::EOpEndPrimitive:
1259 case glslang::EOpBarrier:
1260 case glslang::EOpMemoryBarrier:
1261 case glslang::EOpMemoryBarrierAtomicCounter:
1262 case glslang::EOpMemoryBarrierBuffer:
1263 case glslang::EOpMemoryBarrierImage:
1264 case glslang::EOpMemoryBarrierShared:
1265 case glslang::EOpGroupMemoryBarrier:
1266 noReturnValue = true;
1267 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1268 break;
1269
John Kessenich426394d2015-07-23 10:22:48 -06001270 case glslang::EOpAtomicAdd:
1271 case glslang::EOpAtomicMin:
1272 case glslang::EOpAtomicMax:
1273 case glslang::EOpAtomicAnd:
1274 case glslang::EOpAtomicOr:
1275 case glslang::EOpAtomicXor:
1276 case glslang::EOpAtomicExchange:
1277 case glslang::EOpAtomicCompSwap:
1278 atomic = true;
1279 break;
1280
John Kessenich140f3df2015-06-26 16:58:36 -06001281 default:
1282 break;
1283 }
1284
1285 //
1286 // See if it maps to a regular operation.
1287 //
John Kessenich140f3df2015-06-26 16:58:36 -06001288 if (binOp != glslang::EOpNull) {
1289 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1290 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1291 assert(left && right);
1292
1293 builder.clearAccessChain();
1294 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001295 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001296
1297 builder.clearAccessChain();
1298 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001299 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001300
1301 result = createBinaryOperation(binOp, precision,
1302 convertGlslangToSpvType(node->getType()), leftId, rightId,
1303 left->getType().getBasicType(), reduceComparison);
1304
1305 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001306 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001307 builder.clearAccessChain();
1308 builder.setAccessChainRValue(result);
1309
1310 return false;
1311 }
1312
John Kessenich426394d2015-07-23 10:22:48 -06001313 //
1314 // Create the list of operands.
1315 //
John Kessenich140f3df2015-06-26 16:58:36 -06001316 glslang::TIntermSequence& glslangOperands = node->getSequence();
1317 std::vector<spv::Id> operands;
1318 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1319 builder.clearAccessChain();
1320 glslangOperands[arg]->traverse(this);
1321
1322 // special case l-value operands; there are just a few
1323 bool lvalue = false;
1324 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001325 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001326 case glslang::EOpModf:
1327 if (arg == 1)
1328 lvalue = true;
1329 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001330 case glslang::EOpInterpolateAtSample:
1331 case glslang::EOpInterpolateAtOffset:
1332 if (arg == 0)
1333 lvalue = true;
1334 break;
Rex Xud4782c12015-09-06 16:30:11 +08001335 case glslang::EOpAtomicAdd:
1336 case glslang::EOpAtomicMin:
1337 case glslang::EOpAtomicMax:
1338 case glslang::EOpAtomicAnd:
1339 case glslang::EOpAtomicOr:
1340 case glslang::EOpAtomicXor:
1341 case glslang::EOpAtomicExchange:
1342 case glslang::EOpAtomicCompSwap:
1343 if (arg == 0)
1344 lvalue = true;
1345 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001346 case glslang::EOpAddCarry:
1347 case glslang::EOpSubBorrow:
1348 if (arg == 2)
1349 lvalue = true;
1350 break;
1351 case glslang::EOpUMulExtended:
1352 case glslang::EOpIMulExtended:
1353 if (arg >= 2)
1354 lvalue = true;
1355 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001356 default:
1357 break;
1358 }
1359 if (lvalue)
1360 operands.push_back(builder.accessChainGetLValue());
1361 else
John Kessenich32cfd492016-02-02 12:37:46 -07001362 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001363 }
John Kessenich426394d2015-07-23 10:22:48 -06001364
1365 if (atomic) {
1366 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001367 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001368 } else {
1369 // Pass through to generic operations.
1370 switch (glslangOperands.size()) {
1371 case 0:
1372 result = createNoArgOperation(node->getOp());
1373 break;
1374 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001375 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001376 break;
1377 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001378 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001379 break;
1380 }
John Kessenich140f3df2015-06-26 16:58:36 -06001381 }
1382
1383 if (noReturnValue)
1384 return false;
1385
1386 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001387 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001388 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001389 } else {
1390 builder.clearAccessChain();
1391 builder.setAccessChainRValue(result);
1392 return false;
1393 }
1394}
1395
1396bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1397{
1398 // This path handles both if-then-else and ?:
1399 // The if-then-else has a node type of void, while
1400 // ?: has a non-void node type
1401 spv::Id result = 0;
1402 if (node->getBasicType() != glslang::EbtVoid) {
1403 // don't handle this as just on-the-fly temporaries, because there will be two names
1404 // and better to leave SSA to later passes
1405 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1406 }
1407
1408 // emit the condition before doing anything with selection
1409 node->getCondition()->traverse(this);
1410
1411 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001412 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001413
1414 if (node->getTrueBlock()) {
1415 // emit the "then" statement
1416 node->getTrueBlock()->traverse(this);
1417 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001418 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001419 }
1420
1421 if (node->getFalseBlock()) {
1422 ifBuilder.makeBeginElse();
1423 // emit the "else" statement
1424 node->getFalseBlock()->traverse(this);
1425 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001426 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001427 }
1428
1429 ifBuilder.makeEndIf();
1430
1431 if (result) {
1432 // GLSL only has r-values as the result of a :?, but
1433 // if we have an l-value, that can be more efficient if it will
1434 // become the base of a complex r-value expression, because the
1435 // next layer copies r-values into memory to use the access-chain mechanism
1436 builder.clearAccessChain();
1437 builder.setAccessChainLValue(result);
1438 }
1439
1440 return false;
1441}
1442
1443bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1444{
1445 // emit and get the condition before doing anything with switch
1446 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001447 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001448
1449 // browse the children to sort out code segments
1450 int defaultSegment = -1;
1451 std::vector<TIntermNode*> codeSegments;
1452 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1453 std::vector<int> caseValues;
1454 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1455 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1456 TIntermNode* child = *c;
1457 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001458 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001459 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001460 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001461 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1462 } else
1463 codeSegments.push_back(child);
1464 }
1465
1466 // handle the case where the last code segment is missing, due to no code
1467 // statements between the last case and the end of the switch statement
1468 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1469 (int)codeSegments.size() == defaultSegment)
1470 codeSegments.push_back(nullptr);
1471
1472 // make the switch statement
1473 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001474 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001475
1476 // emit all the code in the segments
1477 breakForLoop.push(false);
1478 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1479 builder.nextSwitchSegment(segmentBlocks, s);
1480 if (codeSegments[s])
1481 codeSegments[s]->traverse(this);
1482 else
1483 builder.addSwitchBreak();
1484 }
1485 breakForLoop.pop();
1486
1487 builder.endSwitch(segmentBlocks);
1488
1489 return false;
1490}
1491
1492void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1493{
1494 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001495 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001496
1497 builder.clearAccessChain();
1498 builder.setAccessChainRValue(constant);
1499}
1500
1501bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1502{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001503 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001504 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001505 // Spec requires back edges to target header blocks, and every header block
1506 // must dominate its merge block. Make a header block first to ensure these
1507 // conditions are met. By definition, it will contain OpLoopMerge, followed
1508 // by a block-ending branch. But we don't want to put any other body/test
1509 // instructions in it, since the body/test may have arbitrary instructions,
1510 // including merges of its own.
1511 builder.setBuildPoint(&blocks.head);
1512 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001513 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001514 spv::Block& test = builder.makeNewBlock();
1515 builder.createBranch(&test);
1516
1517 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001518 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001519 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001520 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001521 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1522
1523 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001524 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001525 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001526 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001527 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001528 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001529
1530 builder.setBuildPoint(&blocks.continue_target);
1531 if (node->getTerminal())
1532 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001533 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001534 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001535 builder.createBranch(&blocks.body);
1536
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001537 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001538 builder.setBuildPoint(&blocks.body);
1539 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001540 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001541 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001542 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001543
1544 builder.setBuildPoint(&blocks.continue_target);
1545 if (node->getTerminal())
1546 node->getTerminal()->traverse(this);
1547 if (node->getTest()) {
1548 node->getTest()->traverse(this);
1549 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001550 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001551 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001552 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001553 // TODO: unless there was a break/return/discard instruction
1554 // somewhere in the body, this is an infinite loop, so we should
1555 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001556 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001557 }
John Kessenich140f3df2015-06-26 16:58:36 -06001558 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001559 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001560 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001561 return false;
1562}
1563
1564bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1565{
1566 if (node->getExpression())
1567 node->getExpression()->traverse(this);
1568
1569 switch (node->getFlowOp()) {
1570 case glslang::EOpKill:
1571 builder.makeDiscard();
1572 break;
1573 case glslang::EOpBreak:
1574 if (breakForLoop.top())
1575 builder.createLoopExit();
1576 else
1577 builder.addSwitchBreak();
1578 break;
1579 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001580 builder.createLoopContinue();
1581 break;
1582 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001583 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001584 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001585 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001586 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001587
1588 builder.clearAccessChain();
1589 break;
1590
1591 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001592 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001593 break;
1594 }
1595
1596 return false;
1597}
1598
1599spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1600{
1601 // First, steer off constants, which are not SPIR-V variables, but
1602 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001603 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001604 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001605 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001606 }
1607
1608 // Now, handle actual variables
1609 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1610 spv::Id spvType = convertGlslangToSpvType(node->getType());
1611
1612 const char* name = node->getName().c_str();
1613 if (glslang::IsAnonymous(name))
1614 name = "";
1615
1616 return builder.createVariable(storageClass, spvType, name);
1617}
1618
1619// Return type Id of the sampled type.
1620spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1621{
1622 switch (sampler.type) {
1623 case glslang::EbtFloat: return builder.makeFloatType(32);
1624 case glslang::EbtInt: return builder.makeIntType(32);
1625 case glslang::EbtUint: return builder.makeUintType(32);
1626 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001627 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001628 return builder.makeFloatType(32);
1629 }
1630}
1631
John Kessenich3ac051e2015-12-20 11:29:16 -07001632// Convert from a glslang type to an SPV type, by calling into a
1633// recursive version of this function. This establishes the inherited
1634// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001635spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1636{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001637 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001638}
1639
1640// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001641// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001642spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001643{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001644 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001645
1646 switch (type.getBasicType()) {
1647 case glslang::EbtVoid:
1648 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001649 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001650 break;
1651 case glslang::EbtFloat:
1652 spvType = builder.makeFloatType(32);
1653 break;
1654 case glslang::EbtDouble:
1655 spvType = builder.makeFloatType(64);
1656 break;
1657 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001658 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1659 // a 32-bit int where non-0 means true.
1660 if (explicitLayout != glslang::ElpNone)
1661 spvType = builder.makeUintType(32);
1662 else
1663 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001664 break;
1665 case glslang::EbtInt:
1666 spvType = builder.makeIntType(32);
1667 break;
1668 case glslang::EbtUint:
1669 spvType = builder.makeUintType(32);
1670 break;
John Kessenich426394d2015-07-23 10:22:48 -06001671 case glslang::EbtAtomicUint:
1672 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1673 spvType = builder.makeUintType(32);
1674 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001675 case glslang::EbtSampler:
1676 {
1677 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001678 if (sampler.sampler) {
1679 // pure sampler
1680 spvType = builder.makeSamplerType();
1681 } else {
1682 // an image is present, make its type
1683 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1684 sampler.image ? 2 : 1, TranslateImageFormat(type));
1685 if (sampler.combined) {
1686 // already has both image and sampler, make the combined type
1687 spvType = builder.makeSampledImageType(spvType);
1688 }
John Kessenich55e7d112015-11-15 21:33:39 -07001689 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001690 }
John Kessenich140f3df2015-06-26 16:58:36 -06001691 break;
1692 case glslang::EbtStruct:
1693 case glslang::EbtBlock:
1694 {
1695 // If we've seen this struct type, return it
1696 const glslang::TTypeList* glslangStruct = type.getStruct();
1697 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001698
1699 // Try to share structs for different layouts, but not yet for other
1700 // kinds of qualification (primarily not yet including interpolant qualification).
1701 if (! HasNonLayoutQualifiers(qualifier))
1702 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1703 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001704 break;
1705
1706 // else, we haven't seen it...
1707
1708 // Create a vector of struct types for SPIR-V to consume
1709 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1710 if (type.getBasicType() == glslang::EbtBlock)
1711 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001712 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001713 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1714 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1715 if (glslangType.hiddenMember()) {
1716 ++memberDelta;
1717 if (type.getBasicType() == glslang::EbtBlock)
1718 memberRemapper[glslangStruct][i] = -1;
1719 } else {
1720 if (type.getBasicType() == glslang::EbtBlock)
1721 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001722 // modify just this child's view of the qualifier
1723 glslang::TQualifier subQualifier = glslangType.getQualifier();
1724 InheritQualifiers(subQualifier, qualifier);
John Kessenich09677482016-02-19 12:21:50 -07001725
1726 // manually inherit location; it's more complex
1727 if (! subQualifier.hasLocation() && qualifier.hasLocation())
1728 subQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
1729 if (qualifier.hasLocation())
John Kessenich7b9fa252016-01-21 18:56:57 -07001730 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001731
1732 // recurse
John Kesseniche0b6cad2015-12-24 10:30:13 -07001733 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001734 }
1735 }
1736
1737 // Make the SPIR-V type
1738 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001739 if (! HasNonLayoutQualifiers(qualifier))
1740 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001741
1742 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001743 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001744 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001745 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1746 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1747 int member = i;
1748 if (type.getBasicType() == glslang::EbtBlock)
1749 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001750
John Kesseniche0b6cad2015-12-24 10:30:13 -07001751 // modify just this child's view of the qualifier
1752 glslang::TQualifier subQualifier = glslangType.getQualifier();
1753 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001754
John Kessenich140f3df2015-06-26 16:58:36 -06001755 // using -1 above to indicate a hidden member
1756 if (member >= 0) {
1757 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001758 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001759 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001760 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1761 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich09677482016-02-19 12:21:50 -07001762
1763 // compute location decoration; tricky based on whether inheritance is at play
1764 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
1765 // probably move to the linker stage of the front end proper, and just have the
1766 // answer sitting already distributed throughout the individual member locations.
1767 int location = -1; // will only decorate if present or inherited
1768 if (subQualifier.hasLocation()) // no inheritance, or override of inheritance
1769 location = subQualifier.layoutLocation;
1770 else if (qualifier.hasLocation()) // inheritance
1771 location = qualifier.layoutLocation + locationOffset;
1772 if (qualifier.hasLocation()) // track for upcoming inheritance
John Kessenich7b9fa252016-01-21 18:56:57 -07001773 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
John Kessenich09677482016-02-19 12:21:50 -07001774 if (location >= 0)
1775 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
1776
1777 // component, XFB, others
John Kessenich140f3df2015-06-26 16:58:36 -06001778 if (glslangType.getQualifier().hasComponent())
1779 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1780 if (glslangType.getQualifier().hasXfbOffset())
1781 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001782 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001783 // figure out what to do with offset, which is accumulating
1784 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001785 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001786 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001787 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001788 offset = nextOffset;
1789 }
John Kessenich140f3df2015-06-26 16:58:36 -06001790
John Kessenichf85e8062015-12-19 13:57:10 -07001791 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001792 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001793
John Kessenich140f3df2015-06-26 16:58:36 -06001794 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001795 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1796 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001797 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001798 }
1799 }
1800
1801 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001802 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001803 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001804 if (type.getQualifier().hasStream()) {
1805 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001806 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001807 }
John Kessenich140f3df2015-06-26 16:58:36 -06001808 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001809 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001810 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001811 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001812 if (type.getQualifier().hasXfbBuffer())
1813 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1814 }
1815 }
1816 break;
1817 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001818 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001819 break;
1820 }
1821
1822 if (type.isMatrix())
1823 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1824 else {
1825 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1826 if (type.getVectorSize() > 1)
1827 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1828 }
1829
1830 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001831 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1832
John Kessenichc9a80832015-09-12 12:17:44 -06001833 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001834 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001835 // We need to decorate array strides for types needing explicit layout, except blocks.
1836 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001837 // Use a dummy glslang type for querying internal strides of
1838 // arrays of arrays, but using just a one-dimensional array.
1839 glslang::TType simpleArrayType(type, 0); // deference type of the array
1840 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1841 simpleArrayType.getArraySizes().dereference();
1842
1843 // Will compute the higher-order strides here, rather than making a whole
1844 // pile of types and doing repetitive recursion on their contents.
1845 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1846 }
John Kessenichf8842e52016-01-04 19:22:56 -07001847
1848 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001849 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001850 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001851 if (stride > 0)
1852 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001853 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001854 }
1855 } else {
1856 // single-dimensional array, and don't yet have stride
1857
John Kessenichf8842e52016-01-04 19:22:56 -07001858 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001859 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1860 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001861 }
John Kessenich31ed4832015-09-09 17:51:38 -06001862
John Kessenichc9a80832015-09-12 12:17:44 -06001863 // Do the outer dimension, which might not be known for a runtime-sized array
1864 if (type.isRuntimeSizedArray()) {
1865 spvType = builder.makeRuntimeArray(spvType);
1866 } else {
1867 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001868 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001869 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001870 if (stride > 0)
1871 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001872 }
1873
1874 return spvType;
1875}
1876
John Kessenich6c292d32016-02-15 20:58:50 -07001877// Turn the expression forming the array size into an id.
1878// This is not quite trivial, because of specialization constants.
1879// Sometimes, a raw constant is turned into an Id, and sometimes
1880// a specialization constant expression is.
1881spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1882{
1883 // First, see if this is sized with a node, meaning a specialization constant:
1884 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1885 if (specNode != nullptr) {
1886 builder.clearAccessChain();
1887 specNode->traverse(this);
1888 return accessChainLoad(specNode->getAsTyped()->getType());
1889 }
1890
1891 // Otherwise, need a compile-time (front end) size, get it:
1892 int size = arraySizes.getDimSize(dim);
1893 assert(size > 0);
1894 return builder.makeUintConstant(size);
1895}
1896
John Kessenich103bef92016-02-08 21:38:15 -07001897// Wrap the builder's accessChainLoad to:
1898// - localize handling of RelaxedPrecision
1899// - use the SPIR-V inferred type instead of another conversion of the glslang type
1900// (avoids unnecessary work and possible type punning for structures)
1901// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001902spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1903{
John Kessenich103bef92016-02-08 21:38:15 -07001904 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1905 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1906
1907 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08001908 if (type.getBasicType() == glslang::EbtBool) {
1909 if (builder.isScalarType(nominalTypeId)) {
1910 // Conversion for bool
1911 spv::Id boolType = builder.makeBoolType();
1912 if (nominalTypeId != boolType)
1913 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
1914 } else if (builder.isVectorType(nominalTypeId)) {
1915 // Conversion for bvec
1916 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1917 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1918 if (nominalTypeId != bvecType)
1919 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
1920 }
1921 }
John Kessenich103bef92016-02-08 21:38:15 -07001922
1923 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001924}
1925
Rex Xu27253232016-02-23 17:51:09 +08001926// Wrap the builder's accessChainStore to:
1927// - do conversion of concrete to abstract type
1928void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
1929{
1930 // Need to convert to abstract types when necessary
1931 if (type.getBasicType() == glslang::EbtBool) {
1932 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1933
1934 if (builder.isScalarType(nominalTypeId)) {
1935 // Conversion for bool
1936 spv::Id boolType = builder.makeBoolType();
1937 if (nominalTypeId != boolType) {
1938 spv::Id zero = builder.makeUintConstant(0);
1939 spv::Id one = builder.makeUintConstant(1);
1940 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1941 }
1942 } else if (builder.isVectorType(nominalTypeId)) {
1943 // Conversion for bvec
1944 int vecSize = builder.getNumTypeComponents(nominalTypeId);
1945 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
1946 if (nominalTypeId != bvecType) {
1947 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
1948 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
1949 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
1950 }
1951 }
1952 }
1953
1954 builder.accessChainStore(rvalue);
1955}
1956
John Kessenichf85e8062015-12-19 13:57:10 -07001957// Decide whether or not this type should be
1958// decorated with offsets and strides, and if so
1959// whether std140 or std430 rules should be applied.
1960glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001961{
John Kessenichf85e8062015-12-19 13:57:10 -07001962 // has to be a block
1963 if (type.getBasicType() != glslang::EbtBlock)
1964 return glslang::ElpNone;
1965
1966 // has to be a uniform or buffer block
1967 if (type.getQualifier().storage != glslang::EvqUniform &&
1968 type.getQualifier().storage != glslang::EvqBuffer)
1969 return glslang::ElpNone;
1970
1971 // return the layout to use
1972 switch (type.getQualifier().layoutPacking) {
1973 case glslang::ElpStd140:
1974 case glslang::ElpStd430:
1975 return type.getQualifier().layoutPacking;
1976 default:
1977 return glslang::ElpNone;
1978 }
John Kessenich31ed4832015-09-09 17:51:38 -06001979}
1980
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001981// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001982int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001983{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001984 int size;
John Kessenich49987892015-12-29 17:11:44 -07001985 int stride;
1986 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001987
1988 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001989}
1990
John Kessenich49987892015-12-29 17:11:44 -07001991// 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 -07001992// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001993int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001994{
John Kessenich49987892015-12-29 17:11:44 -07001995 glslang::TType elementType;
1996 elementType.shallowCopy(matrixType);
1997 elementType.clearArraySizes();
1998
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001999 int size;
John Kessenich49987892015-12-29 17:11:44 -07002000 int stride;
2001 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2002
2003 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002004}
2005
John Kessenich5e4b1242015-08-06 22:53:06 -06002006// Given a member type of a struct, realign the current offset for it, and compute
2007// the next (not yet aligned) offset for the next member, which will get aligned
2008// on the next call.
2009// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2010// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2011// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002012void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002013 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002014{
2015 // this will get a positive value when deemed necessary
2016 nextOffset = -1;
2017
John Kessenich5e4b1242015-08-06 22:53:06 -06002018 // override anything in currentOffset with user-set offset
2019 if (memberType.getQualifier().hasOffset())
2020 currentOffset = memberType.getQualifier().layoutOffset;
2021
2022 // It could be that current linker usage in glslang updated all the layoutOffset,
2023 // in which case the following code does not matter. But, that's not quite right
2024 // once cross-compilation unit GLSL validation is done, as the original user
2025 // settings are needed in layoutOffset, and then the following will come into play.
2026
John Kessenichf85e8062015-12-19 13:57:10 -07002027 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002028 if (! memberType.getQualifier().hasOffset())
2029 currentOffset = -1;
2030
2031 return;
2032 }
2033
John Kessenichf85e8062015-12-19 13:57:10 -07002034 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002035 if (currentOffset < 0)
2036 currentOffset = 0;
2037
2038 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2039 // but possibly not yet correctly aligned.
2040
2041 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002042 int dummyStride;
2043 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06002044 glslang::RoundToPow2(currentOffset, memberAlignment);
2045 nextOffset = currentOffset + memberSize;
2046}
2047
John Kessenich140f3df2015-06-26 16:58:36 -06002048bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
2049{
2050 return node->getName() == "main(";
2051}
2052
2053// Make all the functions, skeletally, without actually visiting their bodies.
2054void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2055{
2056 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2057 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2058 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2059 continue;
2060
2061 // We're on a user function. Set up the basic interface for the function now,
2062 // so that it's available to call.
2063 // Translating the body will happen later.
2064 //
2065 // Typically (except for a "const in" parameter), an address will be passed to the
2066 // function. What it is an address of varies:
2067 //
2068 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2069 // so that write needs to be to a copy, hence the address of a copy works.
2070 //
2071 // - "const in" parameters can just be the r-value, as no writes need occur.
2072 //
2073 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2074 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2075
2076 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002077 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002078 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2079
2080 for (int p = 0; p < (int)parameters.size(); ++p) {
2081 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2082 spv::Id typeId = convertGlslangToSpvType(paramType);
2083 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2084 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2085 else
2086 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002087 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002088 paramTypes.push_back(typeId);
2089 }
2090
2091 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002092 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2093 convertGlslangToSpvType(glslFunction->getType()),
2094 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002095
2096 // Track function to emit/call later
2097 functionMap[glslFunction->getName().c_str()] = function;
2098
2099 // Set the parameter id's
2100 for (int p = 0; p < (int)parameters.size(); ++p) {
2101 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2102 // give a name too
2103 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2104 }
2105 }
2106}
2107
2108// Process all the initializers, while skipping the functions and link objects
2109void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2110{
2111 builder.setBuildPoint(shaderEntry->getLastBlock());
2112 for (int i = 0; i < (int)initializers.size(); ++i) {
2113 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2114 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2115
2116 // We're on a top-level node that's not a function. Treat as an initializer, whose
2117 // code goes into the beginning of main.
2118 initializer->traverse(this);
2119 }
2120 }
2121}
2122
2123// Process all the functions, while skipping initializers.
2124void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2125{
2126 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2127 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2128 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2129 node->traverse(this);
2130 }
2131}
2132
2133void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2134{
2135 // SPIR-V functions should already be in the functionMap from the prepass
2136 // that called makeFunctions().
2137 spv::Function* function = functionMap[node->getName().c_str()];
2138 spv::Block* functionBlock = function->getEntryBlock();
2139 builder.setBuildPoint(functionBlock);
2140}
2141
Rex Xu04db3f52015-09-16 11:44:02 +08002142void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002143{
Rex Xufc618912015-09-09 16:42:49 +08002144 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002145
2146 glslang::TSampler sampler = {};
2147 bool cubeCompare = false;
2148 if (node.isTexture()) {
2149 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2150 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2151 }
2152
John Kessenich140f3df2015-06-26 16:58:36 -06002153 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2154 builder.clearAccessChain();
2155 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002156
2157 // Special case l-value operands
2158 bool lvalue = false;
2159 switch (node.getOp()) {
2160 case glslang::EOpImageAtomicAdd:
2161 case glslang::EOpImageAtomicMin:
2162 case glslang::EOpImageAtomicMax:
2163 case glslang::EOpImageAtomicAnd:
2164 case glslang::EOpImageAtomicOr:
2165 case glslang::EOpImageAtomicXor:
2166 case glslang::EOpImageAtomicExchange:
2167 case glslang::EOpImageAtomicCompSwap:
2168 if (i == 0)
2169 lvalue = true;
2170 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002171 case glslang::EOpSparseTexture:
2172 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2173 lvalue = true;
2174 break;
2175 case glslang::EOpSparseTextureClamp:
2176 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2177 lvalue = true;
2178 break;
2179 case glslang::EOpSparseTextureLod:
2180 case glslang::EOpSparseTextureOffset:
2181 if (i == 3)
2182 lvalue = true;
2183 break;
2184 case glslang::EOpSparseTextureFetch:
2185 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2186 lvalue = true;
2187 break;
2188 case glslang::EOpSparseTextureFetchOffset:
2189 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2190 lvalue = true;
2191 break;
2192 case glslang::EOpSparseTextureLodOffset:
2193 case glslang::EOpSparseTextureGrad:
2194 case glslang::EOpSparseTextureOffsetClamp:
2195 if (i == 4)
2196 lvalue = true;
2197 break;
2198 case glslang::EOpSparseTextureGradOffset:
2199 case glslang::EOpSparseTextureGradClamp:
2200 if (i == 5)
2201 lvalue = true;
2202 break;
2203 case glslang::EOpSparseTextureGradOffsetClamp:
2204 if (i == 6)
2205 lvalue = true;
2206 break;
2207 case glslang::EOpSparseTextureGather:
2208 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2209 lvalue = true;
2210 break;
2211 case glslang::EOpSparseTextureGatherOffset:
2212 case glslang::EOpSparseTextureGatherOffsets:
2213 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2214 lvalue = true;
2215 break;
Rex Xufc618912015-09-09 16:42:49 +08002216 default:
2217 break;
2218 }
2219
Rex Xu6b86d492015-09-16 17:48:22 +08002220 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002221 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002222 else
John Kessenich32cfd492016-02-02 12:37:46 -07002223 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002224 }
2225}
2226
John Kessenichfc51d282015-08-19 13:34:18 -06002227void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002228{
John Kessenichfc51d282015-08-19 13:34:18 -06002229 builder.clearAccessChain();
2230 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002231 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002232}
John Kessenich140f3df2015-06-26 16:58:36 -06002233
John Kessenichfc51d282015-08-19 13:34:18 -06002234spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2235{
Rex Xufc618912015-09-09 16:42:49 +08002236 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002237 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002238 }
2239
John Kessenichfc51d282015-08-19 13:34:18 -06002240 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002241 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2242 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2243 std::vector<spv::Id> arguments;
2244 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002245 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002246 else
2247 translateArguments(*node->getAsUnaryNode(), arguments);
2248 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2249
2250 spv::Builder::TextureParameters params = { };
2251 params.sampler = arguments[0];
2252
Rex Xu04db3f52015-09-16 11:44:02 +08002253 glslang::TCrackedTextureOp cracked;
2254 node->crackTexture(sampler, cracked);
2255
John Kessenichfc51d282015-08-19 13:34:18 -06002256 // Check for queries
2257 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002258 // a sampled image needs to have the image extracted first
2259 if (builder.isSampledImage(params.sampler))
2260 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002261 switch (node->getOp()) {
2262 case glslang::EOpImageQuerySize:
2263 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002264 if (arguments.size() > 1) {
2265 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002266 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002267 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002268 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002269 case glslang::EOpImageQuerySamples:
2270 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002271 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002272 case glslang::EOpTextureQueryLod:
2273 params.coords = arguments[1];
2274 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2275 case glslang::EOpTextureQueryLevels:
2276 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002277 case glslang::EOpSparseTexelsResident:
2278 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002279 default:
2280 assert(0);
2281 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002282 }
John Kessenich140f3df2015-06-26 16:58:36 -06002283 }
2284
Rex Xufc618912015-09-09 16:42:49 +08002285 // Check for image functions other than queries
2286 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002287 std::vector<spv::Id> operands;
2288 auto opIt = arguments.begin();
2289 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002290
2291 // Handle subpass operations
2292 // TODO: GLSL should change to have the "MS" only on the type rather than the
2293 // built-in function.
2294 if (cracked.subpass) {
2295 // add on the (0,0) coordinate
2296 spv::Id zero = builder.makeIntConstant(0);
2297 std::vector<spv::Id> comps;
2298 comps.push_back(zero);
2299 comps.push_back(zero);
2300 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2301 if (sampler.ms) {
2302 operands.push_back(spv::ImageOperandsSampleMask);
2303 operands.push_back(*(opIt++));
2304 }
2305 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2306 }
2307
John Kessenich56bab042015-09-16 10:54:31 -06002308 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002309 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002310 if (sampler.ms) {
2311 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002312 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002313 }
John Kessenich56bab042015-09-16 10:54:31 -06002314 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002315 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2316 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002317 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002318 if (sampler.ms) {
2319 operands.push_back(*(opIt + 1));
2320 operands.push_back(spv::ImageOperandsSampleMask);
2321 operands.push_back(*opIt);
2322 } else
2323 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002324 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002325 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2326 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002327 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002328 } else if (node->isSparseImage()) {
2329 spv::MissingFunctionality("sparse image functions");
2330 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002331 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002332 // Process image atomic operations
2333
2334 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2335 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002336 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002337
Rex Xufc618912015-09-09 16:42:49 +08002338 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002339 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002340
2341 std::vector<spv::Id> operands;
2342 operands.push_back(pointer);
2343 for (; opIt != arguments.end(); ++opIt)
2344 operands.push_back(*opIt);
2345
Rex Xu04db3f52015-09-16 11:44:02 +08002346 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002347 }
2348 }
2349
2350 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002351 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002352 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2353
John Kessenichfc51d282015-08-19 13:34:18 -06002354 // check for bias argument
2355 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002356 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002357 int nonBiasArgCount = 2;
2358 if (cracked.offset)
2359 ++nonBiasArgCount;
2360 if (cracked.grad)
2361 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002362 if (cracked.lodClamp)
2363 ++nonBiasArgCount;
2364 if (sparse)
2365 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002366
2367 if ((int)arguments.size() > nonBiasArgCount)
2368 bias = true;
2369 }
2370
John Kessenichfc51d282015-08-19 13:34:18 -06002371 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002372
John Kessenichfc51d282015-08-19 13:34:18 -06002373 params.coords = arguments[1];
2374 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002375 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002376
2377 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002378 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002379 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002380 ++extraArgs;
2381 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002382 params.Dref = arguments[2];
2383 ++extraArgs;
2384 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002385 std::vector<spv::Id> indexes;
2386 int comp;
2387 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002388 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002389 else
2390 comp = builder.getNumComponents(params.coords) - 1;
2391 indexes.push_back(comp);
2392 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2393 }
2394 if (cracked.lod) {
2395 params.lod = arguments[2];
2396 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002397 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2398 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2399 noImplicitLod = true;
2400 }
2401 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002402 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002403 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002404 }
2405 if (cracked.grad) {
2406 params.gradX = arguments[2 + extraArgs];
2407 params.gradY = arguments[3 + extraArgs];
2408 extraArgs += 2;
2409 }
John Kessenich55e7d112015-11-15 21:33:39 -07002410 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002411 params.offset = arguments[2 + extraArgs];
2412 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002413 } else if (cracked.offsets) {
2414 params.offsets = arguments[2 + extraArgs];
2415 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002416 }
Rex Xu48edadf2015-12-31 16:11:41 +08002417 if (cracked.lodClamp) {
2418 params.lodClamp = arguments[2 + extraArgs];
2419 ++extraArgs;
2420 }
2421 if (sparse) {
2422 params.texelOut = arguments[2 + extraArgs];
2423 ++extraArgs;
2424 }
John Kessenichfc51d282015-08-19 13:34:18 -06002425 if (bias) {
2426 params.bias = arguments[2 + extraArgs];
2427 ++extraArgs;
2428 }
John Kessenich55e7d112015-11-15 21:33:39 -07002429 if (cracked.gather && ! sampler.shadow) {
2430 // default component is 0, if missing, otherwise an argument
2431 if (2 + extraArgs < (int)arguments.size()) {
2432 params.comp = arguments[2 + extraArgs];
2433 ++extraArgs;
2434 } else {
2435 params.comp = builder.makeIntConstant(0);
2436 }
2437 }
John Kessenichfc51d282015-08-19 13:34:18 -06002438
John Kessenich019f08f2016-02-15 15:40:42 -07002439 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002440}
2441
2442spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2443{
2444 // Grab the function's pointer from the previously created function
2445 spv::Function* function = functionMap[node->getName().c_str()];
2446 if (! function)
2447 return 0;
2448
2449 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2450 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2451
2452 // See comments in makeFunctions() for details about the semantics for parameter passing.
2453 //
2454 // These imply we need a four step process:
2455 // 1. Evaluate the arguments
2456 // 2. Allocate and make copies of in, out, and inout arguments
2457 // 3. Make the call
2458 // 4. Copy back the results
2459
2460 // 1. Evaluate the arguments
2461 std::vector<spv::Builder::AccessChain> lValues;
2462 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002463 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002464 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2465 // build l-value
2466 builder.clearAccessChain();
2467 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002468 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002469 // keep outputs as l-values, evaluate input-only as r-values
2470 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2471 // save l-value
2472 lValues.push_back(builder.getAccessChain());
2473 } else {
2474 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002475 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002476 }
2477 }
2478
2479 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2480 // copy the original into that space.
2481 //
2482 // Also, build up the list of actual arguments to pass in for the call
2483 int lValueCount = 0;
2484 int rValueCount = 0;
2485 std::vector<spv::Id> spvArgs;
2486 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2487 spv::Id arg;
2488 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2489 // need space to hold the copy
2490 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2491 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2492 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2493 // need to copy the input into output space
2494 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002495 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002496 builder.createStore(copy, arg);
2497 }
2498 ++lValueCount;
2499 } else {
2500 arg = rValues[rValueCount];
2501 ++rValueCount;
2502 }
2503 spvArgs.push_back(arg);
2504 }
2505
2506 // 3. Make the call.
2507 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002508 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002509
2510 // 4. Copy back out an "out" arguments.
2511 lValueCount = 0;
2512 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2513 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2514 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2515 spv::Id copy = builder.createLoad(spvArgs[a]);
2516 builder.setAccessChain(lValues[lValueCount]);
Rex Xu27253232016-02-23 17:51:09 +08002517 accessChainStore(glslangArgs[a]->getAsTyped()->getType(), copy);
John Kessenich140f3df2015-06-26 16:58:36 -06002518 }
2519 ++lValueCount;
2520 }
2521 }
2522
2523 return result;
2524}
2525
2526// Translate AST operation to SPV operation, already having SPV-based operands/types.
2527spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2528 spv::Id typeId, spv::Id left, spv::Id right,
2529 glslang::TBasicType typeProxy, bool reduceComparison)
2530{
2531 bool isUnsigned = typeProxy == glslang::EbtUint;
2532 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2533
2534 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002535 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002536 bool comparison = false;
2537
2538 switch (op) {
2539 case glslang::EOpAdd:
2540 case glslang::EOpAddAssign:
2541 if (isFloat)
2542 binOp = spv::OpFAdd;
2543 else
2544 binOp = spv::OpIAdd;
2545 break;
2546 case glslang::EOpSub:
2547 case glslang::EOpSubAssign:
2548 if (isFloat)
2549 binOp = spv::OpFSub;
2550 else
2551 binOp = spv::OpISub;
2552 break;
2553 case glslang::EOpMul:
2554 case glslang::EOpMulAssign:
2555 if (isFloat)
2556 binOp = spv::OpFMul;
2557 else
2558 binOp = spv::OpIMul;
2559 break;
2560 case glslang::EOpVectorTimesScalar:
2561 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002562 if (isFloat) {
2563 if (builder.isVector(right))
2564 std::swap(left, right);
2565 assert(builder.isScalar(right));
2566 needMatchingVectors = false;
2567 binOp = spv::OpVectorTimesScalar;
2568 } else
2569 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002570 break;
2571 case glslang::EOpVectorTimesMatrix:
2572 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002573 binOp = spv::OpVectorTimesMatrix;
2574 break;
2575 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002576 binOp = spv::OpMatrixTimesVector;
2577 break;
2578 case glslang::EOpMatrixTimesScalar:
2579 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002580 binOp = spv::OpMatrixTimesScalar;
2581 break;
2582 case glslang::EOpMatrixTimesMatrix:
2583 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002584 binOp = spv::OpMatrixTimesMatrix;
2585 break;
2586 case glslang::EOpOuterProduct:
2587 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002588 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002589 break;
2590
2591 case glslang::EOpDiv:
2592 case glslang::EOpDivAssign:
2593 if (isFloat)
2594 binOp = spv::OpFDiv;
2595 else if (isUnsigned)
2596 binOp = spv::OpUDiv;
2597 else
2598 binOp = spv::OpSDiv;
2599 break;
2600 case glslang::EOpMod:
2601 case glslang::EOpModAssign:
2602 if (isFloat)
2603 binOp = spv::OpFMod;
2604 else if (isUnsigned)
2605 binOp = spv::OpUMod;
2606 else
2607 binOp = spv::OpSMod;
2608 break;
2609 case glslang::EOpRightShift:
2610 case glslang::EOpRightShiftAssign:
2611 if (isUnsigned)
2612 binOp = spv::OpShiftRightLogical;
2613 else
2614 binOp = spv::OpShiftRightArithmetic;
2615 break;
2616 case glslang::EOpLeftShift:
2617 case glslang::EOpLeftShiftAssign:
2618 binOp = spv::OpShiftLeftLogical;
2619 break;
2620 case glslang::EOpAnd:
2621 case glslang::EOpAndAssign:
2622 binOp = spv::OpBitwiseAnd;
2623 break;
2624 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002625 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002626 binOp = spv::OpLogicalAnd;
2627 break;
2628 case glslang::EOpInclusiveOr:
2629 case glslang::EOpInclusiveOrAssign:
2630 binOp = spv::OpBitwiseOr;
2631 break;
2632 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002633 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002634 binOp = spv::OpLogicalOr;
2635 break;
2636 case glslang::EOpExclusiveOr:
2637 case glslang::EOpExclusiveOrAssign:
2638 binOp = spv::OpBitwiseXor;
2639 break;
2640 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002641 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002642 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002643 break;
2644
2645 case glslang::EOpLessThan:
2646 case glslang::EOpGreaterThan:
2647 case glslang::EOpLessThanEqual:
2648 case glslang::EOpGreaterThanEqual:
2649 case glslang::EOpEqual:
2650 case glslang::EOpNotEqual:
2651 case glslang::EOpVectorEqual:
2652 case glslang::EOpVectorNotEqual:
2653 comparison = true;
2654 break;
2655 default:
2656 break;
2657 }
2658
John Kessenich7c1aa102015-10-15 13:29:11 -06002659 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002660 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002661 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002662 if (builder.isMatrix(left) || builder.isMatrix(right))
2663 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002664
2665 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002666 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002667 builder.promoteScalar(precision, left, right);
2668
John Kessenich32cfd492016-02-02 12:37:46 -07002669 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002670 }
2671
2672 if (! comparison)
2673 return 0;
2674
John Kessenich7c1aa102015-10-15 13:29:11 -06002675 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002676
2677 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2678 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2679
John Kessenich22118352015-12-21 20:54:09 -07002680 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002681 }
2682
2683 switch (op) {
2684 case glslang::EOpLessThan:
2685 if (isFloat)
2686 binOp = spv::OpFOrdLessThan;
2687 else if (isUnsigned)
2688 binOp = spv::OpULessThan;
2689 else
2690 binOp = spv::OpSLessThan;
2691 break;
2692 case glslang::EOpGreaterThan:
2693 if (isFloat)
2694 binOp = spv::OpFOrdGreaterThan;
2695 else if (isUnsigned)
2696 binOp = spv::OpUGreaterThan;
2697 else
2698 binOp = spv::OpSGreaterThan;
2699 break;
2700 case glslang::EOpLessThanEqual:
2701 if (isFloat)
2702 binOp = spv::OpFOrdLessThanEqual;
2703 else if (isUnsigned)
2704 binOp = spv::OpULessThanEqual;
2705 else
2706 binOp = spv::OpSLessThanEqual;
2707 break;
2708 case glslang::EOpGreaterThanEqual:
2709 if (isFloat)
2710 binOp = spv::OpFOrdGreaterThanEqual;
2711 else if (isUnsigned)
2712 binOp = spv::OpUGreaterThanEqual;
2713 else
2714 binOp = spv::OpSGreaterThanEqual;
2715 break;
2716 case glslang::EOpEqual:
2717 case glslang::EOpVectorEqual:
2718 if (isFloat)
2719 binOp = spv::OpFOrdEqual;
2720 else
2721 binOp = spv::OpIEqual;
2722 break;
2723 case glslang::EOpNotEqual:
2724 case glslang::EOpVectorNotEqual:
2725 if (isFloat)
2726 binOp = spv::OpFOrdNotEqual;
2727 else
2728 binOp = spv::OpINotEqual;
2729 break;
2730 default:
2731 break;
2732 }
2733
John Kessenich32cfd492016-02-02 12:37:46 -07002734 if (binOp != spv::OpNop)
2735 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002736
2737 return 0;
2738}
2739
John Kessenich04bb8a02015-12-12 12:28:14 -07002740//
2741// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2742// These can be any of:
2743//
2744// matrix * scalar
2745// scalar * matrix
2746// matrix * matrix linear algebraic
2747// matrix * vector
2748// vector * matrix
2749// matrix * matrix componentwise
2750// matrix op matrix op in {+, -, /}
2751// matrix op scalar op in {+, -, /}
2752// scalar op matrix op in {+, -, /}
2753//
2754spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2755{
2756 bool firstClass = true;
2757
2758 // First, handle first-class matrix operations (* and matrix/scalar)
2759 switch (op) {
2760 case spv::OpFDiv:
2761 if (builder.isMatrix(left) && builder.isScalar(right)) {
2762 // turn matrix / scalar into a multiply...
2763 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2764 op = spv::OpMatrixTimesScalar;
2765 } else
2766 firstClass = false;
2767 break;
2768 case spv::OpMatrixTimesScalar:
2769 if (builder.isMatrix(right))
2770 std::swap(left, right);
2771 assert(builder.isScalar(right));
2772 break;
2773 case spv::OpVectorTimesMatrix:
2774 assert(builder.isVector(left));
2775 assert(builder.isMatrix(right));
2776 break;
2777 case spv::OpMatrixTimesVector:
2778 assert(builder.isMatrix(left));
2779 assert(builder.isVector(right));
2780 break;
2781 case spv::OpMatrixTimesMatrix:
2782 assert(builder.isMatrix(left));
2783 assert(builder.isMatrix(right));
2784 break;
2785 default:
2786 firstClass = false;
2787 break;
2788 }
2789
John Kessenich32cfd492016-02-02 12:37:46 -07002790 if (firstClass)
2791 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002792
2793 // Handle component-wise +, -, *, and / for all combinations of type.
2794 // The result type of all of them is the same type as the (a) matrix operand.
2795 // The algorithm is to:
2796 // - break the matrix(es) into vectors
2797 // - smear any scalar to a vector
2798 // - do vector operations
2799 // - make a matrix out the vector results
2800 switch (op) {
2801 case spv::OpFAdd:
2802 case spv::OpFSub:
2803 case spv::OpFDiv:
2804 case spv::OpFMul:
2805 {
2806 // one time set up...
2807 bool leftMat = builder.isMatrix(left);
2808 bool rightMat = builder.isMatrix(right);
2809 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2810 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2811 spv::Id scalarType = builder.getScalarTypeId(typeId);
2812 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2813 std::vector<spv::Id> results;
2814 spv::Id smearVec = spv::NoResult;
2815 if (builder.isScalar(left))
2816 smearVec = builder.smearScalar(precision, left, vecType);
2817 else if (builder.isScalar(right))
2818 smearVec = builder.smearScalar(precision, right, vecType);
2819
2820 // do each vector op
2821 for (unsigned int c = 0; c < numCols; ++c) {
2822 std::vector<unsigned int> indexes;
2823 indexes.push_back(c);
2824 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2825 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2826 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2827 builder.setPrecision(results.back(), precision);
2828 }
2829
2830 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002831 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002832 }
2833 default:
2834 assert(0);
2835 return spv::NoResult;
2836 }
2837}
2838
Rex Xu04db3f52015-09-16 11:44:02 +08002839spv::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 -06002840{
2841 spv::Op unaryOp = spv::OpNop;
2842 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002843 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002844 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002845
2846 switch (op) {
2847 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002848 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002849 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002850 if (builder.isMatrixType(typeId))
2851 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2852 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002853 unaryOp = spv::OpSNegate;
2854 break;
2855
2856 case glslang::EOpLogicalNot:
2857 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002858 unaryOp = spv::OpLogicalNot;
2859 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002860 case glslang::EOpBitwiseNot:
2861 unaryOp = spv::OpNot;
2862 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002863
John Kessenich140f3df2015-06-26 16:58:36 -06002864 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002865 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002866 break;
2867 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002868 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002869 break;
2870 case glslang::EOpTranspose:
2871 unaryOp = spv::OpTranspose;
2872 break;
2873
2874 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002875 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002876 break;
2877 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002878 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002879 break;
2880 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002881 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002882 break;
2883 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002884 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002885 break;
2886 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002887 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002888 break;
2889 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002890 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002891 break;
2892 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002893 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002894 break;
2895 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002896 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002897 break;
2898
2899 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002900 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002901 break;
2902 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002903 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002904 break;
2905 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002906 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002907 break;
2908 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002909 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002910 break;
2911 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002912 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002913 break;
2914 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002915 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002916 break;
2917
2918 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002919 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002920 break;
2921 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002922 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002923 break;
2924
2925 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002926 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002927 break;
2928 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002929 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002930 break;
2931 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002932 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002933 break;
2934 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002935 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002936 break;
2937 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002938 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002939 break;
2940 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002941 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002942 break;
2943
2944 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002945 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002946 break;
2947 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002948 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002949 break;
2950 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002951 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002952 break;
2953 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002954 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002955 break;
2956 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002957 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002958 break;
2959 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002960 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002961 break;
2962
2963 case glslang::EOpIsNan:
2964 unaryOp = spv::OpIsNan;
2965 break;
2966 case glslang::EOpIsInf:
2967 unaryOp = spv::OpIsInf;
2968 break;
2969
Rex Xucbc426e2015-12-15 16:03:10 +08002970 case glslang::EOpFloatBitsToInt:
2971 case glslang::EOpFloatBitsToUint:
2972 case glslang::EOpIntBitsToFloat:
2973 case glslang::EOpUintBitsToFloat:
2974 unaryOp = spv::OpBitcast;
2975 break;
2976
John Kessenich140f3df2015-06-26 16:58:36 -06002977 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002978 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002979 break;
2980 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002981 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002982 break;
2983 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002984 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002985 break;
2986 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002987 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002988 break;
2989 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002990 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002991 break;
2992 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002993 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002994 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002995 case glslang::EOpPackSnorm4x8:
2996 libCall = spv::GLSLstd450PackSnorm4x8;
2997 break;
2998 case glslang::EOpUnpackSnorm4x8:
2999 libCall = spv::GLSLstd450UnpackSnorm4x8;
3000 break;
3001 case glslang::EOpPackUnorm4x8:
3002 libCall = spv::GLSLstd450PackUnorm4x8;
3003 break;
3004 case glslang::EOpUnpackUnorm4x8:
3005 libCall = spv::GLSLstd450UnpackUnorm4x8;
3006 break;
3007 case glslang::EOpPackDouble2x32:
3008 libCall = spv::GLSLstd450PackDouble2x32;
3009 break;
3010 case glslang::EOpUnpackDouble2x32:
3011 libCall = spv::GLSLstd450UnpackDouble2x32;
3012 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003013
3014 case glslang::EOpDPdx:
3015 unaryOp = spv::OpDPdx;
3016 break;
3017 case glslang::EOpDPdy:
3018 unaryOp = spv::OpDPdy;
3019 break;
3020 case glslang::EOpFwidth:
3021 unaryOp = spv::OpFwidth;
3022 break;
3023 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003024 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003025 unaryOp = spv::OpDPdxFine;
3026 break;
3027 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003028 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003029 unaryOp = spv::OpDPdyFine;
3030 break;
3031 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003032 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003033 unaryOp = spv::OpFwidthFine;
3034 break;
3035 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003036 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003037 unaryOp = spv::OpDPdxCoarse;
3038 break;
3039 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003040 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003041 unaryOp = spv::OpDPdyCoarse;
3042 break;
3043 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003044 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003045 unaryOp = spv::OpFwidthCoarse;
3046 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003047 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003048 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003049 libCall = spv::GLSLstd450InterpolateAtCentroid;
3050 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003051 case glslang::EOpAny:
3052 unaryOp = spv::OpAny;
3053 break;
3054 case glslang::EOpAll:
3055 unaryOp = spv::OpAll;
3056 break;
3057
3058 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003059 if (isFloat)
3060 libCall = spv::GLSLstd450FAbs;
3061 else
3062 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003063 break;
3064 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003065 if (isFloat)
3066 libCall = spv::GLSLstd450FSign;
3067 else
3068 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003069 break;
3070
John Kessenichfc51d282015-08-19 13:34:18 -06003071 case glslang::EOpAtomicCounterIncrement:
3072 case glslang::EOpAtomicCounterDecrement:
3073 case glslang::EOpAtomicCounter:
3074 {
3075 // Handle all of the atomics in one place, in createAtomicOperation()
3076 std::vector<spv::Id> operands;
3077 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003078 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003079 }
3080
John Kessenichfc51d282015-08-19 13:34:18 -06003081 case glslang::EOpBitFieldReverse:
3082 unaryOp = spv::OpBitReverse;
3083 break;
3084 case glslang::EOpBitCount:
3085 unaryOp = spv::OpBitCount;
3086 break;
3087 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003088 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003089 break;
3090 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003091 if (isUnsigned)
3092 libCall = spv::GLSLstd450FindUMsb;
3093 else
3094 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003095 break;
3096
John Kessenich140f3df2015-06-26 16:58:36 -06003097 default:
3098 return 0;
3099 }
3100
3101 spv::Id id;
3102 if (libCall >= 0) {
3103 std::vector<spv::Id> args;
3104 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003105 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003106 } else
3107 id = builder.createUnaryOp(unaryOp, typeId, operand);
3108
John Kessenich32cfd492016-02-02 12:37:46 -07003109 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003110}
3111
John Kessenich7a53f762016-01-20 11:19:27 -07003112// Create a unary operation on a matrix
3113spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3114{
3115 // Handle unary operations vector by vector.
3116 // The result type is the same type as the original type.
3117 // The algorithm is to:
3118 // - break the matrix into vectors
3119 // - apply the operation to each vector
3120 // - make a matrix out the vector results
3121
3122 // get the types sorted out
3123 int numCols = builder.getNumColumns(operand);
3124 int numRows = builder.getNumRows(operand);
3125 spv::Id scalarType = builder.getScalarTypeId(typeId);
3126 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3127 std::vector<spv::Id> results;
3128
3129 // do each vector op
3130 for (int c = 0; c < numCols; ++c) {
3131 std::vector<unsigned int> indexes;
3132 indexes.push_back(c);
3133 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3134 results.push_back(builder.createUnaryOp(op, vecType, vec));
3135 builder.setPrecision(results.back(), precision);
3136 }
3137
3138 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003139 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003140}
3141
John Kessenich140f3df2015-06-26 16:58:36 -06003142spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3143{
3144 spv::Op convOp = spv::OpNop;
3145 spv::Id zero = 0;
3146 spv::Id one = 0;
3147
3148 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3149
3150 switch (op) {
3151 case glslang::EOpConvIntToBool:
3152 case glslang::EOpConvUintToBool:
3153 zero = builder.makeUintConstant(0);
3154 zero = makeSmearedConstant(zero, vectorSize);
3155 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3156
3157 case glslang::EOpConvFloatToBool:
3158 zero = builder.makeFloatConstant(0.0F);
3159 zero = makeSmearedConstant(zero, vectorSize);
3160 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3161
3162 case glslang::EOpConvDoubleToBool:
3163 zero = builder.makeDoubleConstant(0.0);
3164 zero = makeSmearedConstant(zero, vectorSize);
3165 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3166
3167 case glslang::EOpConvBoolToFloat:
3168 convOp = spv::OpSelect;
3169 zero = builder.makeFloatConstant(0.0);
3170 one = builder.makeFloatConstant(1.0);
3171 break;
3172 case glslang::EOpConvBoolToDouble:
3173 convOp = spv::OpSelect;
3174 zero = builder.makeDoubleConstant(0.0);
3175 one = builder.makeDoubleConstant(1.0);
3176 break;
3177 case glslang::EOpConvBoolToInt:
3178 zero = builder.makeIntConstant(0);
3179 one = builder.makeIntConstant(1);
3180 convOp = spv::OpSelect;
3181 break;
3182 case glslang::EOpConvBoolToUint:
3183 zero = builder.makeUintConstant(0);
3184 one = builder.makeUintConstant(1);
3185 convOp = spv::OpSelect;
3186 break;
3187
3188 case glslang::EOpConvIntToFloat:
3189 case glslang::EOpConvIntToDouble:
3190 convOp = spv::OpConvertSToF;
3191 break;
3192
3193 case glslang::EOpConvUintToFloat:
3194 case glslang::EOpConvUintToDouble:
3195 convOp = spv::OpConvertUToF;
3196 break;
3197
3198 case glslang::EOpConvDoubleToFloat:
3199 case glslang::EOpConvFloatToDouble:
3200 convOp = spv::OpFConvert;
3201 break;
3202
3203 case glslang::EOpConvFloatToInt:
3204 case glslang::EOpConvDoubleToInt:
3205 convOp = spv::OpConvertFToS;
3206 break;
3207
3208 case glslang::EOpConvUintToInt:
3209 case glslang::EOpConvIntToUint:
3210 convOp = spv::OpBitcast;
3211 break;
3212
3213 case glslang::EOpConvFloatToUint:
3214 case glslang::EOpConvDoubleToUint:
3215 convOp = spv::OpConvertFToU;
3216 break;
3217 default:
3218 break;
3219 }
3220
3221 spv::Id result = 0;
3222 if (convOp == spv::OpNop)
3223 return result;
3224
3225 if (convOp == spv::OpSelect) {
3226 zero = makeSmearedConstant(zero, vectorSize);
3227 one = makeSmearedConstant(one, vectorSize);
3228 result = builder.createTriOp(convOp, destType, operand, one, zero);
3229 } else
3230 result = builder.createUnaryOp(convOp, destType, operand);
3231
John Kessenich32cfd492016-02-02 12:37:46 -07003232 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003233}
3234
3235spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3236{
3237 if (vectorSize == 0)
3238 return constant;
3239
3240 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3241 std::vector<spv::Id> components;
3242 for (int c = 0; c < vectorSize; ++c)
3243 components.push_back(constant);
3244 return builder.makeCompositeConstant(vectorTypeId, components);
3245}
3246
John Kessenich426394d2015-07-23 10:22:48 -06003247// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003248spv::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 -06003249{
3250 spv::Op opCode = spv::OpNop;
3251
3252 switch (op) {
3253 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003254 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003255 opCode = spv::OpAtomicIAdd;
3256 break;
3257 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003258 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003259 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003260 break;
3261 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003262 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003263 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003264 break;
3265 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003266 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003267 opCode = spv::OpAtomicAnd;
3268 break;
3269 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003270 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003271 opCode = spv::OpAtomicOr;
3272 break;
3273 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003274 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003275 opCode = spv::OpAtomicXor;
3276 break;
3277 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003278 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003279 opCode = spv::OpAtomicExchange;
3280 break;
3281 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003282 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003283 opCode = spv::OpAtomicCompareExchange;
3284 break;
3285 case glslang::EOpAtomicCounterIncrement:
3286 opCode = spv::OpAtomicIIncrement;
3287 break;
3288 case glslang::EOpAtomicCounterDecrement:
3289 opCode = spv::OpAtomicIDecrement;
3290 break;
3291 case glslang::EOpAtomicCounter:
3292 opCode = spv::OpAtomicLoad;
3293 break;
3294 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003295 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003296 break;
3297 }
3298
3299 // Sort out the operands
3300 // - mapping from glslang -> SPV
3301 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003302 // - compare-exchange swaps the value and comparator
3303 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003304 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3305 auto opIt = operands.begin(); // walk the glslang operands
3306 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003307 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3308 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3309 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003310 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3311 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003312 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003313 spvAtomicOperands.push_back(*(opIt + 1));
3314 spvAtomicOperands.push_back(*opIt);
3315 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003316 }
John Kessenich426394d2015-07-23 10:22:48 -06003317
John Kessenich3e60a6f2015-09-14 22:45:16 -06003318 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003319 for (; opIt != operands.end(); ++opIt)
3320 spvAtomicOperands.push_back(*opIt);
3321
3322 return builder.createOp(opCode, typeId, spvAtomicOperands);
3323}
3324
John Kessenich5e4b1242015-08-06 22:53:06 -06003325spv::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 -06003326{
John Kessenich5e4b1242015-08-06 22:53:06 -06003327 bool isUnsigned = typeProxy == glslang::EbtUint;
3328 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3329
John Kessenich140f3df2015-06-26 16:58:36 -06003330 spv::Op opCode = spv::OpNop;
3331 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003332 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003333 spv::Id typeId0 = 0;
3334 if (consumedOperands > 0)
3335 typeId0 = builder.getTypeId(operands[0]);
3336 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003337
3338 switch (op) {
3339 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003340 if (isFloat)
3341 libCall = spv::GLSLstd450FMin;
3342 else if (isUnsigned)
3343 libCall = spv::GLSLstd450UMin;
3344 else
3345 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003346 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003347 break;
3348 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003349 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003350 break;
3351 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003352 if (isFloat)
3353 libCall = spv::GLSLstd450FMax;
3354 else if (isUnsigned)
3355 libCall = spv::GLSLstd450UMax;
3356 else
3357 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003358 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003359 break;
3360 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003361 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003362 break;
3363 case glslang::EOpDot:
3364 opCode = spv::OpDot;
3365 break;
3366 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003367 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003368 break;
3369
3370 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003371 if (isFloat)
3372 libCall = spv::GLSLstd450FClamp;
3373 else if (isUnsigned)
3374 libCall = spv::GLSLstd450UClamp;
3375 else
3376 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003377 builder.promoteScalar(precision, operands.front(), operands[1]);
3378 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003379 break;
3380 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003381 if (isFloat)
3382 libCall = spv::GLSLstd450FMix;
John Kessenich6c292d32016-02-15 20:58:50 -07003383 else {
3384 opCode = spv::OpSelect;
3385 spv::MissingFunctionality("translating integer mix to OpSelect");
3386 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003387 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003388 break;
3389 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003390 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003391 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003392 break;
3393 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003394 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003395 builder.promoteScalar(precision, operands[0], operands[2]);
3396 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003397 break;
3398
3399 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003400 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003401 break;
3402 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003403 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003404 break;
3405 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003406 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003407 break;
3408 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003409 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003410 break;
3411 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003412 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003413 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003414 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003415 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003416 libCall = spv::GLSLstd450InterpolateAtSample;
3417 break;
3418 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003419 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003420 libCall = spv::GLSLstd450InterpolateAtOffset;
3421 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003422 case glslang::EOpAddCarry:
3423 opCode = spv::OpIAddCarry;
3424 typeId = builder.makeStructResultType(typeId0, typeId0);
3425 consumedOperands = 2;
3426 break;
3427 case glslang::EOpSubBorrow:
3428 opCode = spv::OpISubBorrow;
3429 typeId = builder.makeStructResultType(typeId0, typeId0);
3430 consumedOperands = 2;
3431 break;
3432 case glslang::EOpUMulExtended:
3433 opCode = spv::OpUMulExtended;
3434 typeId = builder.makeStructResultType(typeId0, typeId0);
3435 consumedOperands = 2;
3436 break;
3437 case glslang::EOpIMulExtended:
3438 opCode = spv::OpSMulExtended;
3439 typeId = builder.makeStructResultType(typeId0, typeId0);
3440 consumedOperands = 2;
3441 break;
3442 case glslang::EOpBitfieldExtract:
3443 if (isUnsigned)
3444 opCode = spv::OpBitFieldUExtract;
3445 else
3446 opCode = spv::OpBitFieldSExtract;
3447 break;
3448 case glslang::EOpBitfieldInsert:
3449 opCode = spv::OpBitFieldInsert;
3450 break;
3451
3452 case glslang::EOpFma:
3453 libCall = spv::GLSLstd450Fma;
3454 break;
3455 case glslang::EOpFrexp:
3456 libCall = spv::GLSLstd450FrexpStruct;
3457 if (builder.getNumComponents(operands[0]) == 1)
3458 frexpIntType = builder.makeIntegerType(32, true);
3459 else
3460 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3461 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3462 consumedOperands = 1;
3463 break;
3464 case glslang::EOpLdexp:
3465 libCall = spv::GLSLstd450Ldexp;
3466 break;
3467
John Kessenich140f3df2015-06-26 16:58:36 -06003468 default:
3469 return 0;
3470 }
3471
3472 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003473 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003474 // Use an extended instruction from the standard library.
3475 // Construct the call arguments, without modifying the original operands vector.
3476 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3477 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003478 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003479 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003480 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003481 case 0:
3482 // should all be handled by visitAggregate and createNoArgOperation
3483 assert(0);
3484 return 0;
3485 case 1:
3486 // should all be handled by createUnaryOperation
3487 assert(0);
3488 return 0;
3489 case 2:
3490 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3491 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003492 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003493 // anything 3 or over doesn't have l-value operands, so all should be consumed
3494 assert(consumedOperands == operands.size());
3495 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003496 break;
3497 }
3498 }
3499
John Kessenich55e7d112015-11-15 21:33:39 -07003500 // Decode the return types that were structures
3501 switch (op) {
3502 case glslang::EOpAddCarry:
3503 case glslang::EOpSubBorrow:
3504 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3505 id = builder.createCompositeExtract(id, typeId0, 0);
3506 break;
3507 case glslang::EOpUMulExtended:
3508 case glslang::EOpIMulExtended:
3509 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3510 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3511 break;
3512 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003513 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003514 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3515 id = builder.createCompositeExtract(id, typeId0, 0);
3516 break;
3517 default:
3518 break;
3519 }
3520
John Kessenich32cfd492016-02-02 12:37:46 -07003521 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003522}
3523
3524// Intrinsics with no arguments, no return value, and no precision.
3525spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3526{
3527 // TODO: get the barrier operands correct
3528
3529 switch (op) {
3530 case glslang::EOpEmitVertex:
3531 builder.createNoResultOp(spv::OpEmitVertex);
3532 return 0;
3533 case glslang::EOpEndPrimitive:
3534 builder.createNoResultOp(spv::OpEndPrimitive);
3535 return 0;
3536 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003537 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3538 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003539 return 0;
3540 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003541 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003542 return 0;
3543 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003544 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003545 return 0;
3546 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003547 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003548 return 0;
3549 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003550 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003551 return 0;
3552 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003553 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003554 return 0;
3555 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003556 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003557 return 0;
3558 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003559 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003560 return 0;
3561 }
3562}
3563
3564spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3565{
John Kessenich2f273362015-07-18 22:34:27 -06003566 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003567 spv::Id id;
3568 if (symbolValues.end() != iter) {
3569 id = iter->second;
3570 return id;
3571 }
3572
3573 // it was not found, create it
3574 id = createSpvVariable(symbol);
3575 symbolValues[symbol->getId()] = id;
3576
3577 if (! symbol->getType().isStruct()) {
3578 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003579 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003580 if (symbol->getType().getQualifier().hasSpecConstantId())
3581 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003582 if (symbol->getQualifier().hasLocation())
3583 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3584 if (symbol->getQualifier().hasIndex())
3585 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3586 if (symbol->getQualifier().hasComponent())
3587 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3588 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003589 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003590 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003591 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003592 if (symbol->getQualifier().hasXfbBuffer())
3593 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3594 if (symbol->getQualifier().hasXfbOffset())
3595 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3596 }
3597 }
3598
John Kesseniche0b6cad2015-12-24 10:30:13 -07003599 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003600 if (symbol->getQualifier().hasStream()) {
3601 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003602 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003603 }
John Kessenich140f3df2015-06-26 16:58:36 -06003604 if (symbol->getQualifier().hasSet())
3605 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003606 else if (IsDescriptorResource(symbol->getType())) {
3607 // default to 0
3608 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3609 }
John Kessenich140f3df2015-06-26 16:58:36 -06003610 if (symbol->getQualifier().hasBinding())
3611 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003612 if (symbol->getQualifier().hasAttachment())
3613 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003614 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003615 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003616 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003617 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003618 if (symbol->getQualifier().hasXfbBuffer())
3619 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3620 }
3621
3622 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003623 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003624 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003625 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003626
John Kessenich140f3df2015-06-26 16:58:36 -06003627 return id;
3628}
3629
John Kessenich55e7d112015-11-15 21:33:39 -07003630// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003631void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3632{
3633 if (dec != spv::BadValue)
3634 builder.addDecoration(id, dec);
3635}
3636
John Kessenich55e7d112015-11-15 21:33:39 -07003637// If 'dec' is valid, add a one-operand decoration to an object
3638void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3639{
3640 if (dec != spv::BadValue)
3641 builder.addDecoration(id, dec, value);
3642}
3643
3644// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003645void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3646{
3647 if (dec != spv::BadValue)
3648 builder.addMemberDecoration(id, (unsigned)member, dec);
3649}
3650
John Kessenich92187592016-02-01 13:45:25 -07003651// If 'dec' is valid, add a one-operand decoration to a struct member
3652void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3653{
3654 if (dec != spv::BadValue)
3655 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3656}
3657
John Kessenich55e7d112015-11-15 21:33:39 -07003658// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003659// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003660//
3661// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3662//
3663// Recursively walk the nodes. The nodes form a tree whose leaves are
3664// regular constants, which themselves are trees that createSpvConstant()
3665// recursively walks. So, this function walks the "top" of the tree:
3666// - emit specialization constant-building instructions for specConstant
3667// - when running into a non-spec-constant, switch to createSpvConstant()
3668spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3669{
3670 assert(node.getQualifier().storage == glslang::EvqConst);
3671
John Kessenich6c292d32016-02-15 20:58:50 -07003672 if (! node.getQualifier().specConstant) {
3673 // hand off to the non-spec-constant path
3674 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3675 int nextConst = 0;
3676 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3677 nextConst, false);
3678 }
3679
3680 // We now know we have a specialization constant to build
3681
3682 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3683 // this is a direct literal assigned to a layout(constant_id=) declaration
3684 int nextConst = 0;
3685 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3686 nextConst, true);
3687 } else {
3688 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3689 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3690 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3691 std::vector<spv::Id> dimConstId;
3692 for (int dim = 0; dim < 3; ++dim) {
3693 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3694 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3695 if (specConst)
3696 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3697 }
3698 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3699 } else {
3700 spv::MissingFunctionality("specialization-constant expression trees");
3701 return spv::NoResult;
3702 }
3703 }
John Kessenich55e7d112015-11-15 21:33:39 -07003704}
3705
John Kessenich140f3df2015-06-26 16:58:36 -06003706// Use 'consts' as the flattened glslang source of scalar constants to recursively
3707// build the aggregate SPIR-V constant.
3708//
3709// If there are not enough elements present in 'consts', 0 will be substituted;
3710// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3711//
John Kessenich55e7d112015-11-15 21:33:39 -07003712spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003713{
3714 // vector of constants for SPIR-V
3715 std::vector<spv::Id> spvConsts;
3716
3717 // Type is used for struct and array constants
3718 spv::Id typeId = convertGlslangToSpvType(glslangType);
3719
3720 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003721 glslang::TType elementType(glslangType, 0);
3722 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003723 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003724 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003725 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003726 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003727 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003728 } else if (glslangType.getStruct()) {
3729 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3730 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003731 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003732 } else if (glslangType.isVector()) {
3733 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3734 bool zero = nextConst >= consts.size();
3735 switch (glslangType.getBasicType()) {
3736 case glslang::EbtInt:
3737 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3738 break;
3739 case glslang::EbtUint:
3740 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3741 break;
3742 case glslang::EbtFloat:
3743 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3744 break;
3745 case glslang::EbtDouble:
3746 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3747 break;
3748 case glslang::EbtBool:
3749 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3750 break;
3751 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003752 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003753 break;
3754 }
3755 ++nextConst;
3756 }
3757 } else {
3758 // we have a non-aggregate (scalar) constant
3759 bool zero = nextConst >= consts.size();
3760 spv::Id scalar = 0;
3761 switch (glslangType.getBasicType()) {
3762 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003763 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003764 break;
3765 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003766 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003767 break;
3768 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003769 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003770 break;
3771 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003772 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003773 break;
3774 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003775 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003776 break;
3777 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003778 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003779 break;
3780 }
3781 ++nextConst;
3782 return scalar;
3783 }
3784
3785 return builder.makeCompositeConstant(typeId, spvConsts);
3786}
3787
John Kessenich7c1aa102015-10-15 13:29:11 -06003788// Return true if the node is a constant or symbol whose reading has no
3789// non-trivial observable cost or effect.
3790bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3791{
3792 // don't know what this is
3793 if (node == nullptr)
3794 return false;
3795
3796 // a constant is safe
3797 if (node->getAsConstantUnion() != nullptr)
3798 return true;
3799
3800 // not a symbol means non-trivial
3801 if (node->getAsSymbolNode() == nullptr)
3802 return false;
3803
3804 // a symbol, depends on what's being read
3805 switch (node->getType().getQualifier().storage) {
3806 case glslang::EvqTemporary:
3807 case glslang::EvqGlobal:
3808 case glslang::EvqIn:
3809 case glslang::EvqInOut:
3810 case glslang::EvqConst:
3811 case glslang::EvqConstReadOnly:
3812 case glslang::EvqUniform:
3813 return true;
3814 default:
3815 return false;
3816 }
3817}
3818
3819// A node is trivial if it is a single operation with no side effects.
3820// Error on the side of saying non-trivial.
3821// Return true if trivial.
3822bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3823{
3824 if (node == nullptr)
3825 return false;
3826
3827 // symbols and constants are trivial
3828 if (isTrivialLeaf(node))
3829 return true;
3830
3831 // otherwise, it needs to be a simple operation or one or two leaf nodes
3832
3833 // not a simple operation
3834 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3835 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3836 if (binaryNode == nullptr && unaryNode == nullptr)
3837 return false;
3838
3839 // not on leaf nodes
3840 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3841 return false;
3842
3843 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3844 return false;
3845 }
3846
3847 switch (node->getAsOperator()->getOp()) {
3848 case glslang::EOpLogicalNot:
3849 case glslang::EOpConvIntToBool:
3850 case glslang::EOpConvUintToBool:
3851 case glslang::EOpConvFloatToBool:
3852 case glslang::EOpConvDoubleToBool:
3853 case glslang::EOpEqual:
3854 case glslang::EOpNotEqual:
3855 case glslang::EOpLessThan:
3856 case glslang::EOpGreaterThan:
3857 case glslang::EOpLessThanEqual:
3858 case glslang::EOpGreaterThanEqual:
3859 case glslang::EOpIndexDirect:
3860 case glslang::EOpIndexDirectStruct:
3861 case glslang::EOpLogicalXor:
3862 case glslang::EOpAny:
3863 case glslang::EOpAll:
3864 return true;
3865 default:
3866 return false;
3867 }
3868}
3869
3870// Emit short-circuiting code, where 'right' is never evaluated unless
3871// the left side is true (for &&) or false (for ||).
3872spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3873{
3874 spv::Id boolTypeId = builder.makeBoolType();
3875
3876 // emit left operand
3877 builder.clearAccessChain();
3878 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003879 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003880
3881 // Operands to accumulate OpPhi operands
3882 std::vector<spv::Id> phiOperands;
3883 // accumulate left operand's phi information
3884 phiOperands.push_back(leftId);
3885 phiOperands.push_back(builder.getBuildPoint()->getId());
3886
3887 // Make the two kinds of operation symmetric with a "!"
3888 // || => emit "if (! left) result = right"
3889 // && => emit "if ( left) result = right"
3890 //
3891 // TODO: this runtime "not" for || could be avoided by adding functionality
3892 // to 'builder' to have an "else" without an "then"
3893 if (op == glslang::EOpLogicalOr)
3894 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3895
3896 // make an "if" based on the left value
3897 spv::Builder::If ifBuilder(leftId, builder);
3898
3899 // emit right operand as the "then" part of the "if"
3900 builder.clearAccessChain();
3901 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003902 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003903
3904 // accumulate left operand's phi information
3905 phiOperands.push_back(rightId);
3906 phiOperands.push_back(builder.getBuildPoint()->getId());
3907
3908 // finish the "if"
3909 ifBuilder.makeEndIf();
3910
3911 // phi together the two results
3912 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3913}
3914
John Kessenich140f3df2015-06-26 16:58:36 -06003915}; // end anonymous namespace
3916
3917namespace glslang {
3918
John Kessenich68d78fd2015-07-12 19:28:10 -06003919void GetSpirvVersion(std::string& version)
3920{
John Kessenich9e55f632015-07-15 10:03:39 -06003921 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003922 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003923 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003924 version = buf;
3925}
3926
John Kessenich140f3df2015-06-26 16:58:36 -06003927// Write SPIR-V out to a binary file
3928void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3929{
3930 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003931 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003932 for (int i = 0; i < (int)spirv.size(); ++i) {
3933 unsigned int word = spirv[i];
3934 out.write((const char*)&word, 4);
3935 }
3936 out.close();
3937}
3938
3939//
3940// Set up the glslang traversal
3941//
3942void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3943{
3944 TIntermNode* root = intermediate.getTreeRoot();
3945
3946 if (root == 0)
3947 return;
3948
3949 glslang::GetThreadPoolAllocator().push();
3950
3951 TGlslangToSpvTraverser it(&intermediate);
3952
3953 root->traverse(&it);
3954
3955 it.dumpSpv(spirv);
3956
3957 glslang::GetThreadPoolAllocator().pop();
3958}
3959
3960}; // end namespace glslang