blob: 864902ccb14f16ac1a3ef5481aa03060e6cc31c5 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich6c292d32016-02-15 20:58:50 -07002//Copyright (C) 2014-2015 LunarG, Inc.
3//Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
5//All rights reserved.
6//
7//Redistribution and use in source and binary forms, with or without
8//modification, are permitted provided that the following conditions
9//are met:
10//
11// Redistributions of source code must retain the above copyright
12// notice, this list of conditions and the following disclaimer.
13//
14// Redistributions in binary form must reproduce the above
15// copyright notice, this list of conditions and the following
16// disclaimer in the documentation and/or other materials provided
17// with the distribution.
18//
19// Neither the name of 3Dlabs Inc. Ltd. nor the names of its
20// contributors may be used to endorse or promote products derived
21// from this software without specific prior written permission.
22//
23//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24//"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25//LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
26//FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
27//COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
28//INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29//BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30//LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31//CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32//LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
33//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34//POSSIBILITY OF SUCH DAMAGE.
35
36//
37// Author: John Kessenich, LunarG
38//
39// Visit the nodes in the glslang intermediate tree representation to
40// translate them to SPIR-V.
41//
42
John Kessenich5e4b1242015-08-06 22:53:06 -060043#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060044#include "GlslangToSpv.h"
45#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060046namespace spv {
47 #include "GLSL.std.450.h"
48}
John Kessenich140f3df2015-06-26 16:58:36 -060049
50// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020051#include "../glslang/MachineIndependent/localintermediate.h"
52#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060053#include "../glslang/Include/Common.h"
John Kessenich140f3df2015-06-26 16:58:36 -060054
55#include <string>
56#include <map>
57#include <list>
58#include <vector>
59#include <stack>
60#include <fstream>
61
62namespace {
63
John Kessenich55e7d112015-11-15 21:33:39 -070064// For low-order part of the generator's magic number. Bump up
65// when there is a change in the style (e.g., if SSA form changes,
66// or a different instruction sequence to do something gets used).
67const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060068
69//
70// The main holder of information for translating glslang to SPIR-V.
71//
72// Derives from the AST walking base class.
73//
74class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
75public:
76 TGlslangToSpvTraverser(const glslang::TIntermediate*);
77 virtual ~TGlslangToSpvTraverser();
78
79 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
80 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
81 void visitConstantUnion(glslang::TIntermConstantUnion*);
82 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
83 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
84 void visitSymbol(glslang::TIntermSymbol* symbol);
85 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
86 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
87 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
88
John Kessenich7ba63412015-12-20 17:37:07 -070089 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -060090
91protected:
John Kessenich5e801132016-02-15 11:09:46 -070092 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
John Kessenich92187592016-02-01 13:45:25 -070093 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable);
John Kessenich5d0fa972016-02-15 11:57:00 -070094 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
John Kessenich140f3df2015-06-26 16:58:36 -060095 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
96 spv::Id getSampledType(const glslang::TSampler&);
97 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -070098 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich6c292d32016-02-15 20:58:50 -070099 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700100 spv::Id accessChainLoad(const glslang::TType& type);
John Kessenichf85e8062015-12-19 13:57:10 -0700101 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700102 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
103 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
104 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
John Kessenich140f3df2015-06-26 16:58:36 -0600105
106 bool isShaderEntrypoint(const glslang::TIntermAggregate* node);
107 void makeFunctions(const glslang::TIntermSequence&);
108 void makeGlobalInitializers(const glslang::TIntermSequence&);
109 void visitFunctions(const glslang::TIntermSequence&);
110 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800111 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600112 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
113 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600114 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
115
116 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
John Kessenich04bb8a02015-12-12 12:28:14 -0700117 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right);
Rex Xu04db3f52015-09-16 11:44:02 +0800118 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -0700119 spv::Id createUnaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600120 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destTypeId, spv::Id operand);
121 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800122 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich5e4b1242015-08-06 22:53:06 -0600123 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600124 spv::Id createNoArgOperation(glslang::TOperator op);
125 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
126 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700127 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600128 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700129 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
John Kessenich55e7d112015-11-15 21:33:39 -0700130 spv::Id createSpvSpecConstant(const glslang::TIntermTyped&);
131 spv::Id createSpvConstant(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600132 bool isTrivialLeaf(const glslang::TIntermTyped* node);
133 bool isTrivial(const glslang::TIntermTyped* node);
134 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
John Kessenich140f3df2015-06-26 16:58:36 -0600135
136 spv::Function* shaderEntry;
John Kessenich55e7d112015-11-15 21:33:39 -0700137 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600138 int sequenceDepth;
139
140 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
141 spv::Builder builder;
142 bool inMain;
143 bool mainTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700144 bool linkageOnly; // true when visiting the set of objects in the AST present only for establishing interface, whether or not they were statically used
John Kessenich59420fd2015-12-21 11:45:34 -0700145 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600146 const glslang::TIntermediate* glslangIntermediate;
147 spv::Id stdBuiltins;
148
John Kessenich2f273362015-07-18 22:34:27 -0600149 std::unordered_map<int, spv::Id> symbolValues;
150 std::unordered_set<int> constReadOnlyParameters; // set of formal function parameters that have glslang qualifier constReadOnly, so we know they are not local function "const" that are write-once
151 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700152 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600153 std::unordered_map<const glslang::TTypeList*, std::vector<int> > memberRemapper; // for mapping glslang block indices to spv indices (e.g., due to hidden members)
John Kessenich140f3df2015-06-26 16:58:36 -0600154 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600155};
156
157//
158// Helper functions for translating glslang representations to SPIR-V enumerants.
159//
160
161// Translate glslang profile to SPIR-V source language.
162spv::SourceLanguage TranslateSourceLanguage(EProfile profile)
163{
164 switch (profile) {
165 case ENoProfile:
166 case ECoreProfile:
167 case ECompatibilityProfile:
168 return spv::SourceLanguageGLSL;
169 case EEsProfile:
170 return spv::SourceLanguageESSL;
171 default:
172 return spv::SourceLanguageUnknown;
173 }
174}
175
176// Translate glslang language (stage) to SPIR-V execution model.
177spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
178{
179 switch (stage) {
180 case EShLangVertex: return spv::ExecutionModelVertex;
181 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
182 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
183 case EShLangGeometry: return spv::ExecutionModelGeometry;
184 case EShLangFragment: return spv::ExecutionModelFragment;
185 case EShLangCompute: return spv::ExecutionModelGLCompute;
186 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700187 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600188 return spv::ExecutionModelFragment;
189 }
190}
191
192// Translate glslang type to SPIR-V storage class.
193spv::StorageClass TranslateStorageClass(const glslang::TType& type)
194{
195 if (type.getQualifier().isPipeInput())
196 return spv::StorageClassInput;
197 else if (type.getQualifier().isPipeOutput())
198 return spv::StorageClassOutput;
199 else if (type.getQualifier().isUniformOrBuffer()) {
John Kessenich6c292d32016-02-15 20:58:50 -0700200 if (type.getQualifier().layoutPushConstant)
201 return spv::StorageClassPushConstant;
John Kessenich140f3df2015-06-26 16:58:36 -0600202 if (type.getBasicType() == glslang::EbtBlock)
203 return spv::StorageClassUniform;
Rex Xufc618912015-09-09 16:42:49 +0800204 else if (type.getBasicType() == glslang::EbtAtomicUint)
205 return spv::StorageClassAtomicCounter;
John Kessenich140f3df2015-06-26 16:58:36 -0600206 else
207 return spv::StorageClassUniformConstant;
208 // TODO: how are we distuingishing between default and non-default non-writable uniforms? Do default uniforms even exist?
209 } else {
210 switch (type.getQualifier().storage) {
John Kessenich55e7d112015-11-15 21:33:39 -0700211 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
212 case glslang::EvqGlobal: return spv::StorageClassPrivate;
John Kessenich140f3df2015-06-26 16:58:36 -0600213 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
214 case glslang::EvqTemporary: return spv::StorageClassFunction;
215 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700216 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600217 return spv::StorageClassFunction;
218 }
219 }
220}
221
222// Translate glslang sampler type to SPIR-V dimensionality.
223spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
224{
225 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700226 case glslang::Esd1D: return spv::Dim1D;
227 case glslang::Esd2D: return spv::Dim2D;
228 case glslang::Esd3D: return spv::Dim3D;
229 case glslang::EsdCube: return spv::DimCube;
230 case glslang::EsdRect: return spv::DimRect;
231 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700232 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600233 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700234 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600235 return spv::Dim2D;
236 }
237}
238
239// Translate glslang type to SPIR-V precision decorations.
240spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
241{
242 switch (type.getQualifier().precision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700243 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600244 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600245 default:
246 return spv::NoPrecision;
247 }
248}
249
250// Translate glslang type to SPIR-V block decorations.
251spv::Decoration TranslateBlockDecoration(const glslang::TType& type)
252{
253 if (type.getBasicType() == glslang::EbtBlock) {
254 switch (type.getQualifier().storage) {
255 case glslang::EvqUniform: return spv::DecorationBlock;
256 case glslang::EvqBuffer: return spv::DecorationBufferBlock;
257 case glslang::EvqVaryingIn: return spv::DecorationBlock;
258 case glslang::EvqVaryingOut: return spv::DecorationBlock;
259 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700260 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600261 break;
262 }
263 }
264
265 return (spv::Decoration)spv::BadValue;
266}
267
268// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700269spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600270{
271 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700272 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600273 case glslang::ElmRowMajor:
274 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700275 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600276 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700277 default:
278 // opaque layouts don't need a majorness
279 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600280 }
281 } else {
282 switch (type.getBasicType()) {
283 default:
284 return (spv::Decoration)spv::BadValue;
285 break;
286 case glslang::EbtBlock:
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform:
289 case glslang::EvqBuffer:
290 switch (type.getQualifier().layoutPacking) {
291 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
293 default:
John Kessenich5e4b1242015-08-06 22:53:06 -0600294 return (spv::Decoration)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600295 }
296 case glslang::EvqVaryingIn:
297 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700298 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich140f3df2015-06-26 16:58:36 -0600299 return (spv::Decoration)spv::BadValue;
300 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700301 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600302 return (spv::Decoration)spv::BadValue;
303 }
304 }
305 }
306}
307
308// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich55e7d112015-11-15 21:33:39 -0700309// Returns spv::Decoration(spv::BadValue) when no decoration
310// should be applied.
John Kessenich5e801132016-02-15 11:09:46 -0700311spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600312{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700313 if (qualifier.smooth) {
John Kessenich55e7d112015-11-15 21:33:39 -0700314 // Smooth decoration doesn't exist in SPIR-V 1.0
315 return (spv::Decoration)spv::BadValue;
316 }
John Kesseniche0b6cad2015-12-24 10:30:13 -0700317 if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700318 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700319 else if (qualifier.patch)
John Kessenich140f3df2015-06-26 16:58:36 -0600320 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700321 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600322 return spv::DecorationFlat;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700323 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700325 else if (qualifier.sample) {
326 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600327 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700328 } else
John Kessenich140f3df2015-06-26 16:58:36 -0600329 return (spv::Decoration)spv::BadValue;
330}
331
John Kessenich92187592016-02-01 13:45:25 -0700332// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700333spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600334{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700335 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600336 return spv::DecorationInvariant;
337 else
338 return (spv::Decoration)spv::BadValue;
339}
340
341// Translate glslang built-in variable to SPIR-V built in decoration.
John Kessenich92187592016-02-01 13:45:25 -0700342spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn)
John Kessenich140f3df2015-06-26 16:58:36 -0600343{
344 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700345 case glslang::EbvPointSize:
346 switch (glslangIntermediate->getStage()) {
347 case EShLangGeometry:
348 builder.addCapability(spv::CapabilityGeometryPointSize);
349 break;
350 case EShLangTessControl:
351 case EShLangTessEvaluation:
352 builder.addCapability(spv::CapabilityTessellationPointSize);
353 break;
354 }
355 return spv::BuiltInPointSize;
356
357 case glslang::EbvClipDistance:
358 builder.addCapability(spv::CapabilityClipDistance);
359 return spv::BuiltInClipDistance;
360
361 case glslang::EbvCullDistance:
362 builder.addCapability(spv::CapabilityCullDistance);
363 return spv::BuiltInCullDistance;
364
365 case glslang::EbvViewportIndex:
366 // TODO: builder.addCapability(spv::CapabilityMultiViewport);
367 return spv::BuiltInViewportIndex;
368
John Kessenich5e801132016-02-15 11:09:46 -0700369 case glslang::EbvSampleId:
370 builder.addCapability(spv::CapabilitySampleRateShading);
371 return spv::BuiltInSampleId;
372
373 case glslang::EbvSamplePosition:
374 builder.addCapability(spv::CapabilitySampleRateShading);
375 return spv::BuiltInSamplePosition;
376
377 case glslang::EbvSampleMask:
378 builder.addCapability(spv::CapabilitySampleRateShading);
379 return spv::BuiltInSampleMask;
380
John Kessenich140f3df2015-06-26 16:58:36 -0600381 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600382 case glslang::EbvVertexId: return spv::BuiltInVertexId;
383 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700384 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
385 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
John Kessenichda581a22015-10-14 14:10:30 -0600386 case glslang::EbvBaseVertex:
387 case glslang::EbvBaseInstance:
388 case glslang::EbvDrawId:
389 // TODO: Add SPIR-V builtin ID.
390 spv::MissingFunctionality("Draw parameters");
391 return (spv::BuiltIn)spv::BadValue;
John Kessenich140f3df2015-06-26 16:58:36 -0600392 case glslang::EbvPrimitiveId: return spv::BuiltInPrimitiveId;
393 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
394 case glslang::EbvLayer: return spv::BuiltInLayer;
John Kessenich140f3df2015-06-26 16:58:36 -0600395 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
396 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
397 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
398 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
399 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
400 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
401 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600402 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
403 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
404 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
405 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
406 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
407 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
408 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
409 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
410 default: return (spv::BuiltIn)spv::BadValue;
411 }
412}
413
Rex Xufc618912015-09-09 16:42:49 +0800414// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700415spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800416{
417 assert(type.getBasicType() == glslang::EbtSampler);
418
John Kessenich5d0fa972016-02-15 11:57:00 -0700419 // Check for capabilities
420 switch (type.getQualifier().layoutFormat) {
421 case glslang::ElfRg32f:
422 case glslang::ElfRg16f:
423 case glslang::ElfR11fG11fB10f:
424 case glslang::ElfR16f:
425 case glslang::ElfRgba16:
426 case glslang::ElfRgb10A2:
427 case glslang::ElfRg16:
428 case glslang::ElfRg8:
429 case glslang::ElfR16:
430 case glslang::ElfR8:
431 case glslang::ElfRgba16Snorm:
432 case glslang::ElfRg16Snorm:
433 case glslang::ElfRg8Snorm:
434 case glslang::ElfR16Snorm:
435 case glslang::ElfR8Snorm:
436
437 case glslang::ElfRg32i:
438 case glslang::ElfRg16i:
439 case glslang::ElfRg8i:
440 case glslang::ElfR16i:
441 case glslang::ElfR8i:
442
443 case glslang::ElfRgb10a2ui:
444 case glslang::ElfRg32ui:
445 case glslang::ElfRg16ui:
446 case glslang::ElfRg8ui:
447 case glslang::ElfR16ui:
448 case glslang::ElfR8ui:
449 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
450 break;
451
452 default:
453 break;
454 }
455
456 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800457 switch (type.getQualifier().layoutFormat) {
458 case glslang::ElfNone: return spv::ImageFormatUnknown;
459 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
460 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
461 case glslang::ElfR32f: return spv::ImageFormatR32f;
462 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
463 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
464 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
465 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
466 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
467 case glslang::ElfR16f: return spv::ImageFormatR16f;
468 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
469 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
470 case glslang::ElfRg16: return spv::ImageFormatRg16;
471 case glslang::ElfRg8: return spv::ImageFormatRg8;
472 case glslang::ElfR16: return spv::ImageFormatR16;
473 case glslang::ElfR8: return spv::ImageFormatR8;
474 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
475 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
476 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
477 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
478 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
479 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
480 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
481 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
482 case glslang::ElfR32i: return spv::ImageFormatR32i;
483 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
484 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
485 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
486 case glslang::ElfR16i: return spv::ImageFormatR16i;
487 case glslang::ElfR8i: return spv::ImageFormatR8i;
488 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
489 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
490 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
491 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
492 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
493 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
494 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
495 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
496 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
497 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
498 default: return (spv::ImageFormat)spv::BadValue;
499 }
500}
501
John Kessenich6c292d32016-02-15 20:58:50 -0700502// Return whether or not the given type is something that should be tied to a
503// descriptor set.
504bool IsDescriptorResource(const glslang::TType& type)
505{
506 // uniform and buffer blocks are included
507 if (type.getBasicType() == glslang::EbtBlock)
508 return type.getQualifier().isUniformOrBuffer();
509
510 // non block...
511 // basically samplerXXX/subpass/sampler/texture are all included
512 // if they are the global-scope-class, not the function parameter
513 // (or local, if they ever exist) class.
514 if (type.getBasicType() == glslang::EbtSampler)
515 return type.getQualifier().isUniformOrBuffer();
516
517 // None of the above.
518 return false;
519}
520
John Kesseniche0b6cad2015-12-24 10:30:13 -0700521void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
522{
523 if (child.layoutMatrix == glslang::ElmNone)
524 child.layoutMatrix = parent.layoutMatrix;
525
526 if (parent.invariant)
527 child.invariant = true;
528 if (parent.nopersp)
529 child.nopersp = true;
530 if (parent.flat)
531 child.flat = true;
532 if (parent.centroid)
533 child.centroid = true;
534 if (parent.patch)
535 child.patch = true;
536 if (parent.sample)
537 child.sample = true;
John Kessenich7b9fa252016-01-21 18:56:57 -0700538
539 child.layoutLocation = parent.layoutLocation;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700540}
541
542bool HasNonLayoutQualifiers(const glslang::TQualifier& qualifier)
543{
John Kessenich7b9fa252016-01-21 18:56:57 -0700544 // This should list qualifiers that simultaneous satisfy:
John Kesseniche0b6cad2015-12-24 10:30:13 -0700545 // - struct members can inherit from a struct declaration
546 // - effect decorations on the struct members (note smooth does not, and expecting something like volatile to effect the whole object)
547 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenich7b9fa252016-01-21 18:56:57 -0700548 return qualifier.invariant || qualifier.nopersp || qualifier.flat || qualifier.centroid || qualifier.patch || qualifier.sample || qualifier.hasLocation();
John Kesseniche0b6cad2015-12-24 10:30:13 -0700549}
550
John Kessenich140f3df2015-06-26 16:58:36 -0600551//
552// Implement the TGlslangToSpvTraverser class.
553//
554
555TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate)
556 : TIntermTraverser(true, false, true), shaderEntry(0), sequenceDepth(0),
John Kessenich55e7d112015-11-15 21:33:39 -0700557 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion),
John Kessenich140f3df2015-06-26 16:58:36 -0600558 inMain(false), mainTerminated(false), linkageOnly(false),
559 glslangIntermediate(glslangIntermediate)
560{
561 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
562
563 builder.clearAccessChain();
564 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
565 stdBuiltins = builder.import("GLSL.std.450");
566 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
567 shaderEntry = builder.makeMain();
John Kessenich55e7d112015-11-15 21:33:39 -0700568 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, "main");
John Kessenich140f3df2015-06-26 16:58:36 -0600569
570 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600571 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
572 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600573 builder.addSourceExtension(it->c_str());
574
575 // Add the top-level modes for this shader.
576
John Kessenich92187592016-02-01 13:45:25 -0700577 if (glslangIntermediate->getXfbMode()) {
578 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600579 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700580 }
John Kessenich140f3df2015-06-26 16:58:36 -0600581
582 unsigned int mode;
583 switch (glslangIntermediate->getStage()) {
584 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600585 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600586 break;
587
588 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600589 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600590 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
591 break;
592
593 case EShLangTessEvaluation:
John Kessenich5e4b1242015-08-06 22:53:06 -0600594 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600595 switch (glslangIntermediate->getInputPrimitive()) {
John Kessenich55e7d112015-11-15 21:33:39 -0700596 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
597 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
598 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kesseniche6903322015-10-13 16:29:02 -0600599 default: mode = spv::BadValue; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600600 }
601 if (mode != spv::BadValue)
602 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
603
John Kesseniche6903322015-10-13 16:29:02 -0600604 switch (glslangIntermediate->getVertexSpacing()) {
605 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
606 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
607 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
608 default: mode = spv::BadValue; break;
609 }
610 if (mode != spv::BadValue)
611 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
612
613 switch (glslangIntermediate->getVertexOrder()) {
614 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
615 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
616 default: mode = spv::BadValue; break;
617 }
618 if (mode != spv::BadValue)
619 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
620
621 if (glslangIntermediate->getPointMode())
622 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600623 break;
624
625 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600626 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600627 switch (glslangIntermediate->getInputPrimitive()) {
628 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
629 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
630 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700631 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600632 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
633 default: mode = spv::BadValue; break;
634 }
635 if (mode != spv::BadValue)
636 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600637
John Kessenich140f3df2015-06-26 16:58:36 -0600638 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
639
640 switch (glslangIntermediate->getOutputPrimitive()) {
641 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
642 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
643 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
644 default: mode = spv::BadValue; break;
645 }
646 if (mode != spv::BadValue)
647 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
648 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
649 break;
650
651 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600652 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600653 if (glslangIntermediate->getPixelCenterInteger())
654 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600655
John Kessenich140f3df2015-06-26 16:58:36 -0600656 if (glslangIntermediate->getOriginUpperLeft())
657 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600658 else
659 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600660
661 if (glslangIntermediate->getEarlyFragmentTests())
662 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
663
664 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600665 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
666 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
667 default: mode = spv::BadValue; break;
668 }
669 if (mode != spv::BadValue)
670 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
671
672 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
673 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600674 break;
675
676 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600677 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600678 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
679 glslangIntermediate->getLocalSize(1),
680 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600681 break;
682
683 default:
684 break;
685 }
686
687}
688
John Kessenich7ba63412015-12-20 17:37:07 -0700689// Finish everything and dump
690void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
691{
692 // finish off the entry-point SPV instruction by adding the Input/Output <id>
693 for (auto it : iOSet)
694 entryPoint->addIdOperand(it);
695
696 builder.dump(out);
697}
698
John Kessenich140f3df2015-06-26 16:58:36 -0600699TGlslangToSpvTraverser::~TGlslangToSpvTraverser()
700{
701 if (! mainTerminated) {
702 spv::Block* lastMainBlock = shaderEntry->getLastBlock();
703 builder.setBuildPoint(lastMainBlock);
John Kesseniche770b3e2015-09-14 20:58:02 -0600704 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -0600705 }
706}
707
708//
709// Implement the traversal functions.
710//
711// Return true from interior nodes to have the external traversal
712// continue on to children. Return false if children were
713// already processed.
714//
715
716//
717// Symbols can turn into
718// - uniform/input reads
719// - output writes
720// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
721// - something simple that degenerates into the last bullet
722//
723void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
724{
725 // getSymbolId() will set up all the IO decorations on the first call.
726 // Formal function parameters were mapped during makeFunctions().
727 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -0700728
729 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
730 if (builder.isPointer(id)) {
731 spv::StorageClass sc = builder.getStorageClass(id);
732 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
733 iOSet.insert(id);
734 }
735
736 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -0700737 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -0600738 // Prepare to generate code for the access
739
740 // L-value chains will be computed left to right. We're on the symbol now,
741 // which is the left-most part of the access chain, so now is "clear" time,
742 // followed by setting the base.
743 builder.clearAccessChain();
744
745 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -0700746 // except for
747 // A) "const in" arguments to a function, which are an intermediate object.
748 // See comments in handleUserFunctionCall().
749 // B) Specialization constants (normal constant don't even come in as a variable),
750 // These are also pure R-values.
751 glslang::TQualifier qualifier = symbol->getQualifier();
752 if ((qualifier.storage == glslang::EvqConstReadOnly && constReadOnlyParameters.find(symbol->getId()) != constReadOnlyParameters.end()) ||
753 qualifier.isSpecConstant())
John Kessenich140f3df2015-06-26 16:58:36 -0600754 builder.setAccessChainRValue(id);
755 else
756 builder.setAccessChainLValue(id);
757 }
758}
759
760bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
761{
762 // First, handle special cases
763 switch (node->getOp()) {
764 case glslang::EOpAssign:
765 case glslang::EOpAddAssign:
766 case glslang::EOpSubAssign:
767 case glslang::EOpMulAssign:
768 case glslang::EOpVectorTimesMatrixAssign:
769 case glslang::EOpVectorTimesScalarAssign:
770 case glslang::EOpMatrixTimesScalarAssign:
771 case glslang::EOpMatrixTimesMatrixAssign:
772 case glslang::EOpDivAssign:
773 case glslang::EOpModAssign:
774 case glslang::EOpAndAssign:
775 case glslang::EOpInclusiveOrAssign:
776 case glslang::EOpExclusiveOrAssign:
777 case glslang::EOpLeftShiftAssign:
778 case glslang::EOpRightShiftAssign:
779 // A bin-op assign "a += b" means the same thing as "a = a + b"
780 // where a is evaluated before b. For a simple assignment, GLSL
781 // says to evaluate the left before the right. So, always, left
782 // node then right node.
783 {
784 // get the left l-value, save it away
785 builder.clearAccessChain();
786 node->getLeft()->traverse(this);
787 spv::Builder::AccessChain lValue = builder.getAccessChain();
788
789 // evaluate the right
790 builder.clearAccessChain();
791 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700792 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600793
794 if (node->getOp() != glslang::EOpAssign) {
795 // the left is also an r-value
796 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -0700797 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600798
799 // do the operation
800 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
801 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
802 node->getType().getBasicType());
803
804 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -0700805 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -0600806 }
807
808 // store the result
809 builder.setAccessChain(lValue);
810 builder.accessChainStore(rValue);
811
812 // assignments are expressions having an rValue after they are evaluated...
813 builder.clearAccessChain();
814 builder.setAccessChainRValue(rValue);
815 }
816 return false;
817 case glslang::EOpIndexDirect:
818 case glslang::EOpIndexDirectStruct:
819 {
820 // Get the left part of the access chain.
821 node->getLeft()->traverse(this);
822
823 // Add the next element in the chain
824
John Kessenich55e7d112015-11-15 21:33:39 -0700825 int index = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -0600826 if (node->getLeft()->getBasicType() == glslang::EbtBlock && node->getOp() == glslang::EOpIndexDirectStruct) {
827 // This may be, e.g., an anonymous block-member selection, which generally need
828 // index remapping due to hidden members in anonymous blocks.
829 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
John Kessenich55e7d112015-11-15 21:33:39 -0700830 assert(remapper.size() > 0);
831 index = remapper[index];
John Kessenich140f3df2015-06-26 16:58:36 -0600832 }
833
834 if (! node->getLeft()->getType().isArray() &&
835 node->getLeft()->getType().isVector() &&
836 node->getOp() == glslang::EOpIndexDirect) {
837 // This is essentially a hard-coded vector swizzle of size 1,
838 // so short circuit the access-chain stuff with a swizzle.
839 std::vector<unsigned> swizzle;
840 swizzle.push_back(node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600841 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600842 } else {
843 // normal case for indexing array or structure or block
John Kessenichfa668da2015-09-13 14:46:30 -0600844 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich140f3df2015-06-26 16:58:36 -0600845 }
846 }
847 return false;
848 case glslang::EOpIndexIndirect:
849 {
850 // Structure or array or vector indirection.
851 // Will use native SPIR-V access-chain for struct and array indirection;
852 // matrices are arrays of vectors, so will also work for a matrix.
853 // Will use the access chain's 'component' for variable index into a vector.
854
855 // This adapter is building access chains left to right.
856 // Set up the access chain to the left.
857 node->getLeft()->traverse(this);
858
859 // save it so that computing the right side doesn't trash it
860 spv::Builder::AccessChain partial = builder.getAccessChain();
861
862 // compute the next index in the chain
863 builder.clearAccessChain();
864 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700865 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600866
867 // restore the saved access chain
868 builder.setAccessChain(partial);
869
870 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -0600871 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600872 else
John Kessenichfa668da2015-09-13 14:46:30 -0600873 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -0600874 }
875 return false;
876 case glslang::EOpVectorSwizzle:
877 {
878 node->getLeft()->traverse(this);
879 glslang::TIntermSequence& swizzleSequence = node->getRight()->getAsAggregate()->getSequence();
880 std::vector<unsigned> swizzle;
881 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
882 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
John Kessenichfa668da2015-09-13 14:46:30 -0600883 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -0600884 }
885 return false;
John Kessenich7c1aa102015-10-15 13:29:11 -0600886 case glslang::EOpLogicalOr:
887 case glslang::EOpLogicalAnd:
888 {
889
890 // These may require short circuiting, but can sometimes be done as straight
891 // binary operations. The right operand must be short circuited if it has
892 // side effects, and should probably be if it is complex.
893 if (isTrivial(node->getRight()->getAsTyped()))
894 break; // handle below as a normal binary operation
895 // otherwise, we need to do dynamic short circuiting on the right operand
896 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
897 builder.clearAccessChain();
898 builder.setAccessChainRValue(result);
899 }
900 return false;
John Kessenich140f3df2015-06-26 16:58:36 -0600901 default:
902 break;
903 }
904
905 // Assume generic binary op...
906
John Kessenich32cfd492016-02-02 12:37:46 -0700907 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -0600908 builder.clearAccessChain();
909 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700910 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600911
John Kessenich32cfd492016-02-02 12:37:46 -0700912 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -0600913 builder.clearAccessChain();
914 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -0700915 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600916
John Kessenich32cfd492016-02-02 12:37:46 -0700917 // get result
918 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getType()),
919 convertGlslangToSpvType(node->getType()), left, right,
920 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600921
John Kessenich50e57562015-12-21 21:21:11 -0700922 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -0600923 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -0700924 spv::MissingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -0700925 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -0600926 } else {
John Kessenich140f3df2015-06-26 16:58:36 -0600927 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -0600928 return false;
929 }
John Kessenich140f3df2015-06-26 16:58:36 -0600930}
931
932bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
933{
John Kessenichfc51d282015-08-19 13:34:18 -0600934 spv::Id result = spv::NoResult;
935
936 // try texturing first
937 result = createImageTextureFunctionCall(node);
938 if (result != spv::NoResult) {
939 builder.clearAccessChain();
940 builder.setAccessChainRValue(result);
941
942 return false; // done with this node
943 }
944
945 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -0600946
947 if (node->getOp() == glslang::EOpArrayLength) {
948 // Quite special; won't want to evaluate the operand.
949
950 // Normal .length() would have been constant folded by the front-end.
951 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -0600952 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -0600953 assert(node->getOperand()->getType().isRuntimeSizedArray());
954 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
955 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -0600956 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
957 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -0600958
959 builder.clearAccessChain();
960 builder.setAccessChainRValue(length);
961
962 return false;
963 }
964
John Kessenichfc51d282015-08-19 13:34:18 -0600965 // Start by evaluating the operand
966
John Kessenich140f3df2015-06-26 16:58:36 -0600967 builder.clearAccessChain();
968 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +0800969
Rex Xufc618912015-09-09 16:42:49 +0800970 spv::Id operand = spv::NoResult;
971
972 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
973 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +0800974 node->getOp() == glslang::EOpAtomicCounter ||
975 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +0800976 operand = builder.accessChainGetLValue(); // Special case l-value operands
977 else
John Kessenich32cfd492016-02-02 12:37:46 -0700978 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -0600979
980 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
981
982 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -0600983 if (! result)
984 result = createConversion(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand);
John Kessenich140f3df2015-06-26 16:58:36 -0600985
986 // if not, then possibly an operation
987 if (! result)
John Kessenich55e7d112015-11-15 21:33:39 -0700988 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -0600989
990 if (result) {
991 builder.clearAccessChain();
992 builder.setAccessChainRValue(result);
993
994 return false; // done with this node
995 }
996
997 // it must be a special case, check...
998 switch (node->getOp()) {
999 case glslang::EOpPostIncrement:
1000 case glslang::EOpPostDecrement:
1001 case glslang::EOpPreIncrement:
1002 case glslang::EOpPreDecrement:
1003 {
1004 // we need the integer value "1" or the floating point "1.0" to add/subtract
1005 spv::Id one = node->getBasicType() == glslang::EbtFloat ?
1006 builder.makeFloatConstant(1.0F) :
1007 builder.makeIntConstant(1);
1008 glslang::TOperator op;
1009 if (node->getOp() == glslang::EOpPreIncrement ||
1010 node->getOp() == glslang::EOpPostIncrement)
1011 op = glslang::EOpAdd;
1012 else
1013 op = glslang::EOpSub;
1014
1015 spv::Id result = createBinaryOperation(op, TranslatePrecisionDecoration(node->getType()),
1016 convertGlslangToSpvType(node->getType()), operand, one,
1017 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001018 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001019
1020 // The result of operation is always stored, but conditionally the
1021 // consumed result. The consumed result is always an r-value.
1022 builder.accessChainStore(result);
1023 builder.clearAccessChain();
1024 if (node->getOp() == glslang::EOpPreIncrement ||
1025 node->getOp() == glslang::EOpPreDecrement)
1026 builder.setAccessChainRValue(result);
1027 else
1028 builder.setAccessChainRValue(operand);
1029 }
1030
1031 return false;
1032
1033 case glslang::EOpEmitStreamVertex:
1034 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1035 return false;
1036 case glslang::EOpEndStreamPrimitive:
1037 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1038 return false;
1039
1040 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001041 spv::MissingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001042 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001043 }
John Kessenich140f3df2015-06-26 16:58:36 -06001044}
1045
1046bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1047{
John Kessenichfc51d282015-08-19 13:34:18 -06001048 spv::Id result = spv::NoResult;
1049
1050 // try texturing
1051 result = createImageTextureFunctionCall(node);
1052 if (result != spv::NoResult) {
1053 builder.clearAccessChain();
1054 builder.setAccessChainRValue(result);
1055
1056 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001057 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001058 // "imageStore" is a special case, which has no result
1059 return false;
1060 }
John Kessenichfc51d282015-08-19 13:34:18 -06001061
John Kessenich140f3df2015-06-26 16:58:36 -06001062 glslang::TOperator binOp = glslang::EOpNull;
1063 bool reduceComparison = true;
1064 bool isMatrix = false;
1065 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001066 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001067
1068 assert(node->getOp());
1069
1070 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
1071
1072 switch (node->getOp()) {
1073 case glslang::EOpSequence:
1074 {
1075 if (preVisit)
1076 ++sequenceDepth;
1077 else
1078 --sequenceDepth;
1079
1080 if (sequenceDepth == 1) {
1081 // If this is the parent node of all the functions, we want to see them
1082 // early, so all call points have actual SPIR-V functions to reference.
1083 // In all cases, still let the traverser visit the children for us.
1084 makeFunctions(node->getAsAggregate()->getSequence());
1085
1086 // Also, we want all globals initializers to go into the entry of main(), before
1087 // anything else gets there, so visit out of order, doing them all now.
1088 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1089
1090 // Initializers are done, don't want to visit again, but functions link objects need to be processed,
1091 // so do them manually.
1092 visitFunctions(node->getAsAggregate()->getSequence());
1093
1094 return false;
1095 }
1096
1097 return true;
1098 }
1099 case glslang::EOpLinkerObjects:
1100 {
1101 if (visit == glslang::EvPreVisit)
1102 linkageOnly = true;
1103 else
1104 linkageOnly = false;
1105
1106 return true;
1107 }
1108 case glslang::EOpComma:
1109 {
1110 // processing from left to right naturally leaves the right-most
1111 // lying around in the access chain
1112 glslang::TIntermSequence& glslangOperands = node->getSequence();
1113 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1114 glslangOperands[i]->traverse(this);
1115
1116 return false;
1117 }
1118 case glslang::EOpFunction:
1119 if (visit == glslang::EvPreVisit) {
1120 if (isShaderEntrypoint(node)) {
1121 inMain = true;
1122 builder.setBuildPoint(shaderEntry->getLastBlock());
1123 } else {
1124 handleFunctionEntry(node);
1125 }
1126 } else {
1127 if (inMain)
1128 mainTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001129 builder.leaveFunction();
John Kessenich140f3df2015-06-26 16:58:36 -06001130 inMain = false;
1131 }
1132
1133 return true;
1134 case glslang::EOpParameters:
1135 // Parameters will have been consumed by EOpFunction processing, but not
1136 // the body, so we still visited the function node's children, making this
1137 // child redundant.
1138 return false;
1139 case glslang::EOpFunctionCall:
1140 {
1141 if (node->isUserDefined())
1142 result = handleUserFunctionCall(node);
John Kessenich6c292d32016-02-15 20:58:50 -07001143 //assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
1144 if (result) {
1145 builder.clearAccessChain();
1146 builder.setAccessChainRValue(result);
1147 } else
1148 spv::MissingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001149
1150 return false;
1151 }
1152 case glslang::EOpConstructMat2x2:
1153 case glslang::EOpConstructMat2x3:
1154 case glslang::EOpConstructMat2x4:
1155 case glslang::EOpConstructMat3x2:
1156 case glslang::EOpConstructMat3x3:
1157 case glslang::EOpConstructMat3x4:
1158 case glslang::EOpConstructMat4x2:
1159 case glslang::EOpConstructMat4x3:
1160 case glslang::EOpConstructMat4x4:
1161 case glslang::EOpConstructDMat2x2:
1162 case glslang::EOpConstructDMat2x3:
1163 case glslang::EOpConstructDMat2x4:
1164 case glslang::EOpConstructDMat3x2:
1165 case glslang::EOpConstructDMat3x3:
1166 case glslang::EOpConstructDMat3x4:
1167 case glslang::EOpConstructDMat4x2:
1168 case glslang::EOpConstructDMat4x3:
1169 case glslang::EOpConstructDMat4x4:
1170 isMatrix = true;
1171 // fall through
1172 case glslang::EOpConstructFloat:
1173 case glslang::EOpConstructVec2:
1174 case glslang::EOpConstructVec3:
1175 case glslang::EOpConstructVec4:
1176 case glslang::EOpConstructDouble:
1177 case glslang::EOpConstructDVec2:
1178 case glslang::EOpConstructDVec3:
1179 case glslang::EOpConstructDVec4:
1180 case glslang::EOpConstructBool:
1181 case glslang::EOpConstructBVec2:
1182 case glslang::EOpConstructBVec3:
1183 case glslang::EOpConstructBVec4:
1184 case glslang::EOpConstructInt:
1185 case glslang::EOpConstructIVec2:
1186 case glslang::EOpConstructIVec3:
1187 case glslang::EOpConstructIVec4:
1188 case glslang::EOpConstructUint:
1189 case glslang::EOpConstructUVec2:
1190 case glslang::EOpConstructUVec3:
1191 case glslang::EOpConstructUVec4:
1192 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001193 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001194 {
1195 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001196 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 spv::Id resultTypeId = convertGlslangToSpvType(node->getType());
1198 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001199 if (node->getOp() == glslang::EOpConstructTextureSampler)
1200 constructed = builder.createOp(spv::OpSampledImage, resultTypeId, arguments);
1201 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001202 std::vector<spv::Id> constituents;
1203 for (int c = 0; c < (int)arguments.size(); ++c)
1204 constituents.push_back(arguments[c]);
1205 constructed = builder.createCompositeConstruct(resultTypeId, constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001206 } else if (isMatrix)
1207 constructed = builder.createMatrixConstructor(precision, arguments, resultTypeId);
1208 else
1209 constructed = builder.createConstructor(precision, arguments, resultTypeId);
John Kessenich140f3df2015-06-26 16:58:36 -06001210
1211 builder.clearAccessChain();
1212 builder.setAccessChainRValue(constructed);
1213
1214 return false;
1215 }
1216
1217 // These six are component-wise compares with component-wise results.
1218 // Forward on to createBinaryOperation(), requesting a vector result.
1219 case glslang::EOpLessThan:
1220 case glslang::EOpGreaterThan:
1221 case glslang::EOpLessThanEqual:
1222 case glslang::EOpGreaterThanEqual:
1223 case glslang::EOpVectorEqual:
1224 case glslang::EOpVectorNotEqual:
1225 {
1226 // Map the operation to a binary
1227 binOp = node->getOp();
1228 reduceComparison = false;
1229 switch (node->getOp()) {
1230 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1231 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1232 default: binOp = node->getOp(); break;
1233 }
1234
1235 break;
1236 }
1237 case glslang::EOpMul:
1238 // compontent-wise matrix multiply
1239 binOp = glslang::EOpMul;
1240 break;
1241 case glslang::EOpOuterProduct:
1242 // two vectors multiplied to make a matrix
1243 binOp = glslang::EOpOuterProduct;
1244 break;
1245 case glslang::EOpDot:
1246 {
1247 // for scalar dot product, use multiply
1248 glslang::TIntermSequence& glslangOperands = node->getSequence();
1249 if (! glslangOperands[0]->getAsTyped()->isVector())
1250 binOp = glslang::EOpMul;
1251 break;
1252 }
1253 case glslang::EOpMod:
1254 // when an aggregate, this is the floating-point mod built-in function,
1255 // which can be emitted by the one in createBinaryOperation()
1256 binOp = glslang::EOpMod;
1257 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001258 case glslang::EOpEmitVertex:
1259 case glslang::EOpEndPrimitive:
1260 case glslang::EOpBarrier:
1261 case glslang::EOpMemoryBarrier:
1262 case glslang::EOpMemoryBarrierAtomicCounter:
1263 case glslang::EOpMemoryBarrierBuffer:
1264 case glslang::EOpMemoryBarrierImage:
1265 case glslang::EOpMemoryBarrierShared:
1266 case glslang::EOpGroupMemoryBarrier:
1267 noReturnValue = true;
1268 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1269 break;
1270
John Kessenich426394d2015-07-23 10:22:48 -06001271 case glslang::EOpAtomicAdd:
1272 case glslang::EOpAtomicMin:
1273 case glslang::EOpAtomicMax:
1274 case glslang::EOpAtomicAnd:
1275 case glslang::EOpAtomicOr:
1276 case glslang::EOpAtomicXor:
1277 case glslang::EOpAtomicExchange:
1278 case glslang::EOpAtomicCompSwap:
1279 atomic = true;
1280 break;
1281
John Kessenich140f3df2015-06-26 16:58:36 -06001282 default:
1283 break;
1284 }
1285
1286 //
1287 // See if it maps to a regular operation.
1288 //
John Kessenich140f3df2015-06-26 16:58:36 -06001289 if (binOp != glslang::EOpNull) {
1290 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1291 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1292 assert(left && right);
1293
1294 builder.clearAccessChain();
1295 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001296 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001297
1298 builder.clearAccessChain();
1299 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001300 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001301
1302 result = createBinaryOperation(binOp, precision,
1303 convertGlslangToSpvType(node->getType()), leftId, rightId,
1304 left->getType().getBasicType(), reduceComparison);
1305
1306 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001307 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001308 builder.clearAccessChain();
1309 builder.setAccessChainRValue(result);
1310
1311 return false;
1312 }
1313
John Kessenich426394d2015-07-23 10:22:48 -06001314 //
1315 // Create the list of operands.
1316 //
John Kessenich140f3df2015-06-26 16:58:36 -06001317 glslang::TIntermSequence& glslangOperands = node->getSequence();
1318 std::vector<spv::Id> operands;
1319 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
1320 builder.clearAccessChain();
1321 glslangOperands[arg]->traverse(this);
1322
1323 // special case l-value operands; there are just a few
1324 bool lvalue = false;
1325 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001326 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001327 case glslang::EOpModf:
1328 if (arg == 1)
1329 lvalue = true;
1330 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001331 case glslang::EOpInterpolateAtSample:
1332 case glslang::EOpInterpolateAtOffset:
1333 if (arg == 0)
1334 lvalue = true;
1335 break;
Rex Xud4782c12015-09-06 16:30:11 +08001336 case glslang::EOpAtomicAdd:
1337 case glslang::EOpAtomicMin:
1338 case glslang::EOpAtomicMax:
1339 case glslang::EOpAtomicAnd:
1340 case glslang::EOpAtomicOr:
1341 case glslang::EOpAtomicXor:
1342 case glslang::EOpAtomicExchange:
1343 case glslang::EOpAtomicCompSwap:
1344 if (arg == 0)
1345 lvalue = true;
1346 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001347 case glslang::EOpAddCarry:
1348 case glslang::EOpSubBorrow:
1349 if (arg == 2)
1350 lvalue = true;
1351 break;
1352 case glslang::EOpUMulExtended:
1353 case glslang::EOpIMulExtended:
1354 if (arg >= 2)
1355 lvalue = true;
1356 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001357 default:
1358 break;
1359 }
1360 if (lvalue)
1361 operands.push_back(builder.accessChainGetLValue());
1362 else
John Kessenich32cfd492016-02-02 12:37:46 -07001363 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001364 }
John Kessenich426394d2015-07-23 10:22:48 -06001365
1366 if (atomic) {
1367 // Handle all atomics
Rex Xu04db3f52015-09-16 11:44:02 +08001368 result = createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001369 } else {
1370 // Pass through to generic operations.
1371 switch (glslangOperands.size()) {
1372 case 0:
1373 result = createNoArgOperation(node->getOp());
1374 break;
1375 case 1:
John Kessenich55e7d112015-11-15 21:33:39 -07001376 result = createUnaryOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands.front(), glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001377 break;
1378 default:
John Kessenich5e4b1242015-08-06 22:53:06 -06001379 result = createMiscOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001380 break;
1381 }
John Kessenich140f3df2015-06-26 16:58:36 -06001382 }
1383
1384 if (noReturnValue)
1385 return false;
1386
1387 if (! result) {
John Kessenich55e7d112015-11-15 21:33:39 -07001388 spv::MissingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001389 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001390 } else {
1391 builder.clearAccessChain();
1392 builder.setAccessChainRValue(result);
1393 return false;
1394 }
1395}
1396
1397bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1398{
1399 // This path handles both if-then-else and ?:
1400 // The if-then-else has a node type of void, while
1401 // ?: has a non-void node type
1402 spv::Id result = 0;
1403 if (node->getBasicType() != glslang::EbtVoid) {
1404 // don't handle this as just on-the-fly temporaries, because there will be two names
1405 // and better to leave SSA to later passes
1406 result = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1407 }
1408
1409 // emit the condition before doing anything with selection
1410 node->getCondition()->traverse(this);
1411
1412 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001413 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001414
1415 if (node->getTrueBlock()) {
1416 // emit the "then" statement
1417 node->getTrueBlock()->traverse(this);
1418 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001419 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001420 }
1421
1422 if (node->getFalseBlock()) {
1423 ifBuilder.makeBeginElse();
1424 // emit the "else" statement
1425 node->getFalseBlock()->traverse(this);
1426 if (result)
John Kessenich32cfd492016-02-02 12:37:46 -07001427 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001428 }
1429
1430 ifBuilder.makeEndIf();
1431
1432 if (result) {
1433 // GLSL only has r-values as the result of a :?, but
1434 // if we have an l-value, that can be more efficient if it will
1435 // become the base of a complex r-value expression, because the
1436 // next layer copies r-values into memory to use the access-chain mechanism
1437 builder.clearAccessChain();
1438 builder.setAccessChainLValue(result);
1439 }
1440
1441 return false;
1442}
1443
1444bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1445{
1446 // emit and get the condition before doing anything with switch
1447 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001448 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001449
1450 // browse the children to sort out code segments
1451 int defaultSegment = -1;
1452 std::vector<TIntermNode*> codeSegments;
1453 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1454 std::vector<int> caseValues;
1455 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1456 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1457 TIntermNode* child = *c;
1458 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001459 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001460 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001461 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001462 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1463 } else
1464 codeSegments.push_back(child);
1465 }
1466
1467 // handle the case where the last code segment is missing, due to no code
1468 // statements between the last case and the end of the switch statement
1469 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1470 (int)codeSegments.size() == defaultSegment)
1471 codeSegments.push_back(nullptr);
1472
1473 // make the switch statement
1474 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001475 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001476
1477 // emit all the code in the segments
1478 breakForLoop.push(false);
1479 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1480 builder.nextSwitchSegment(segmentBlocks, s);
1481 if (codeSegments[s])
1482 codeSegments[s]->traverse(this);
1483 else
1484 builder.addSwitchBreak();
1485 }
1486 breakForLoop.pop();
1487
1488 builder.endSwitch(segmentBlocks);
1489
1490 return false;
1491}
1492
1493void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1494{
1495 int nextConst = 0;
John Kessenich55e7d112015-11-15 21:33:39 -07001496 spv::Id constant = createSpvConstant(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001497
1498 builder.clearAccessChain();
1499 builder.setAccessChainRValue(constant);
1500}
1501
1502bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1503{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001504 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001505 builder.createBranch(&blocks.head);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001506 // Spec requires back edges to target header blocks, and every header block
1507 // must dominate its merge block. Make a header block first to ensure these
1508 // conditions are met. By definition, it will contain OpLoopMerge, followed
1509 // by a block-ending branch. But we don't want to put any other body/test
1510 // instructions in it, since the body/test may have arbitrary instructions,
1511 // including merges of its own.
1512 builder.setBuildPoint(&blocks.head);
1513 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, spv::LoopControlMaskNone);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001514 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001515 spv::Block& test = builder.makeNewBlock();
1516 builder.createBranch(&test);
1517
1518 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001519 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001520 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001521 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001522 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
1523
1524 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001525 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001526 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001527 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001528 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001529 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001530
1531 builder.setBuildPoint(&blocks.continue_target);
1532 if (node->getTerminal())
1533 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001534 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04001535 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001536 builder.createBranch(&blocks.body);
1537
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001538 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001539 builder.setBuildPoint(&blocks.body);
1540 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05001541 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001542 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001543 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001544
1545 builder.setBuildPoint(&blocks.continue_target);
1546 if (node->getTerminal())
1547 node->getTerminal()->traverse(this);
1548 if (node->getTest()) {
1549 node->getTest()->traverse(this);
1550 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001551 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001552 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001553 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05001554 // TODO: unless there was a break/return/discard instruction
1555 // somewhere in the body, this is an infinite loop, so we should
1556 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001557 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001558 }
John Kessenich140f3df2015-06-26 16:58:36 -06001559 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001560 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05001561 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06001562 return false;
1563}
1564
1565bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
1566{
1567 if (node->getExpression())
1568 node->getExpression()->traverse(this);
1569
1570 switch (node->getFlowOp()) {
1571 case glslang::EOpKill:
1572 builder.makeDiscard();
1573 break;
1574 case glslang::EOpBreak:
1575 if (breakForLoop.top())
1576 builder.createLoopExit();
1577 else
1578 builder.addSwitchBreak();
1579 break;
1580 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06001581 builder.createLoopContinue();
1582 break;
1583 case glslang::EOpReturn:
John Kesseniche770b3e2015-09-14 20:58:02 -06001584 if (node->getExpression())
John Kessenich32cfd492016-02-02 12:37:46 -07001585 builder.makeReturn(false, accessChainLoad(node->getExpression()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001586 else
John Kesseniche770b3e2015-09-14 20:58:02 -06001587 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06001588
1589 builder.clearAccessChain();
1590 break;
1591
1592 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001593 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001594 break;
1595 }
1596
1597 return false;
1598}
1599
1600spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
1601{
1602 // First, steer off constants, which are not SPIR-V variables, but
1603 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07001604 // This includes specialization constants.
John Kessenich140f3df2015-06-26 16:58:36 -06001605 if (node->getQualifier().storage == glslang::EvqConst) {
John Kessenich55e7d112015-11-15 21:33:39 -07001606 return createSpvSpecConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06001607 }
1608
1609 // Now, handle actual variables
1610 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
1611 spv::Id spvType = convertGlslangToSpvType(node->getType());
1612
1613 const char* name = node->getName().c_str();
1614 if (glslang::IsAnonymous(name))
1615 name = "";
1616
1617 return builder.createVariable(storageClass, spvType, name);
1618}
1619
1620// Return type Id of the sampled type.
1621spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
1622{
1623 switch (sampler.type) {
1624 case glslang::EbtFloat: return builder.makeFloatType(32);
1625 case glslang::EbtInt: return builder.makeIntType(32);
1626 case glslang::EbtUint: return builder.makeUintType(32);
1627 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001628 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001629 return builder.makeFloatType(32);
1630 }
1631}
1632
John Kessenich3ac051e2015-12-20 11:29:16 -07001633// Convert from a glslang type to an SPV type, by calling into a
1634// recursive version of this function. This establishes the inherited
1635// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06001636spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
1637{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001638 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06001639}
1640
1641// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07001642// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kesseniche0b6cad2015-12-24 10:30:13 -07001643spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06001644{
John Kesseniche0b6cad2015-12-24 10:30:13 -07001645 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06001646
1647 switch (type.getBasicType()) {
1648 case glslang::EbtVoid:
1649 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07001650 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06001651 break;
1652 case glslang::EbtFloat:
1653 spvType = builder.makeFloatType(32);
1654 break;
1655 case glslang::EbtDouble:
1656 spvType = builder.makeFloatType(64);
1657 break;
1658 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07001659 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
1660 // a 32-bit int where non-0 means true.
1661 if (explicitLayout != glslang::ElpNone)
1662 spvType = builder.makeUintType(32);
1663 else
1664 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06001665 break;
1666 case glslang::EbtInt:
1667 spvType = builder.makeIntType(32);
1668 break;
1669 case glslang::EbtUint:
1670 spvType = builder.makeUintType(32);
1671 break;
John Kessenich426394d2015-07-23 10:22:48 -06001672 case glslang::EbtAtomicUint:
1673 spv::TbdFunctionality("Is atomic_uint an opaque handle in the uniform storage class, or an addresses in the atomic storage class?");
1674 spvType = builder.makeUintType(32);
1675 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001676 case glslang::EbtSampler:
1677 {
1678 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07001679 if (sampler.sampler) {
1680 // pure sampler
1681 spvType = builder.makeSamplerType();
1682 } else {
1683 // an image is present, make its type
1684 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
1685 sampler.image ? 2 : 1, TranslateImageFormat(type));
1686 if (sampler.combined) {
1687 // already has both image and sampler, make the combined type
1688 spvType = builder.makeSampledImageType(spvType);
1689 }
John Kessenich55e7d112015-11-15 21:33:39 -07001690 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001691 }
John Kessenich140f3df2015-06-26 16:58:36 -06001692 break;
1693 case glslang::EbtStruct:
1694 case glslang::EbtBlock:
1695 {
1696 // If we've seen this struct type, return it
1697 const glslang::TTypeList* glslangStruct = type.getStruct();
1698 std::vector<spv::Id> structFields;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001699
1700 // Try to share structs for different layouts, but not yet for other
1701 // kinds of qualification (primarily not yet including interpolant qualification).
1702 if (! HasNonLayoutQualifiers(qualifier))
1703 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct];
1704 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06001705 break;
1706
1707 // else, we haven't seen it...
1708
1709 // Create a vector of struct types for SPIR-V to consume
1710 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
1711 if (type.getBasicType() == glslang::EbtBlock)
1712 memberRemapper[glslangStruct].resize(glslangStruct->size());
John Kessenich7b9fa252016-01-21 18:56:57 -07001713 int locationOffset = 0; // for use across struct members, when they are called recursively
John Kessenich140f3df2015-06-26 16:58:36 -06001714 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1715 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1716 if (glslangType.hiddenMember()) {
1717 ++memberDelta;
1718 if (type.getBasicType() == glslang::EbtBlock)
1719 memberRemapper[glslangStruct][i] = -1;
1720 } else {
1721 if (type.getBasicType() == glslang::EbtBlock)
1722 memberRemapper[glslangStruct][i] = i - memberDelta;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001723 // modify just this child's view of the qualifier
1724 glslang::TQualifier subQualifier = glslangType.getQualifier();
1725 InheritQualifiers(subQualifier, qualifier);
John Kessenich7b9fa252016-01-21 18:56:57 -07001726 if (qualifier.hasLocation()) {
1727 subQualifier.layoutLocation += locationOffset;
1728 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1729 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07001730 structFields.push_back(convertGlslangToSpvType(glslangType, explicitLayout, subQualifier));
John Kessenich140f3df2015-06-26 16:58:36 -06001731 }
1732 }
1733
1734 // Make the SPIR-V type
1735 spvType = builder.makeStructType(structFields, type.getTypeName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001736 if (! HasNonLayoutQualifiers(qualifier))
1737 structMap[explicitLayout][qualifier.layoutMatrix][glslangStruct] = spvType;
John Kessenich140f3df2015-06-26 16:58:36 -06001738
1739 // Name and decorate the non-hidden members
John Kessenich5e4b1242015-08-06 22:53:06 -06001740 int offset = -1;
John Kessenich7b9fa252016-01-21 18:56:57 -07001741 locationOffset = 0; // for use within the members of this struct, right now
John Kessenich140f3df2015-06-26 16:58:36 -06001742 for (int i = 0; i < (int)glslangStruct->size(); i++) {
1743 glslang::TType& glslangType = *(*glslangStruct)[i].type;
1744 int member = i;
1745 if (type.getBasicType() == glslang::EbtBlock)
1746 member = memberRemapper[glslangStruct][i];
John Kessenich3ac051e2015-12-20 11:29:16 -07001747
John Kesseniche0b6cad2015-12-24 10:30:13 -07001748 // modify just this child's view of the qualifier
1749 glslang::TQualifier subQualifier = glslangType.getQualifier();
1750 InheritQualifiers(subQualifier, qualifier);
John Kessenich3ac051e2015-12-20 11:29:16 -07001751
John Kessenich140f3df2015-06-26 16:58:36 -06001752 // using -1 above to indicate a hidden member
1753 if (member >= 0) {
1754 builder.addMemberName(spvType, member, glslangType.getFieldName().c_str());
John Kesseniche0b6cad2015-12-24 10:30:13 -07001755 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangType, subQualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001756 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangType));
John Kesseniche0b6cad2015-12-24 10:30:13 -07001757 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(subQualifier));
1758 addMemberDecoration(spvType, member, TranslateInvariantDecoration(subQualifier));
John Kessenich7b9fa252016-01-21 18:56:57 -07001759 if (qualifier.hasLocation()) {
1760 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, qualifier.layoutLocation + locationOffset);
1761 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangType);
1762 }
John Kessenich140f3df2015-06-26 16:58:36 -06001763 if (glslangType.getQualifier().hasComponent())
1764 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangType.getQualifier().layoutComponent);
1765 if (glslangType.getQualifier().hasXfbOffset())
1766 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangType.getQualifier().layoutXfbOffset);
John Kessenichf85e8062015-12-19 13:57:10 -07001767 else if (explicitLayout != glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001768 // figure out what to do with offset, which is accumulating
1769 int nextOffset;
John Kesseniche0b6cad2015-12-24 10:30:13 -07001770 updateMemberOffset(type, glslangType, offset, nextOffset, explicitLayout, subQualifier.layoutMatrix);
John Kessenich5e4b1242015-08-06 22:53:06 -06001771 if (offset >= 0)
John Kessenicha06bd522015-09-11 15:15:23 -06001772 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
John Kessenich5e4b1242015-08-06 22:53:06 -06001773 offset = nextOffset;
1774 }
John Kessenich140f3df2015-06-26 16:58:36 -06001775
John Kessenichf85e8062015-12-19 13:57:10 -07001776 if (glslangType.isMatrix() && explicitLayout != glslang::ElpNone)
John Kesseniche0b6cad2015-12-24 10:30:13 -07001777 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangType, explicitLayout, subQualifier.layoutMatrix));
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001778
John Kessenich140f3df2015-06-26 16:58:36 -06001779 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06001780 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangType.getQualifier().builtIn);
1781 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07001782 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06001783 }
1784 }
1785
1786 // Decorate the structure
John Kesseniche0b6cad2015-12-24 10:30:13 -07001787 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich140f3df2015-06-26 16:58:36 -06001788 addDecoration(spvType, TranslateBlockDecoration(type));
John Kessenich92187592016-02-01 13:45:25 -07001789 if (type.getQualifier().hasStream()) {
1790 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06001791 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07001792 }
John Kessenich140f3df2015-06-26 16:58:36 -06001793 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07001794 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06001795 if (type.getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06001796 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06001797 if (type.getQualifier().hasXfbBuffer())
1798 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
1799 }
1800 }
1801 break;
1802 default:
John Kessenich55e7d112015-11-15 21:33:39 -07001803 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06001804 break;
1805 }
1806
1807 if (type.isMatrix())
1808 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
1809 else {
1810 // If this variable has a vector element count greater than 1, create a SPIR-V vector
1811 if (type.getVectorSize() > 1)
1812 spvType = builder.makeVectorType(spvType, type.getVectorSize());
1813 }
1814
1815 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001816 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
1817
John Kessenichc9a80832015-09-12 12:17:44 -06001818 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07001819 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07001820 // We need to decorate array strides for types needing explicit layout, except blocks.
1821 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07001822 // Use a dummy glslang type for querying internal strides of
1823 // arrays of arrays, but using just a one-dimensional array.
1824 glslang::TType simpleArrayType(type, 0); // deference type of the array
1825 while (simpleArrayType.getArraySizes().getNumDims() > 1)
1826 simpleArrayType.getArraySizes().dereference();
1827
1828 // Will compute the higher-order strides here, rather than making a whole
1829 // pile of types and doing repetitive recursion on their contents.
1830 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
1831 }
John Kessenichf8842e52016-01-04 19:22:56 -07001832
1833 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07001834 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07001835 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07001836 if (stride > 0)
1837 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07001838 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07001839 }
1840 } else {
1841 // single-dimensional array, and don't yet have stride
1842
John Kessenichf8842e52016-01-04 19:22:56 -07001843 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07001844 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
1845 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06001846 }
John Kessenich31ed4832015-09-09 17:51:38 -06001847
John Kessenichc9a80832015-09-12 12:17:44 -06001848 // Do the outer dimension, which might not be known for a runtime-sized array
1849 if (type.isRuntimeSizedArray()) {
1850 spvType = builder.makeRuntimeArray(spvType);
1851 } else {
1852 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07001853 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06001854 }
John Kessenichc9e0a422015-12-29 21:27:24 -07001855 if (stride > 0)
1856 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06001857 }
1858
1859 return spvType;
1860}
1861
John Kessenich6c292d32016-02-15 20:58:50 -07001862// Turn the expression forming the array size into an id.
1863// This is not quite trivial, because of specialization constants.
1864// Sometimes, a raw constant is turned into an Id, and sometimes
1865// a specialization constant expression is.
1866spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
1867{
1868 // First, see if this is sized with a node, meaning a specialization constant:
1869 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
1870 if (specNode != nullptr) {
1871 builder.clearAccessChain();
1872 specNode->traverse(this);
1873 return accessChainLoad(specNode->getAsTyped()->getType());
1874 }
1875
1876 // Otherwise, need a compile-time (front end) size, get it:
1877 int size = arraySizes.getDimSize(dim);
1878 assert(size > 0);
1879 return builder.makeUintConstant(size);
1880}
1881
John Kessenich103bef92016-02-08 21:38:15 -07001882// Wrap the builder's accessChainLoad to:
1883// - localize handling of RelaxedPrecision
1884// - use the SPIR-V inferred type instead of another conversion of the glslang type
1885// (avoids unnecessary work and possible type punning for structures)
1886// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07001887spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
1888{
John Kessenich103bef92016-02-08 21:38:15 -07001889 spv::Id nominalTypeId = builder.accessChainGetInferredType();
1890 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
1891
1892 // Need to convert to abstract types when necessary
1893 if (builder.isScalarType(nominalTypeId) && type.getBasicType() == glslang::EbtBool && nominalTypeId != builder.makeBoolType())
1894 loadedId = builder.createBinOp(spv::OpINotEqual, builder.makeBoolType(), loadedId, builder.makeUintConstant(0));
1895
1896 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07001897}
1898
John Kessenichf85e8062015-12-19 13:57:10 -07001899// Decide whether or not this type should be
1900// decorated with offsets and strides, and if so
1901// whether std140 or std430 rules should be applied.
1902glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06001903{
John Kessenichf85e8062015-12-19 13:57:10 -07001904 // has to be a block
1905 if (type.getBasicType() != glslang::EbtBlock)
1906 return glslang::ElpNone;
1907
1908 // has to be a uniform or buffer block
1909 if (type.getQualifier().storage != glslang::EvqUniform &&
1910 type.getQualifier().storage != glslang::EvqBuffer)
1911 return glslang::ElpNone;
1912
1913 // return the layout to use
1914 switch (type.getQualifier().layoutPacking) {
1915 case glslang::ElpStd140:
1916 case glslang::ElpStd430:
1917 return type.getQualifier().layoutPacking;
1918 default:
1919 return glslang::ElpNone;
1920 }
John Kessenich31ed4832015-09-09 17:51:38 -06001921}
1922
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001923// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07001924int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001925{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001926 int size;
John Kessenich49987892015-12-29 17:11:44 -07001927 int stride;
1928 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07001929
1930 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001931}
1932
John Kessenich49987892015-12-29 17:11:44 -07001933// 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 -07001934// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07001935int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001936{
John Kessenich49987892015-12-29 17:11:44 -07001937 glslang::TType elementType;
1938 elementType.shallowCopy(matrixType);
1939 elementType.clearArraySizes();
1940
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001941 int size;
John Kessenich49987892015-12-29 17:11:44 -07001942 int stride;
1943 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
1944
1945 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07001946}
1947
John Kessenich5e4b1242015-08-06 22:53:06 -06001948// Given a member type of a struct, realign the current offset for it, and compute
1949// the next (not yet aligned) offset for the next member, which will get aligned
1950// on the next call.
1951// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
1952// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
1953// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07001954void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07001955 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06001956{
1957 // this will get a positive value when deemed necessary
1958 nextOffset = -1;
1959
John Kessenich5e4b1242015-08-06 22:53:06 -06001960 // override anything in currentOffset with user-set offset
1961 if (memberType.getQualifier().hasOffset())
1962 currentOffset = memberType.getQualifier().layoutOffset;
1963
1964 // It could be that current linker usage in glslang updated all the layoutOffset,
1965 // in which case the following code does not matter. But, that's not quite right
1966 // once cross-compilation unit GLSL validation is done, as the original user
1967 // settings are needed in layoutOffset, and then the following will come into play.
1968
John Kessenichf85e8062015-12-19 13:57:10 -07001969 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06001970 if (! memberType.getQualifier().hasOffset())
1971 currentOffset = -1;
1972
1973 return;
1974 }
1975
John Kessenichf85e8062015-12-19 13:57:10 -07001976 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06001977 if (currentOffset < 0)
1978 currentOffset = 0;
1979
1980 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
1981 // but possibly not yet correctly aligned.
1982
1983 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07001984 int dummyStride;
1985 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich5e4b1242015-08-06 22:53:06 -06001986 glslang::RoundToPow2(currentOffset, memberAlignment);
1987 nextOffset = currentOffset + memberSize;
1988}
1989
John Kessenich140f3df2015-06-26 16:58:36 -06001990bool TGlslangToSpvTraverser::isShaderEntrypoint(const glslang::TIntermAggregate* node)
1991{
1992 return node->getName() == "main(";
1993}
1994
1995// Make all the functions, skeletally, without actually visiting their bodies.
1996void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
1997{
1998 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
1999 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
2000 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntrypoint(glslFunction))
2001 continue;
2002
2003 // We're on a user function. Set up the basic interface for the function now,
2004 // so that it's available to call.
2005 // Translating the body will happen later.
2006 //
2007 // Typically (except for a "const in" parameter), an address will be passed to the
2008 // function. What it is an address of varies:
2009 //
2010 // - "in" parameters not marked as "const" can be written to without modifying the argument,
2011 // so that write needs to be to a copy, hence the address of a copy works.
2012 //
2013 // - "const in" parameters can just be the r-value, as no writes need occur.
2014 //
2015 // - "out" and "inout" arguments can't be done as direct pointers, because GLSL has
2016 // copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
2017
2018 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002019 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002020 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2021
2022 for (int p = 0; p < (int)parameters.size(); ++p) {
2023 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2024 spv::Id typeId = convertGlslangToSpvType(paramType);
2025 if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
2026 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2027 else
2028 constReadOnlyParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002029 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002030 paramTypes.push_back(typeId);
2031 }
2032
2033 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002034 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2035 convertGlslangToSpvType(glslFunction->getType()),
2036 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich140f3df2015-06-26 16:58:36 -06002037
2038 // Track function to emit/call later
2039 functionMap[glslFunction->getName().c_str()] = function;
2040
2041 // Set the parameter id's
2042 for (int p = 0; p < (int)parameters.size(); ++p) {
2043 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2044 // give a name too
2045 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2046 }
2047 }
2048}
2049
2050// Process all the initializers, while skipping the functions and link objects
2051void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2052{
2053 builder.setBuildPoint(shaderEntry->getLastBlock());
2054 for (int i = 0; i < (int)initializers.size(); ++i) {
2055 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2056 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2057
2058 // We're on a top-level node that's not a function. Treat as an initializer, whose
2059 // code goes into the beginning of main.
2060 initializer->traverse(this);
2061 }
2062 }
2063}
2064
2065// Process all the functions, while skipping initializers.
2066void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2067{
2068 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2069 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
2070 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang ::EOpLinkerObjects))
2071 node->traverse(this);
2072 }
2073}
2074
2075void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2076{
2077 // SPIR-V functions should already be in the functionMap from the prepass
2078 // that called makeFunctions().
2079 spv::Function* function = functionMap[node->getName().c_str()];
2080 spv::Block* functionBlock = function->getEntryBlock();
2081 builder.setBuildPoint(functionBlock);
2082}
2083
Rex Xu04db3f52015-09-16 11:44:02 +08002084void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002085{
Rex Xufc618912015-09-09 16:42:49 +08002086 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002087
2088 glslang::TSampler sampler = {};
2089 bool cubeCompare = false;
2090 if (node.isTexture()) {
2091 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2092 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2093 }
2094
John Kessenich140f3df2015-06-26 16:58:36 -06002095 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2096 builder.clearAccessChain();
2097 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002098
2099 // Special case l-value operands
2100 bool lvalue = false;
2101 switch (node.getOp()) {
2102 case glslang::EOpImageAtomicAdd:
2103 case glslang::EOpImageAtomicMin:
2104 case glslang::EOpImageAtomicMax:
2105 case glslang::EOpImageAtomicAnd:
2106 case glslang::EOpImageAtomicOr:
2107 case glslang::EOpImageAtomicXor:
2108 case glslang::EOpImageAtomicExchange:
2109 case glslang::EOpImageAtomicCompSwap:
2110 if (i == 0)
2111 lvalue = true;
2112 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002113 case glslang::EOpSparseTexture:
2114 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2115 lvalue = true;
2116 break;
2117 case glslang::EOpSparseTextureClamp:
2118 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2119 lvalue = true;
2120 break;
2121 case glslang::EOpSparseTextureLod:
2122 case glslang::EOpSparseTextureOffset:
2123 if (i == 3)
2124 lvalue = true;
2125 break;
2126 case glslang::EOpSparseTextureFetch:
2127 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2128 lvalue = true;
2129 break;
2130 case glslang::EOpSparseTextureFetchOffset:
2131 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2132 lvalue = true;
2133 break;
2134 case glslang::EOpSparseTextureLodOffset:
2135 case glslang::EOpSparseTextureGrad:
2136 case glslang::EOpSparseTextureOffsetClamp:
2137 if (i == 4)
2138 lvalue = true;
2139 break;
2140 case glslang::EOpSparseTextureGradOffset:
2141 case glslang::EOpSparseTextureGradClamp:
2142 if (i == 5)
2143 lvalue = true;
2144 break;
2145 case glslang::EOpSparseTextureGradOffsetClamp:
2146 if (i == 6)
2147 lvalue = true;
2148 break;
2149 case glslang::EOpSparseTextureGather:
2150 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2151 lvalue = true;
2152 break;
2153 case glslang::EOpSparseTextureGatherOffset:
2154 case glslang::EOpSparseTextureGatherOffsets:
2155 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
2156 lvalue = true;
2157 break;
Rex Xufc618912015-09-09 16:42:49 +08002158 default:
2159 break;
2160 }
2161
Rex Xu6b86d492015-09-16 17:48:22 +08002162 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08002163 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08002164 else
John Kessenich32cfd492016-02-02 12:37:46 -07002165 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002166 }
2167}
2168
John Kessenichfc51d282015-08-19 13:34:18 -06002169void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002170{
John Kessenichfc51d282015-08-19 13:34:18 -06002171 builder.clearAccessChain();
2172 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002173 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06002174}
John Kessenich140f3df2015-06-26 16:58:36 -06002175
John Kessenichfc51d282015-08-19 13:34:18 -06002176spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
2177{
Rex Xufc618912015-09-09 16:42:49 +08002178 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06002179 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002180 }
2181
John Kessenichfc51d282015-08-19 13:34:18 -06002182 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06002183 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
2184 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
2185 std::vector<spv::Id> arguments;
2186 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08002187 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06002188 else
2189 translateArguments(*node->getAsUnaryNode(), arguments);
2190 spv::Decoration precision = TranslatePrecisionDecoration(node->getType());
2191
2192 spv::Builder::TextureParameters params = { };
2193 params.sampler = arguments[0];
2194
Rex Xu04db3f52015-09-16 11:44:02 +08002195 glslang::TCrackedTextureOp cracked;
2196 node->crackTexture(sampler, cracked);
2197
John Kessenichfc51d282015-08-19 13:34:18 -06002198 // Check for queries
2199 if (cracked.query) {
John Kessenich33661452015-12-08 19:32:47 -07002200 // a sampled image needs to have the image extracted first
2201 if (builder.isSampledImage(params.sampler))
2202 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
John Kessenichfc51d282015-08-19 13:34:18 -06002203 switch (node->getOp()) {
2204 case glslang::EOpImageQuerySize:
2205 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06002206 if (arguments.size() > 1) {
2207 params.lod = arguments[1];
John Kessenich5e4b1242015-08-06 22:53:06 -06002208 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002209 } else
John Kessenich5e4b1242015-08-06 22:53:06 -06002210 return builder.createTextureQueryCall(spv::OpImageQuerySize, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002211 case glslang::EOpImageQuerySamples:
2212 case glslang::EOpTextureQuerySamples:
John Kessenich5e4b1242015-08-06 22:53:06 -06002213 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params);
John Kessenichfc51d282015-08-19 13:34:18 -06002214 case glslang::EOpTextureQueryLod:
2215 params.coords = arguments[1];
2216 return builder.createTextureQueryCall(spv::OpImageQueryLod, params);
2217 case glslang::EOpTextureQueryLevels:
2218 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params);
Rex Xu48edadf2015-12-31 16:11:41 +08002219 case glslang::EOpSparseTexelsResident:
2220 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06002221 default:
2222 assert(0);
2223 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002224 }
John Kessenich140f3df2015-06-26 16:58:36 -06002225 }
2226
Rex Xufc618912015-09-09 16:42:49 +08002227 // Check for image functions other than queries
2228 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06002229 std::vector<spv::Id> operands;
2230 auto opIt = arguments.begin();
2231 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07002232
2233 // Handle subpass operations
2234 // TODO: GLSL should change to have the "MS" only on the type rather than the
2235 // built-in function.
2236 if (cracked.subpass) {
2237 // add on the (0,0) coordinate
2238 spv::Id zero = builder.makeIntConstant(0);
2239 std::vector<spv::Id> comps;
2240 comps.push_back(zero);
2241 comps.push_back(zero);
2242 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
2243 if (sampler.ms) {
2244 operands.push_back(spv::ImageOperandsSampleMask);
2245 operands.push_back(*(opIt++));
2246 }
2247 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
2248 }
2249
John Kessenich56bab042015-09-16 10:54:31 -06002250 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06002251 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07002252 if (sampler.ms) {
2253 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08002254 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07002255 }
John Kessenich56bab042015-09-16 10:54:31 -06002256 return builder.createOp(spv::OpImageRead, convertGlslangToSpvType(node->getType()), operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002257 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2258 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002259 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08002260 if (sampler.ms) {
2261 operands.push_back(*(opIt + 1));
2262 operands.push_back(spv::ImageOperandsSampleMask);
2263 operands.push_back(*opIt);
2264 } else
2265 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06002266 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07002267 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
2268 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06002269 return spv::NoResult;
Rex Xu48edadf2015-12-31 16:11:41 +08002270 } else if (node->isSparseImage()) {
2271 spv::MissingFunctionality("sparse image functions");
2272 return spv::NoResult;
John Kessenichcd261442016-01-22 09:54:12 -07002273 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08002274 // Process image atomic operations
2275
2276 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
2277 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07002278 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06002279
Rex Xufc618912015-09-09 16:42:49 +08002280 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, convertGlslangToSpvType(node->getType()));
John Kessenich56bab042015-09-16 10:54:31 -06002281 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08002282
2283 std::vector<spv::Id> operands;
2284 operands.push_back(pointer);
2285 for (; opIt != arguments.end(); ++opIt)
2286 operands.push_back(*opIt);
2287
Rex Xu04db3f52015-09-16 11:44:02 +08002288 return createAtomicOperation(node->getOp(), precision, convertGlslangToSpvType(node->getType()), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08002289 }
2290 }
2291
2292 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08002293 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08002294 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2295
John Kessenichfc51d282015-08-19 13:34:18 -06002296 // check for bias argument
2297 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08002298 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002299 int nonBiasArgCount = 2;
2300 if (cracked.offset)
2301 ++nonBiasArgCount;
2302 if (cracked.grad)
2303 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08002304 if (cracked.lodClamp)
2305 ++nonBiasArgCount;
2306 if (sparse)
2307 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06002308
2309 if ((int)arguments.size() > nonBiasArgCount)
2310 bias = true;
2311 }
2312
John Kessenichfc51d282015-08-19 13:34:18 -06002313 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07002314
John Kessenichfc51d282015-08-19 13:34:18 -06002315 params.coords = arguments[1];
2316 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07002317 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07002318
2319 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08002320 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06002321 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08002322 ++extraArgs;
2323 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07002324 params.Dref = arguments[2];
2325 ++extraArgs;
2326 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06002327 std::vector<spv::Id> indexes;
2328 int comp;
2329 if (cracked.proj)
John Kessenich6feb4982015-12-13 12:23:33 -07002330 comp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06002331 else
2332 comp = builder.getNumComponents(params.coords) - 1;
2333 indexes.push_back(comp);
2334 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
2335 }
2336 if (cracked.lod) {
2337 params.lod = arguments[2];
2338 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07002339 } else if (glslangIntermediate->getStage() != EShLangFragment) {
2340 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
2341 noImplicitLod = true;
2342 }
2343 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08002344 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08002345 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002346 }
2347 if (cracked.grad) {
2348 params.gradX = arguments[2 + extraArgs];
2349 params.gradY = arguments[3 + extraArgs];
2350 extraArgs += 2;
2351 }
John Kessenich55e7d112015-11-15 21:33:39 -07002352 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06002353 params.offset = arguments[2 + extraArgs];
2354 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07002355 } else if (cracked.offsets) {
2356 params.offsets = arguments[2 + extraArgs];
2357 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06002358 }
Rex Xu48edadf2015-12-31 16:11:41 +08002359 if (cracked.lodClamp) {
2360 params.lodClamp = arguments[2 + extraArgs];
2361 ++extraArgs;
2362 }
2363 if (sparse) {
2364 params.texelOut = arguments[2 + extraArgs];
2365 ++extraArgs;
2366 }
John Kessenichfc51d282015-08-19 13:34:18 -06002367 if (bias) {
2368 params.bias = arguments[2 + extraArgs];
2369 ++extraArgs;
2370 }
John Kessenich55e7d112015-11-15 21:33:39 -07002371 if (cracked.gather && ! sampler.shadow) {
2372 // default component is 0, if missing, otherwise an argument
2373 if (2 + extraArgs < (int)arguments.size()) {
2374 params.comp = arguments[2 + extraArgs];
2375 ++extraArgs;
2376 } else {
2377 params.comp = builder.makeIntConstant(0);
2378 }
2379 }
John Kessenichfc51d282015-08-19 13:34:18 -06002380
John Kessenich019f08f2016-02-15 15:40:42 -07002381 return builder.createTextureCall(precision, convertGlslangToSpvType(node->getType()), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06002382}
2383
2384spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
2385{
2386 // Grab the function's pointer from the previously created function
2387 spv::Function* function = functionMap[node->getName().c_str()];
2388 if (! function)
2389 return 0;
2390
2391 const glslang::TIntermSequence& glslangArgs = node->getSequence();
2392 const glslang::TQualifierList& qualifiers = node->getQualifierList();
2393
2394 // See comments in makeFunctions() for details about the semantics for parameter passing.
2395 //
2396 // These imply we need a four step process:
2397 // 1. Evaluate the arguments
2398 // 2. Allocate and make copies of in, out, and inout arguments
2399 // 3. Make the call
2400 // 4. Copy back the results
2401
2402 // 1. Evaluate the arguments
2403 std::vector<spv::Builder::AccessChain> lValues;
2404 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07002405 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06002406 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2407 // build l-value
2408 builder.clearAccessChain();
2409 glslangArgs[a]->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002410 argTypes.push_back(&glslangArgs[a]->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002411 // keep outputs as l-values, evaluate input-only as r-values
2412 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2413 // save l-value
2414 lValues.push_back(builder.getAccessChain());
2415 } else {
2416 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07002417 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06002418 }
2419 }
2420
2421 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
2422 // copy the original into that space.
2423 //
2424 // Also, build up the list of actual arguments to pass in for the call
2425 int lValueCount = 0;
2426 int rValueCount = 0;
2427 std::vector<spv::Id> spvArgs;
2428 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2429 spv::Id arg;
2430 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2431 // need space to hold the copy
2432 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
2433 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
2434 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
2435 // need to copy the input into output space
2436 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07002437 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich140f3df2015-06-26 16:58:36 -06002438 builder.createStore(copy, arg);
2439 }
2440 ++lValueCount;
2441 } else {
2442 arg = rValues[rValueCount];
2443 ++rValueCount;
2444 }
2445 spvArgs.push_back(arg);
2446 }
2447
2448 // 3. Make the call.
2449 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07002450 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06002451
2452 // 4. Copy back out an "out" arguments.
2453 lValueCount = 0;
2454 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
2455 if (qualifiers[a] != glslang::EvqConstReadOnly) {
2456 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
2457 spv::Id copy = builder.createLoad(spvArgs[a]);
2458 builder.setAccessChain(lValues[lValueCount]);
2459 builder.accessChainStore(copy);
2460 }
2461 ++lValueCount;
2462 }
2463 }
2464
2465 return result;
2466}
2467
2468// Translate AST operation to SPV operation, already having SPV-based operands/types.
2469spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
2470 spv::Id typeId, spv::Id left, spv::Id right,
2471 glslang::TBasicType typeProxy, bool reduceComparison)
2472{
2473 bool isUnsigned = typeProxy == glslang::EbtUint;
2474 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
2475
2476 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06002477 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06002478 bool comparison = false;
2479
2480 switch (op) {
2481 case glslang::EOpAdd:
2482 case glslang::EOpAddAssign:
2483 if (isFloat)
2484 binOp = spv::OpFAdd;
2485 else
2486 binOp = spv::OpIAdd;
2487 break;
2488 case glslang::EOpSub:
2489 case glslang::EOpSubAssign:
2490 if (isFloat)
2491 binOp = spv::OpFSub;
2492 else
2493 binOp = spv::OpISub;
2494 break;
2495 case glslang::EOpMul:
2496 case glslang::EOpMulAssign:
2497 if (isFloat)
2498 binOp = spv::OpFMul;
2499 else
2500 binOp = spv::OpIMul;
2501 break;
2502 case glslang::EOpVectorTimesScalar:
2503 case glslang::EOpVectorTimesScalarAssign:
John Kessenichec43d0a2015-07-04 17:17:31 -06002504 if (isFloat) {
2505 if (builder.isVector(right))
2506 std::swap(left, right);
2507 assert(builder.isScalar(right));
2508 needMatchingVectors = false;
2509 binOp = spv::OpVectorTimesScalar;
2510 } else
2511 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06002512 break;
2513 case glslang::EOpVectorTimesMatrix:
2514 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002515 binOp = spv::OpVectorTimesMatrix;
2516 break;
2517 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06002518 binOp = spv::OpMatrixTimesVector;
2519 break;
2520 case glslang::EOpMatrixTimesScalar:
2521 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002522 binOp = spv::OpMatrixTimesScalar;
2523 break;
2524 case glslang::EOpMatrixTimesMatrix:
2525 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06002526 binOp = spv::OpMatrixTimesMatrix;
2527 break;
2528 case glslang::EOpOuterProduct:
2529 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06002530 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002531 break;
2532
2533 case glslang::EOpDiv:
2534 case glslang::EOpDivAssign:
2535 if (isFloat)
2536 binOp = spv::OpFDiv;
2537 else if (isUnsigned)
2538 binOp = spv::OpUDiv;
2539 else
2540 binOp = spv::OpSDiv;
2541 break;
2542 case glslang::EOpMod:
2543 case glslang::EOpModAssign:
2544 if (isFloat)
2545 binOp = spv::OpFMod;
2546 else if (isUnsigned)
2547 binOp = spv::OpUMod;
2548 else
2549 binOp = spv::OpSMod;
2550 break;
2551 case glslang::EOpRightShift:
2552 case glslang::EOpRightShiftAssign:
2553 if (isUnsigned)
2554 binOp = spv::OpShiftRightLogical;
2555 else
2556 binOp = spv::OpShiftRightArithmetic;
2557 break;
2558 case glslang::EOpLeftShift:
2559 case glslang::EOpLeftShiftAssign:
2560 binOp = spv::OpShiftLeftLogical;
2561 break;
2562 case glslang::EOpAnd:
2563 case glslang::EOpAndAssign:
2564 binOp = spv::OpBitwiseAnd;
2565 break;
2566 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06002567 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002568 binOp = spv::OpLogicalAnd;
2569 break;
2570 case glslang::EOpInclusiveOr:
2571 case glslang::EOpInclusiveOrAssign:
2572 binOp = spv::OpBitwiseOr;
2573 break;
2574 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06002575 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06002576 binOp = spv::OpLogicalOr;
2577 break;
2578 case glslang::EOpExclusiveOr:
2579 case glslang::EOpExclusiveOrAssign:
2580 binOp = spv::OpBitwiseXor;
2581 break;
2582 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06002583 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06002584 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06002585 break;
2586
2587 case glslang::EOpLessThan:
2588 case glslang::EOpGreaterThan:
2589 case glslang::EOpLessThanEqual:
2590 case glslang::EOpGreaterThanEqual:
2591 case glslang::EOpEqual:
2592 case glslang::EOpNotEqual:
2593 case glslang::EOpVectorEqual:
2594 case glslang::EOpVectorNotEqual:
2595 comparison = true;
2596 break;
2597 default:
2598 break;
2599 }
2600
John Kessenich7c1aa102015-10-15 13:29:11 -06002601 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06002602 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06002603 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07002604 if (builder.isMatrix(left) || builder.isMatrix(right))
2605 return createBinaryMatrixOperation(binOp, precision, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06002606
2607 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06002608 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06002609 builder.promoteScalar(precision, left, right);
2610
John Kessenich32cfd492016-02-02 12:37:46 -07002611 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002612 }
2613
2614 if (! comparison)
2615 return 0;
2616
John Kessenich7c1aa102015-10-15 13:29:11 -06002617 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06002618
2619 if (reduceComparison && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left))) {
2620 assert(op == glslang::EOpEqual || op == glslang::EOpNotEqual);
2621
John Kessenich22118352015-12-21 20:54:09 -07002622 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06002623 }
2624
2625 switch (op) {
2626 case glslang::EOpLessThan:
2627 if (isFloat)
2628 binOp = spv::OpFOrdLessThan;
2629 else if (isUnsigned)
2630 binOp = spv::OpULessThan;
2631 else
2632 binOp = spv::OpSLessThan;
2633 break;
2634 case glslang::EOpGreaterThan:
2635 if (isFloat)
2636 binOp = spv::OpFOrdGreaterThan;
2637 else if (isUnsigned)
2638 binOp = spv::OpUGreaterThan;
2639 else
2640 binOp = spv::OpSGreaterThan;
2641 break;
2642 case glslang::EOpLessThanEqual:
2643 if (isFloat)
2644 binOp = spv::OpFOrdLessThanEqual;
2645 else if (isUnsigned)
2646 binOp = spv::OpULessThanEqual;
2647 else
2648 binOp = spv::OpSLessThanEqual;
2649 break;
2650 case glslang::EOpGreaterThanEqual:
2651 if (isFloat)
2652 binOp = spv::OpFOrdGreaterThanEqual;
2653 else if (isUnsigned)
2654 binOp = spv::OpUGreaterThanEqual;
2655 else
2656 binOp = spv::OpSGreaterThanEqual;
2657 break;
2658 case glslang::EOpEqual:
2659 case glslang::EOpVectorEqual:
2660 if (isFloat)
2661 binOp = spv::OpFOrdEqual;
2662 else
2663 binOp = spv::OpIEqual;
2664 break;
2665 case glslang::EOpNotEqual:
2666 case glslang::EOpVectorNotEqual:
2667 if (isFloat)
2668 binOp = spv::OpFOrdNotEqual;
2669 else
2670 binOp = spv::OpINotEqual;
2671 break;
2672 default:
2673 break;
2674 }
2675
John Kessenich32cfd492016-02-02 12:37:46 -07002676 if (binOp != spv::OpNop)
2677 return builder.setPrecision(builder.createBinOp(binOp, typeId, left, right), precision);
John Kessenich140f3df2015-06-26 16:58:36 -06002678
2679 return 0;
2680}
2681
John Kessenich04bb8a02015-12-12 12:28:14 -07002682//
2683// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
2684// These can be any of:
2685//
2686// matrix * scalar
2687// scalar * matrix
2688// matrix * matrix linear algebraic
2689// matrix * vector
2690// vector * matrix
2691// matrix * matrix componentwise
2692// matrix op matrix op in {+, -, /}
2693// matrix op scalar op in {+, -, /}
2694// scalar op matrix op in {+, -, /}
2695//
2696spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id left, spv::Id right)
2697{
2698 bool firstClass = true;
2699
2700 // First, handle first-class matrix operations (* and matrix/scalar)
2701 switch (op) {
2702 case spv::OpFDiv:
2703 if (builder.isMatrix(left) && builder.isScalar(right)) {
2704 // turn matrix / scalar into a multiply...
2705 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
2706 op = spv::OpMatrixTimesScalar;
2707 } else
2708 firstClass = false;
2709 break;
2710 case spv::OpMatrixTimesScalar:
2711 if (builder.isMatrix(right))
2712 std::swap(left, right);
2713 assert(builder.isScalar(right));
2714 break;
2715 case spv::OpVectorTimesMatrix:
2716 assert(builder.isVector(left));
2717 assert(builder.isMatrix(right));
2718 break;
2719 case spv::OpMatrixTimesVector:
2720 assert(builder.isMatrix(left));
2721 assert(builder.isVector(right));
2722 break;
2723 case spv::OpMatrixTimesMatrix:
2724 assert(builder.isMatrix(left));
2725 assert(builder.isMatrix(right));
2726 break;
2727 default:
2728 firstClass = false;
2729 break;
2730 }
2731
John Kessenich32cfd492016-02-02 12:37:46 -07002732 if (firstClass)
2733 return builder.setPrecision(builder.createBinOp(op, typeId, left, right), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002734
2735 // Handle component-wise +, -, *, and / for all combinations of type.
2736 // The result type of all of them is the same type as the (a) matrix operand.
2737 // The algorithm is to:
2738 // - break the matrix(es) into vectors
2739 // - smear any scalar to a vector
2740 // - do vector operations
2741 // - make a matrix out the vector results
2742 switch (op) {
2743 case spv::OpFAdd:
2744 case spv::OpFSub:
2745 case spv::OpFDiv:
2746 case spv::OpFMul:
2747 {
2748 // one time set up...
2749 bool leftMat = builder.isMatrix(left);
2750 bool rightMat = builder.isMatrix(right);
2751 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
2752 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
2753 spv::Id scalarType = builder.getScalarTypeId(typeId);
2754 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
2755 std::vector<spv::Id> results;
2756 spv::Id smearVec = spv::NoResult;
2757 if (builder.isScalar(left))
2758 smearVec = builder.smearScalar(precision, left, vecType);
2759 else if (builder.isScalar(right))
2760 smearVec = builder.smearScalar(precision, right, vecType);
2761
2762 // do each vector op
2763 for (unsigned int c = 0; c < numCols; ++c) {
2764 std::vector<unsigned int> indexes;
2765 indexes.push_back(c);
2766 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
2767 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
2768 results.push_back(builder.createBinOp(op, vecType, leftVec, rightVec));
2769 builder.setPrecision(results.back(), precision);
2770 }
2771
2772 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07002773 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07002774 }
2775 default:
2776 assert(0);
2777 return spv::NoResult;
2778 }
2779}
2780
Rex Xu04db3f52015-09-16 11:44:02 +08002781spv::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 -06002782{
2783 spv::Op unaryOp = spv::OpNop;
2784 int libCall = -1;
John Kessenich55e7d112015-11-15 21:33:39 -07002785 bool isUnsigned = typeProxy == glslang::EbtUint;
Rex Xu04db3f52015-09-16 11:44:02 +08002786 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
John Kessenich140f3df2015-06-26 16:58:36 -06002787
2788 switch (op) {
2789 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07002790 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06002791 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07002792 if (builder.isMatrixType(typeId))
2793 return createUnaryMatrixOperation(unaryOp, precision, typeId, operand, typeProxy);
2794 } else
John Kessenich140f3df2015-06-26 16:58:36 -06002795 unaryOp = spv::OpSNegate;
2796 break;
2797
2798 case glslang::EOpLogicalNot:
2799 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06002800 unaryOp = spv::OpLogicalNot;
2801 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002802 case glslang::EOpBitwiseNot:
2803 unaryOp = spv::OpNot;
2804 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06002805
John Kessenich140f3df2015-06-26 16:58:36 -06002806 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06002807 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06002808 break;
2809 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06002810 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06002811 break;
2812 case glslang::EOpTranspose:
2813 unaryOp = spv::OpTranspose;
2814 break;
2815
2816 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06002817 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06002818 break;
2819 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06002820 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06002821 break;
2822 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002823 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06002824 break;
2825 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002826 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06002827 break;
2828 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002829 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06002830 break;
2831 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06002832 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06002833 break;
2834 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06002835 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06002836 break;
2837 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06002838 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06002839 break;
2840
2841 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002842 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002843 break;
2844 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002845 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002846 break;
2847 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002848 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002849 break;
2850 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002851 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06002852 break;
2853 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002854 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06002855 break;
2856 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06002857 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06002858 break;
2859
2860 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06002861 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06002862 break;
2863 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06002864 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06002865 break;
2866
2867 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06002868 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06002869 break;
2870 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06002871 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06002872 break;
2873 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002874 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06002875 break;
2876 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06002877 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06002878 break;
2879 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002880 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002881 break;
2882 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06002883 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06002884 break;
2885
2886 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06002887 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06002888 break;
2889 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06002890 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06002891 break;
2892 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06002893 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06002894 break;
2895 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06002896 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06002897 break;
2898 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06002899 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06002900 break;
2901 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06002902 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06002903 break;
2904
2905 case glslang::EOpIsNan:
2906 unaryOp = spv::OpIsNan;
2907 break;
2908 case glslang::EOpIsInf:
2909 unaryOp = spv::OpIsInf;
2910 break;
2911
Rex Xucbc426e2015-12-15 16:03:10 +08002912 case glslang::EOpFloatBitsToInt:
2913 case glslang::EOpFloatBitsToUint:
2914 case glslang::EOpIntBitsToFloat:
2915 case glslang::EOpUintBitsToFloat:
2916 unaryOp = spv::OpBitcast;
2917 break;
2918
John Kessenich140f3df2015-06-26 16:58:36 -06002919 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002920 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002921 break;
2922 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002923 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002924 break;
2925 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002926 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002927 break;
2928 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002929 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002930 break;
2931 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002932 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002933 break;
2934 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06002935 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06002936 break;
John Kessenichfc51d282015-08-19 13:34:18 -06002937 case glslang::EOpPackSnorm4x8:
2938 libCall = spv::GLSLstd450PackSnorm4x8;
2939 break;
2940 case glslang::EOpUnpackSnorm4x8:
2941 libCall = spv::GLSLstd450UnpackSnorm4x8;
2942 break;
2943 case glslang::EOpPackUnorm4x8:
2944 libCall = spv::GLSLstd450PackUnorm4x8;
2945 break;
2946 case glslang::EOpUnpackUnorm4x8:
2947 libCall = spv::GLSLstd450UnpackUnorm4x8;
2948 break;
2949 case glslang::EOpPackDouble2x32:
2950 libCall = spv::GLSLstd450PackDouble2x32;
2951 break;
2952 case glslang::EOpUnpackDouble2x32:
2953 libCall = spv::GLSLstd450UnpackDouble2x32;
2954 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002955
2956 case glslang::EOpDPdx:
2957 unaryOp = spv::OpDPdx;
2958 break;
2959 case glslang::EOpDPdy:
2960 unaryOp = spv::OpDPdy;
2961 break;
2962 case glslang::EOpFwidth:
2963 unaryOp = spv::OpFwidth;
2964 break;
2965 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07002966 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002967 unaryOp = spv::OpDPdxFine;
2968 break;
2969 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07002970 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002971 unaryOp = spv::OpDPdyFine;
2972 break;
2973 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07002974 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002975 unaryOp = spv::OpFwidthFine;
2976 break;
2977 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002978 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002979 unaryOp = spv::OpDPdxCoarse;
2980 break;
2981 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002982 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002983 unaryOp = spv::OpDPdyCoarse;
2984 break;
2985 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07002986 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06002987 unaryOp = spv::OpFwidthCoarse;
2988 break;
Rex Xu7a26c172015-12-08 17:12:09 +08002989 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07002990 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08002991 libCall = spv::GLSLstd450InterpolateAtCentroid;
2992 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002993 case glslang::EOpAny:
2994 unaryOp = spv::OpAny;
2995 break;
2996 case glslang::EOpAll:
2997 unaryOp = spv::OpAll;
2998 break;
2999
3000 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003001 if (isFloat)
3002 libCall = spv::GLSLstd450FAbs;
3003 else
3004 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003005 break;
3006 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003007 if (isFloat)
3008 libCall = spv::GLSLstd450FSign;
3009 else
3010 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003011 break;
3012
John Kessenichfc51d282015-08-19 13:34:18 -06003013 case glslang::EOpAtomicCounterIncrement:
3014 case glslang::EOpAtomicCounterDecrement:
3015 case glslang::EOpAtomicCounter:
3016 {
3017 // Handle all of the atomics in one place, in createAtomicOperation()
3018 std::vector<spv::Id> operands;
3019 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003020 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003021 }
3022
John Kessenichfc51d282015-08-19 13:34:18 -06003023 case glslang::EOpBitFieldReverse:
3024 unaryOp = spv::OpBitReverse;
3025 break;
3026 case glslang::EOpBitCount:
3027 unaryOp = spv::OpBitCount;
3028 break;
3029 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003030 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003031 break;
3032 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07003033 if (isUnsigned)
3034 libCall = spv::GLSLstd450FindUMsb;
3035 else
3036 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06003037 break;
3038
John Kessenich140f3df2015-06-26 16:58:36 -06003039 default:
3040 return 0;
3041 }
3042
3043 spv::Id id;
3044 if (libCall >= 0) {
3045 std::vector<spv::Id> args;
3046 args.push_back(operand);
John Kessenich32cfd492016-02-02 12:37:46 -07003047 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, args);
John Kessenich140f3df2015-06-26 16:58:36 -06003048 } else
3049 id = builder.createUnaryOp(unaryOp, typeId, operand);
3050
John Kessenich32cfd492016-02-02 12:37:46 -07003051 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003052}
3053
John Kessenich7a53f762016-01-20 11:19:27 -07003054// Create a unary operation on a matrix
3055spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
3056{
3057 // Handle unary operations vector by vector.
3058 // The result type is the same type as the original type.
3059 // The algorithm is to:
3060 // - break the matrix into vectors
3061 // - apply the operation to each vector
3062 // - make a matrix out the vector results
3063
3064 // get the types sorted out
3065 int numCols = builder.getNumColumns(operand);
3066 int numRows = builder.getNumRows(operand);
3067 spv::Id scalarType = builder.getScalarTypeId(typeId);
3068 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3069 std::vector<spv::Id> results;
3070
3071 // do each vector op
3072 for (int c = 0; c < numCols; ++c) {
3073 std::vector<unsigned int> indexes;
3074 indexes.push_back(c);
3075 spv::Id vec = builder.createCompositeExtract(operand, vecType, indexes);
3076 results.push_back(builder.createUnaryOp(op, vecType, vec));
3077 builder.setPrecision(results.back(), precision);
3078 }
3079
3080 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003081 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07003082}
3083
John Kessenich140f3df2015-06-26 16:58:36 -06003084spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Id destType, spv::Id operand)
3085{
3086 spv::Op convOp = spv::OpNop;
3087 spv::Id zero = 0;
3088 spv::Id one = 0;
3089
3090 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
3091
3092 switch (op) {
3093 case glslang::EOpConvIntToBool:
3094 case glslang::EOpConvUintToBool:
3095 zero = builder.makeUintConstant(0);
3096 zero = makeSmearedConstant(zero, vectorSize);
3097 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
3098
3099 case glslang::EOpConvFloatToBool:
3100 zero = builder.makeFloatConstant(0.0F);
3101 zero = makeSmearedConstant(zero, vectorSize);
3102 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3103
3104 case glslang::EOpConvDoubleToBool:
3105 zero = builder.makeDoubleConstant(0.0);
3106 zero = makeSmearedConstant(zero, vectorSize);
3107 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
3108
3109 case glslang::EOpConvBoolToFloat:
3110 convOp = spv::OpSelect;
3111 zero = builder.makeFloatConstant(0.0);
3112 one = builder.makeFloatConstant(1.0);
3113 break;
3114 case glslang::EOpConvBoolToDouble:
3115 convOp = spv::OpSelect;
3116 zero = builder.makeDoubleConstant(0.0);
3117 one = builder.makeDoubleConstant(1.0);
3118 break;
3119 case glslang::EOpConvBoolToInt:
3120 zero = builder.makeIntConstant(0);
3121 one = builder.makeIntConstant(1);
3122 convOp = spv::OpSelect;
3123 break;
3124 case glslang::EOpConvBoolToUint:
3125 zero = builder.makeUintConstant(0);
3126 one = builder.makeUintConstant(1);
3127 convOp = spv::OpSelect;
3128 break;
3129
3130 case glslang::EOpConvIntToFloat:
3131 case glslang::EOpConvIntToDouble:
3132 convOp = spv::OpConvertSToF;
3133 break;
3134
3135 case glslang::EOpConvUintToFloat:
3136 case glslang::EOpConvUintToDouble:
3137 convOp = spv::OpConvertUToF;
3138 break;
3139
3140 case glslang::EOpConvDoubleToFloat:
3141 case glslang::EOpConvFloatToDouble:
3142 convOp = spv::OpFConvert;
3143 break;
3144
3145 case glslang::EOpConvFloatToInt:
3146 case glslang::EOpConvDoubleToInt:
3147 convOp = spv::OpConvertFToS;
3148 break;
3149
3150 case glslang::EOpConvUintToInt:
3151 case glslang::EOpConvIntToUint:
3152 convOp = spv::OpBitcast;
3153 break;
3154
3155 case glslang::EOpConvFloatToUint:
3156 case glslang::EOpConvDoubleToUint:
3157 convOp = spv::OpConvertFToU;
3158 break;
3159 default:
3160 break;
3161 }
3162
3163 spv::Id result = 0;
3164 if (convOp == spv::OpNop)
3165 return result;
3166
3167 if (convOp == spv::OpSelect) {
3168 zero = makeSmearedConstant(zero, vectorSize);
3169 one = makeSmearedConstant(one, vectorSize);
3170 result = builder.createTriOp(convOp, destType, operand, one, zero);
3171 } else
3172 result = builder.createUnaryOp(convOp, destType, operand);
3173
John Kessenich32cfd492016-02-02 12:37:46 -07003174 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003175}
3176
3177spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
3178{
3179 if (vectorSize == 0)
3180 return constant;
3181
3182 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
3183 std::vector<spv::Id> components;
3184 for (int c = 0; c < vectorSize; ++c)
3185 components.push_back(constant);
3186 return builder.makeCompositeConstant(vectorTypeId, components);
3187}
3188
John Kessenich426394d2015-07-23 10:22:48 -06003189// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07003190spv::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 -06003191{
3192 spv::Op opCode = spv::OpNop;
3193
3194 switch (op) {
3195 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08003196 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06003197 opCode = spv::OpAtomicIAdd;
3198 break;
3199 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08003200 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08003201 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06003202 break;
3203 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08003204 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08003205 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06003206 break;
3207 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08003208 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06003209 opCode = spv::OpAtomicAnd;
3210 break;
3211 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08003212 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06003213 opCode = spv::OpAtomicOr;
3214 break;
3215 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08003216 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06003217 opCode = spv::OpAtomicXor;
3218 break;
3219 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08003220 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06003221 opCode = spv::OpAtomicExchange;
3222 break;
3223 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08003224 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06003225 opCode = spv::OpAtomicCompareExchange;
3226 break;
3227 case glslang::EOpAtomicCounterIncrement:
3228 opCode = spv::OpAtomicIIncrement;
3229 break;
3230 case glslang::EOpAtomicCounterDecrement:
3231 opCode = spv::OpAtomicIDecrement;
3232 break;
3233 case glslang::EOpAtomicCounter:
3234 opCode = spv::OpAtomicLoad;
3235 break;
3236 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003237 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06003238 break;
3239 }
3240
3241 // Sort out the operands
3242 // - mapping from glslang -> SPV
3243 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06003244 // - compare-exchange swaps the value and comparator
3245 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06003246 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
3247 auto opIt = operands.begin(); // walk the glslang operands
3248 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08003249 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
3250 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
3251 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08003252 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
3253 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08003254 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06003255 spvAtomicOperands.push_back(*(opIt + 1));
3256 spvAtomicOperands.push_back(*opIt);
3257 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08003258 }
John Kessenich426394d2015-07-23 10:22:48 -06003259
John Kessenich3e60a6f2015-09-14 22:45:16 -06003260 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06003261 for (; opIt != operands.end(); ++opIt)
3262 spvAtomicOperands.push_back(*opIt);
3263
3264 return builder.createOp(opCode, typeId, spvAtomicOperands);
3265}
3266
John Kessenich5e4b1242015-08-06 22:53:06 -06003267spv::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 -06003268{
John Kessenich5e4b1242015-08-06 22:53:06 -06003269 bool isUnsigned = typeProxy == glslang::EbtUint;
3270 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
3271
John Kessenich140f3df2015-06-26 16:58:36 -06003272 spv::Op opCode = spv::OpNop;
3273 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05003274 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07003275 spv::Id typeId0 = 0;
3276 if (consumedOperands > 0)
3277 typeId0 = builder.getTypeId(operands[0]);
3278 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06003279
3280 switch (op) {
3281 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003282 if (isFloat)
3283 libCall = spv::GLSLstd450FMin;
3284 else if (isUnsigned)
3285 libCall = spv::GLSLstd450UMin;
3286 else
3287 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003288 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003289 break;
3290 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06003291 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06003292 break;
3293 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06003294 if (isFloat)
3295 libCall = spv::GLSLstd450FMax;
3296 else if (isUnsigned)
3297 libCall = spv::GLSLstd450UMax;
3298 else
3299 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003300 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003301 break;
3302 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06003303 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06003304 break;
3305 case glslang::EOpDot:
3306 opCode = spv::OpDot;
3307 break;
3308 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003309 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06003310 break;
3311
3312 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003313 if (isFloat)
3314 libCall = spv::GLSLstd450FClamp;
3315 else if (isUnsigned)
3316 libCall = spv::GLSLstd450UClamp;
3317 else
3318 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003319 builder.promoteScalar(precision, operands.front(), operands[1]);
3320 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003321 break;
3322 case glslang::EOpMix:
John Kessenich55e7d112015-11-15 21:33:39 -07003323 if (isFloat)
3324 libCall = spv::GLSLstd450FMix;
John Kessenich6c292d32016-02-15 20:58:50 -07003325 else {
3326 opCode = spv::OpSelect;
3327 spv::MissingFunctionality("translating integer mix to OpSelect");
3328 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07003329 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003330 break;
3331 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003332 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003333 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06003334 break;
3335 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06003336 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07003337 builder.promoteScalar(precision, operands[0], operands[2]);
3338 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06003339 break;
3340
3341 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06003342 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06003343 break;
3344 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06003345 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06003346 break;
3347 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06003348 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06003349 break;
3350 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06003351 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06003352 break;
3353 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003354 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06003355 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003356 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07003357 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003358 libCall = spv::GLSLstd450InterpolateAtSample;
3359 break;
3360 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07003361 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003362 libCall = spv::GLSLstd450InterpolateAtOffset;
3363 break;
John Kessenich55e7d112015-11-15 21:33:39 -07003364 case glslang::EOpAddCarry:
3365 opCode = spv::OpIAddCarry;
3366 typeId = builder.makeStructResultType(typeId0, typeId0);
3367 consumedOperands = 2;
3368 break;
3369 case glslang::EOpSubBorrow:
3370 opCode = spv::OpISubBorrow;
3371 typeId = builder.makeStructResultType(typeId0, typeId0);
3372 consumedOperands = 2;
3373 break;
3374 case glslang::EOpUMulExtended:
3375 opCode = spv::OpUMulExtended;
3376 typeId = builder.makeStructResultType(typeId0, typeId0);
3377 consumedOperands = 2;
3378 break;
3379 case glslang::EOpIMulExtended:
3380 opCode = spv::OpSMulExtended;
3381 typeId = builder.makeStructResultType(typeId0, typeId0);
3382 consumedOperands = 2;
3383 break;
3384 case glslang::EOpBitfieldExtract:
3385 if (isUnsigned)
3386 opCode = spv::OpBitFieldUExtract;
3387 else
3388 opCode = spv::OpBitFieldSExtract;
3389 break;
3390 case glslang::EOpBitfieldInsert:
3391 opCode = spv::OpBitFieldInsert;
3392 break;
3393
3394 case glslang::EOpFma:
3395 libCall = spv::GLSLstd450Fma;
3396 break;
3397 case glslang::EOpFrexp:
3398 libCall = spv::GLSLstd450FrexpStruct;
3399 if (builder.getNumComponents(operands[0]) == 1)
3400 frexpIntType = builder.makeIntegerType(32, true);
3401 else
3402 frexpIntType = builder.makeVectorType(builder.makeIntegerType(32, true), builder.getNumComponents(operands[0]));
3403 typeId = builder.makeStructResultType(typeId0, frexpIntType);
3404 consumedOperands = 1;
3405 break;
3406 case glslang::EOpLdexp:
3407 libCall = spv::GLSLstd450Ldexp;
3408 break;
3409
John Kessenich140f3df2015-06-26 16:58:36 -06003410 default:
3411 return 0;
3412 }
3413
3414 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07003415 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05003416 // Use an extended instruction from the standard library.
3417 // Construct the call arguments, without modifying the original operands vector.
3418 // We might need the remaining arguments, e.g. in the EOpFrexp case.
3419 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
John Kessenich32cfd492016-02-02 12:37:46 -07003420 id = builder.createBuiltinCall(typeId, stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07003421 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07003422 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06003423 case 0:
3424 // should all be handled by visitAggregate and createNoArgOperation
3425 assert(0);
3426 return 0;
3427 case 1:
3428 // should all be handled by createUnaryOperation
3429 assert(0);
3430 return 0;
3431 case 2:
3432 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
3433 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003434 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003435 // anything 3 or over doesn't have l-value operands, so all should be consumed
3436 assert(consumedOperands == operands.size());
3437 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06003438 break;
3439 }
3440 }
3441
John Kessenich55e7d112015-11-15 21:33:39 -07003442 // Decode the return types that were structures
3443 switch (op) {
3444 case glslang::EOpAddCarry:
3445 case glslang::EOpSubBorrow:
3446 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3447 id = builder.createCompositeExtract(id, typeId0, 0);
3448 break;
3449 case glslang::EOpUMulExtended:
3450 case glslang::EOpIMulExtended:
3451 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
3452 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
3453 break;
3454 case glslang::EOpFrexp:
David Neto8d63a3d2015-12-07 16:17:06 -05003455 assert(operands.size() == 2);
John Kessenich55e7d112015-11-15 21:33:39 -07003456 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
3457 id = builder.createCompositeExtract(id, typeId0, 0);
3458 break;
3459 default:
3460 break;
3461 }
3462
John Kessenich32cfd492016-02-02 12:37:46 -07003463 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003464}
3465
3466// Intrinsics with no arguments, no return value, and no precision.
3467spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op)
3468{
3469 // TODO: get the barrier operands correct
3470
3471 switch (op) {
3472 case glslang::EOpEmitVertex:
3473 builder.createNoResultOp(spv::OpEmitVertex);
3474 return 0;
3475 case glslang::EOpEndPrimitive:
3476 builder.createNoResultOp(spv::OpEndPrimitive);
3477 return 0;
3478 case glslang::EOpBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003479 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
3480 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06003481 return 0;
3482 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06003483 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06003484 return 0;
3485 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06003486 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003487 return 0;
3488 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06003489 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003490 return 0;
3491 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06003492 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003493 return 0;
3494 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07003495 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003496 return 0;
3497 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07003498 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06003499 return 0;
3500 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003501 spv::MissingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06003502 return 0;
3503 }
3504}
3505
3506spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
3507{
John Kessenich2f273362015-07-18 22:34:27 -06003508 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06003509 spv::Id id;
3510 if (symbolValues.end() != iter) {
3511 id = iter->second;
3512 return id;
3513 }
3514
3515 // it was not found, create it
3516 id = createSpvVariable(symbol);
3517 symbolValues[symbol->getId()] = id;
3518
3519 if (! symbol->getType().isStruct()) {
3520 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07003521 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07003522 if (symbol->getType().getQualifier().hasSpecConstantId())
3523 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06003524 if (symbol->getQualifier().hasLocation())
3525 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
3526 if (symbol->getQualifier().hasIndex())
3527 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
3528 if (symbol->getQualifier().hasComponent())
3529 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
3530 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003531 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003532 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003533 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003534 if (symbol->getQualifier().hasXfbBuffer())
3535 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3536 if (symbol->getQualifier().hasXfbOffset())
3537 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
3538 }
3539 }
3540
John Kesseniche0b6cad2015-12-24 10:30:13 -07003541 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenich92187592016-02-01 13:45:25 -07003542 if (symbol->getQualifier().hasStream()) {
3543 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06003544 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07003545 }
John Kessenich140f3df2015-06-26 16:58:36 -06003546 if (symbol->getQualifier().hasSet())
3547 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07003548 else if (IsDescriptorResource(symbol->getType())) {
3549 // default to 0
3550 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
3551 }
John Kessenich140f3df2015-06-26 16:58:36 -06003552 if (symbol->getQualifier().hasBinding())
3553 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07003554 if (symbol->getQualifier().hasAttachment())
3555 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06003556 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07003557 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06003558 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06003559 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06003560 if (symbol->getQualifier().hasXfbBuffer())
3561 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
3562 }
3563
3564 // built-in variable decorations
John Kessenich30669532015-08-06 22:02:24 -06003565 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn);
John Kessenich5e4b1242015-08-06 22:53:06 -06003566 if (builtIn != spv::BadValue)
John Kessenich92187592016-02-01 13:45:25 -07003567 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06003568
John Kessenich140f3df2015-06-26 16:58:36 -06003569 return id;
3570}
3571
John Kessenich55e7d112015-11-15 21:33:39 -07003572// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06003573void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
3574{
3575 if (dec != spv::BadValue)
3576 builder.addDecoration(id, dec);
3577}
3578
John Kessenich55e7d112015-11-15 21:33:39 -07003579// If 'dec' is valid, add a one-operand decoration to an object
3580void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
3581{
3582 if (dec != spv::BadValue)
3583 builder.addDecoration(id, dec, value);
3584}
3585
3586// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06003587void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
3588{
3589 if (dec != spv::BadValue)
3590 builder.addMemberDecoration(id, (unsigned)member, dec);
3591}
3592
John Kessenich92187592016-02-01 13:45:25 -07003593// If 'dec' is valid, add a one-operand decoration to a struct member
3594void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
3595{
3596 if (dec != spv::BadValue)
3597 builder.addMemberDecoration(id, (unsigned)member, dec, value);
3598}
3599
John Kessenich55e7d112015-11-15 21:33:39 -07003600// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07003601// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07003602//
3603// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
3604//
3605// Recursively walk the nodes. The nodes form a tree whose leaves are
3606// regular constants, which themselves are trees that createSpvConstant()
3607// recursively walks. So, this function walks the "top" of the tree:
3608// - emit specialization constant-building instructions for specConstant
3609// - when running into a non-spec-constant, switch to createSpvConstant()
3610spv::Id TGlslangToSpvTraverser::createSpvSpecConstant(const glslang::TIntermTyped& node)
3611{
3612 assert(node.getQualifier().storage == glslang::EvqConst);
3613
John Kessenich6c292d32016-02-15 20:58:50 -07003614 if (! node.getQualifier().specConstant) {
3615 // hand off to the non-spec-constant path
3616 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
3617 int nextConst = 0;
3618 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3619 nextConst, false);
3620 }
3621
3622 // We now know we have a specialization constant to build
3623
3624 if (node.getAsSymbolNode() && node.getQualifier().hasSpecConstantId()) {
3625 // this is a direct literal assigned to a layout(constant_id=) declaration
3626 int nextConst = 0;
3627 return createSpvConstant(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
3628 nextConst, true);
3629 } else {
3630 // gl_WorkgroupSize is a special case until the front-end handles hierarchical specialization constants,
3631 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
3632 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
3633 std::vector<spv::Id> dimConstId;
3634 for (int dim = 0; dim < 3; ++dim) {
3635 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
3636 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
3637 if (specConst)
3638 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
3639 }
3640 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
3641 } else {
3642 spv::MissingFunctionality("specialization-constant expression trees");
3643 return spv::NoResult;
3644 }
3645 }
John Kessenich55e7d112015-11-15 21:33:39 -07003646}
3647
John Kessenich140f3df2015-06-26 16:58:36 -06003648// Use 'consts' as the flattened glslang source of scalar constants to recursively
3649// build the aggregate SPIR-V constant.
3650//
3651// If there are not enough elements present in 'consts', 0 will be substituted;
3652// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
3653//
John Kessenich55e7d112015-11-15 21:33:39 -07003654spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06003655{
3656 // vector of constants for SPIR-V
3657 std::vector<spv::Id> spvConsts;
3658
3659 // Type is used for struct and array constants
3660 spv::Id typeId = convertGlslangToSpvType(glslangType);
3661
3662 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003663 glslang::TType elementType(glslangType, 0);
3664 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
John Kessenich55e7d112015-11-15 21:33:39 -07003665 spvConsts.push_back(createSpvConstant(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003666 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06003667 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06003668 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
John Kessenich55e7d112015-11-15 21:33:39 -07003669 spvConsts.push_back(createSpvConstant(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003670 } else if (glslangType.getStruct()) {
3671 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
3672 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
John Kessenich55e7d112015-11-15 21:33:39 -07003673 spvConsts.push_back(createSpvConstant(*iter->type, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06003674 } else if (glslangType.isVector()) {
3675 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
3676 bool zero = nextConst >= consts.size();
3677 switch (glslangType.getBasicType()) {
3678 case glslang::EbtInt:
3679 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
3680 break;
3681 case glslang::EbtUint:
3682 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
3683 break;
3684 case glslang::EbtFloat:
3685 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
3686 break;
3687 case glslang::EbtDouble:
3688 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
3689 break;
3690 case glslang::EbtBool:
3691 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
3692 break;
3693 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003694 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003695 break;
3696 }
3697 ++nextConst;
3698 }
3699 } else {
3700 // we have a non-aggregate (scalar) constant
3701 bool zero = nextConst >= consts.size();
3702 spv::Id scalar = 0;
3703 switch (glslangType.getBasicType()) {
3704 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07003705 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003706 break;
3707 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07003708 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003709 break;
3710 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07003711 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003712 break;
3713 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07003714 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003715 break;
3716 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07003717 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06003718 break;
3719 default:
John Kessenich55e7d112015-11-15 21:33:39 -07003720 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06003721 break;
3722 }
3723 ++nextConst;
3724 return scalar;
3725 }
3726
3727 return builder.makeCompositeConstant(typeId, spvConsts);
3728}
3729
John Kessenich7c1aa102015-10-15 13:29:11 -06003730// Return true if the node is a constant or symbol whose reading has no
3731// non-trivial observable cost or effect.
3732bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
3733{
3734 // don't know what this is
3735 if (node == nullptr)
3736 return false;
3737
3738 // a constant is safe
3739 if (node->getAsConstantUnion() != nullptr)
3740 return true;
3741
3742 // not a symbol means non-trivial
3743 if (node->getAsSymbolNode() == nullptr)
3744 return false;
3745
3746 // a symbol, depends on what's being read
3747 switch (node->getType().getQualifier().storage) {
3748 case glslang::EvqTemporary:
3749 case glslang::EvqGlobal:
3750 case glslang::EvqIn:
3751 case glslang::EvqInOut:
3752 case glslang::EvqConst:
3753 case glslang::EvqConstReadOnly:
3754 case glslang::EvqUniform:
3755 return true;
3756 default:
3757 return false;
3758 }
3759}
3760
3761// A node is trivial if it is a single operation with no side effects.
3762// Error on the side of saying non-trivial.
3763// Return true if trivial.
3764bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
3765{
3766 if (node == nullptr)
3767 return false;
3768
3769 // symbols and constants are trivial
3770 if (isTrivialLeaf(node))
3771 return true;
3772
3773 // otherwise, it needs to be a simple operation or one or two leaf nodes
3774
3775 // not a simple operation
3776 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
3777 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
3778 if (binaryNode == nullptr && unaryNode == nullptr)
3779 return false;
3780
3781 // not on leaf nodes
3782 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
3783 return false;
3784
3785 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
3786 return false;
3787 }
3788
3789 switch (node->getAsOperator()->getOp()) {
3790 case glslang::EOpLogicalNot:
3791 case glslang::EOpConvIntToBool:
3792 case glslang::EOpConvUintToBool:
3793 case glslang::EOpConvFloatToBool:
3794 case glslang::EOpConvDoubleToBool:
3795 case glslang::EOpEqual:
3796 case glslang::EOpNotEqual:
3797 case glslang::EOpLessThan:
3798 case glslang::EOpGreaterThan:
3799 case glslang::EOpLessThanEqual:
3800 case glslang::EOpGreaterThanEqual:
3801 case glslang::EOpIndexDirect:
3802 case glslang::EOpIndexDirectStruct:
3803 case glslang::EOpLogicalXor:
3804 case glslang::EOpAny:
3805 case glslang::EOpAll:
3806 return true;
3807 default:
3808 return false;
3809 }
3810}
3811
3812// Emit short-circuiting code, where 'right' is never evaluated unless
3813// the left side is true (for &&) or false (for ||).
3814spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
3815{
3816 spv::Id boolTypeId = builder.makeBoolType();
3817
3818 // emit left operand
3819 builder.clearAccessChain();
3820 left.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003821 spv::Id leftId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003822
3823 // Operands to accumulate OpPhi operands
3824 std::vector<spv::Id> phiOperands;
3825 // accumulate left operand's phi information
3826 phiOperands.push_back(leftId);
3827 phiOperands.push_back(builder.getBuildPoint()->getId());
3828
3829 // Make the two kinds of operation symmetric with a "!"
3830 // || => emit "if (! left) result = right"
3831 // && => emit "if ( left) result = right"
3832 //
3833 // TODO: this runtime "not" for || could be avoided by adding functionality
3834 // to 'builder' to have an "else" without an "then"
3835 if (op == glslang::EOpLogicalOr)
3836 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
3837
3838 // make an "if" based on the left value
3839 spv::Builder::If ifBuilder(leftId, builder);
3840
3841 // emit right operand as the "then" part of the "if"
3842 builder.clearAccessChain();
3843 right.traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003844 spv::Id rightId = builder.accessChainLoad(spv::NoPrecision, boolTypeId);
John Kessenich7c1aa102015-10-15 13:29:11 -06003845
3846 // accumulate left operand's phi information
3847 phiOperands.push_back(rightId);
3848 phiOperands.push_back(builder.getBuildPoint()->getId());
3849
3850 // finish the "if"
3851 ifBuilder.makeEndIf();
3852
3853 // phi together the two results
3854 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
3855}
3856
John Kessenich140f3df2015-06-26 16:58:36 -06003857}; // end anonymous namespace
3858
3859namespace glslang {
3860
John Kessenich68d78fd2015-07-12 19:28:10 -06003861void GetSpirvVersion(std::string& version)
3862{
John Kessenich9e55f632015-07-15 10:03:39 -06003863 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06003864 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07003865 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06003866 version = buf;
3867}
3868
John Kessenich140f3df2015-06-26 16:58:36 -06003869// Write SPIR-V out to a binary file
3870void OutputSpv(const std::vector<unsigned int>& spirv, const char* baseName)
3871{
3872 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06003873 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich140f3df2015-06-26 16:58:36 -06003874 for (int i = 0; i < (int)spirv.size(); ++i) {
3875 unsigned int word = spirv[i];
3876 out.write((const char*)&word, 4);
3877 }
3878 out.close();
3879}
3880
3881//
3882// Set up the glslang traversal
3883//
3884void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
3885{
3886 TIntermNode* root = intermediate.getTreeRoot();
3887
3888 if (root == 0)
3889 return;
3890
3891 glslang::GetThreadPoolAllocator().push();
3892
3893 TGlslangToSpvTraverser it(&intermediate);
3894
3895 root->traverse(&it);
3896
3897 it.dumpSpv(spirv);
3898
3899 glslang::GetThreadPoolAllocator().pop();
3900}
3901
3902}; // end namespace glslang