blob: 3597c0a3fb7d21af8b39a72fb117574556f0ecf5 [file] [log] [blame]
John Kessenich140f3df2015-06-26 16:58:36 -06001//
John Kessenich927608b2017-01-06 12:34:14 -07002// Copyright (C) 2014-2016 LunarG, Inc.
3// Copyright (C) 2015-2016 Google, Inc.
John Kessenich140f3df2015-06-26 16:58:36 -06004//
John Kessenich927608b2017-01-06 12:34:14 -07005// All rights reserved.
John Kessenich140f3df2015-06-26 16:58:36 -06006//
John Kessenich927608b2017-01-06 12:34:14 -07007// Redistribution and use in source and binary forms, with or without
8// modification, are permitted provided that the following conditions
9// are met:
John Kessenich140f3df2015-06-26 16:58:36 -060010//
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//
John Kessenich927608b2017-01-06 12:34:14 -070023// 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.
John Kessenich140f3df2015-06-26 16:58:36 -060035
36//
John Kessenich140f3df2015-06-26 16:58:36 -060037// Visit the nodes in the glslang intermediate tree representation to
38// translate them to SPIR-V.
39//
40
John Kessenich5e4b1242015-08-06 22:53:06 -060041#include "spirv.hpp"
John Kessenich140f3df2015-06-26 16:58:36 -060042#include "GlslangToSpv.h"
43#include "SpvBuilder.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060044namespace spv {
Rex Xu51596642016-09-21 18:56:12 +080045 #include "GLSL.std.450.h"
46 #include "GLSL.ext.KHR.h"
Rex Xu9d93a232016-05-05 12:30:44 +080047#ifdef AMD_EXTENSIONS
Rex Xu51596642016-09-21 18:56:12 +080048 #include "GLSL.ext.AMD.h"
Rex Xu9d93a232016-05-05 12:30:44 +080049#endif
chaoc0ad6a4e2016-12-19 16:29:34 -080050#ifdef NV_EXTENSIONS
51 #include "GLSL.ext.NV.h"
52#endif
John Kessenich5e4b1242015-08-06 22:53:06 -060053}
John Kessenich140f3df2015-06-26 16:58:36 -060054
55// Glslang includes
baldurk42169c52015-07-08 15:11:59 +020056#include "../glslang/MachineIndependent/localintermediate.h"
57#include "../glslang/MachineIndependent/SymbolTable.h"
John Kessenich5e4b1242015-08-06 22:53:06 -060058#include "../glslang/Include/Common.h"
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050059#include "../glslang/Include/revision.h"
John Kessenich140f3df2015-06-26 16:58:36 -060060
John Kessenich140f3df2015-06-26 16:58:36 -060061#include <fstream>
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -050062#include <iomanip>
Lei Zhang17535f72016-05-04 15:55:59 -040063#include <list>
64#include <map>
65#include <stack>
66#include <string>
67#include <vector>
John Kessenich140f3df2015-06-26 16:58:36 -060068
69namespace {
70
John Kessenich55e7d112015-11-15 21:33:39 -070071// For low-order part of the generator's magic number. Bump up
72// when there is a change in the style (e.g., if SSA form changes,
73// or a different instruction sequence to do something gets used).
74const int GeneratorVersion = 1;
John Kessenich140f3df2015-06-26 16:58:36 -060075
qining4c912612016-04-01 10:35:16 -040076namespace {
77class SpecConstantOpModeGuard {
78public:
79 SpecConstantOpModeGuard(spv::Builder* builder)
80 : builder_(builder) {
81 previous_flag_ = builder->isInSpecConstCodeGenMode();
qining4c912612016-04-01 10:35:16 -040082 }
83 ~SpecConstantOpModeGuard() {
84 previous_flag_ ? builder_->setToSpecConstCodeGenMode()
85 : builder_->setToNormalCodeGenMode();
86 }
qining40887662016-04-03 22:20:42 -040087 void turnOnSpecConstantOpMode() {
88 builder_->setToSpecConstCodeGenMode();
89 }
qining4c912612016-04-01 10:35:16 -040090
91private:
92 spv::Builder* builder_;
93 bool previous_flag_;
94};
95}
96
John Kessenich140f3df2015-06-26 16:58:36 -060097//
98// The main holder of information for translating glslang to SPIR-V.
99//
100// Derives from the AST walking base class.
101//
102class TGlslangToSpvTraverser : public glslang::TIntermTraverser {
103public:
Lei Zhang17535f72016-05-04 15:55:59 -0400104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger);
John Kessenichfca82622016-11-26 13:23:20 -0700105 virtual ~TGlslangToSpvTraverser() { }
John Kessenich140f3df2015-06-26 16:58:36 -0600106
107 bool visitAggregate(glslang::TVisit, glslang::TIntermAggregate*);
108 bool visitBinary(glslang::TVisit, glslang::TIntermBinary*);
109 void visitConstantUnion(glslang::TIntermConstantUnion*);
110 bool visitSelection(glslang::TVisit, glslang::TIntermSelection*);
111 bool visitSwitch(glslang::TVisit, glslang::TIntermSwitch*);
112 void visitSymbol(glslang::TIntermSymbol* symbol);
113 bool visitUnary(glslang::TVisit, glslang::TIntermUnary*);
114 bool visitLoop(glslang::TVisit, glslang::TIntermLoop*);
115 bool visitBranch(glslang::TVisit visit, glslang::TIntermBranch*);
116
John Kessenichfca82622016-11-26 13:23:20 -0700117 void finishSpv();
John Kessenich7ba63412015-12-20 17:37:07 -0700118 void dumpSpv(std::vector<unsigned int>& out);
John Kessenich140f3df2015-06-26 16:58:36 -0600119
120protected:
Rex Xu17ff3432016-10-14 17:41:45 +0800121 spv::Decoration TranslateInterpolationDecoration(const glslang::TQualifier& qualifier);
Rex Xubbceed72016-05-21 09:40:44 +0800122 spv::Decoration TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier);
David Netoa901ffe2016-06-08 14:11:40 +0100123 spv::BuiltIn TranslateBuiltInDecoration(glslang::TBuiltInVariable, bool memberDeclaration);
John Kessenich5d0fa972016-02-15 11:57:00 -0700124 spv::ImageFormat TranslateImageFormat(const glslang::TType& type);
steve-lunargf1709e72017-05-02 20:14:50 -0600125 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600126 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600127 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
128 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600129 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
130 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
131 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600132 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700133 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600134 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600135 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
136 glslang::TLayoutPacking, const glslang::TQualifier&);
137 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
138 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700139 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700140 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800141 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600142 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700143 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700144 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
145 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 void updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset, glslang::TLayoutPacking, glslang::TLayoutMatrix);
David Netoa901ffe2016-06-08 14:11:40 +0100147 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600148
John Kessenich6fccb3c2016-09-19 16:01:41 -0600149 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600150 void makeFunctions(const glslang::TIntermSequence&);
151 void makeGlobalInitializers(const glslang::TIntermSequence&);
152 void visitFunctions(const glslang::TIntermSequence&);
153 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800154 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600155 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
156 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600157 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
158
qining25262b32016-05-06 17:25:16 -0400159 spv::Id createBinaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right, glslang::TBasicType typeProxy, bool reduceComparison = true);
160 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
161 spv::Id createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu2bbbe062016-08-23 15:41:05 +0800162 spv::Id createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand,glslang::TBasicType typeProxy);
Rex Xu73e3ce72016-04-27 18:48:17 +0800163 spv::Id createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destTypeId, spv::Id operand, glslang::TBasicType typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -0600164 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800165 spv::Id createAtomicOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu51596642016-09-21 18:56:12 +0800166 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800167 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600168 spv::Id createMiscOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu9d93a232016-05-05 12:30:44 +0800169 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600170 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
171 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700172 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600173 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400175 spv::Id createSpvConstant(const glslang::TIntermTyped&);
176 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600177 bool isTrivialLeaf(const glslang::TIntermTyped* node);
178 bool isTrivial(const glslang::TIntermTyped* node);
179 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800180 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600181
182 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600183 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700184 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600185 int sequenceDepth;
186
Lei Zhang17535f72016-05-04 15:55:59 -0400187 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400188
John Kessenich140f3df2015-06-26 16:58:36 -0600189 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
190 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700191 bool inEntryPoint;
192 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700193 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 -0700194 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600195 const glslang::TIntermediate* glslangIntermediate;
196 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800197 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600198
John Kessenich2f273362015-07-18 22:34:27 -0600199 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600200 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700202 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600203 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 -0600204 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600205};
206
207//
208// Helper functions for translating glslang representations to SPIR-V enumerants.
209//
210
211// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700212spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600213{
John Kessenich66e2faf2016-03-12 18:34:36 -0700214 switch (source) {
215 case glslang::EShSourceGlsl:
216 switch (profile) {
217 case ENoProfile:
218 case ECoreProfile:
219 case ECompatibilityProfile:
220 return spv::SourceLanguageGLSL;
221 case EEsProfile:
222 return spv::SourceLanguageESSL;
223 default:
224 return spv::SourceLanguageUnknown;
225 }
226 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600227 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600228 default:
229 return spv::SourceLanguageUnknown;
230 }
231}
232
233// Translate glslang language (stage) to SPIR-V execution model.
234spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
235{
236 switch (stage) {
237 case EShLangVertex: return spv::ExecutionModelVertex;
238 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
239 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
240 case EShLangGeometry: return spv::ExecutionModelGeometry;
241 case EShLangFragment: return spv::ExecutionModelFragment;
242 case EShLangCompute: return spv::ExecutionModelGLCompute;
243 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700244 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600245 return spv::ExecutionModelFragment;
246 }
247}
248
John Kessenich140f3df2015-06-26 16:58:36 -0600249// Translate glslang sampler type to SPIR-V dimensionality.
250spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
251{
252 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700253 case glslang::Esd1D: return spv::Dim1D;
254 case glslang::Esd2D: return spv::Dim2D;
255 case glslang::Esd3D: return spv::Dim3D;
256 case glslang::EsdCube: return spv::DimCube;
257 case glslang::EsdRect: return spv::DimRect;
258 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700259 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600260 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700261 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600262 return spv::Dim2D;
263 }
264}
265
John Kessenichf6640762016-08-01 19:44:00 -0600266// Translate glslang precision to SPIR-V precision decorations.
267spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600268{
John Kessenichf6640762016-08-01 19:44:00 -0600269 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700270 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600271 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600272 default:
273 return spv::NoPrecision;
274 }
275}
276
John Kessenichf6640762016-08-01 19:44:00 -0600277// Translate glslang type to SPIR-V precision decorations.
278spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
279{
280 return TranslatePrecisionDecoration(type.getQualifier().precision);
281}
282
John Kessenich140f3df2015-06-26 16:58:36 -0600283// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600284spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600285{
286 if (type.getBasicType() == glslang::EbtBlock) {
287 switch (type.getQualifier().storage) {
288 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600289 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600290 case glslang::EvqVaryingIn: return spv::DecorationBlock;
291 case glslang::EvqVaryingOut: return spv::DecorationBlock;
292 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700293 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600294 break;
295 }
296 }
297
John Kessenich4016e382016-07-15 11:53:56 -0600298 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600299}
300
Rex Xu1da878f2016-02-21 20:59:01 +0800301// Translate glslang type to SPIR-V memory decorations.
302void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
303{
304 if (qualifier.coherent)
305 memory.push_back(spv::DecorationCoherent);
306 if (qualifier.volatil)
307 memory.push_back(spv::DecorationVolatile);
308 if (qualifier.restrict)
309 memory.push_back(spv::DecorationRestrict);
310 if (qualifier.readonly)
311 memory.push_back(spv::DecorationNonWritable);
312 if (qualifier.writeonly)
313 memory.push_back(spv::DecorationNonReadable);
314}
315
John Kessenich140f3df2015-06-26 16:58:36 -0600316// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700317spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600318{
319 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700320 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600321 case glslang::ElmRowMajor:
322 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700323 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600324 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 default:
326 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600327 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600328 }
329 } else {
330 switch (type.getBasicType()) {
331 default:
John Kessenich4016e382016-07-15 11:53:56 -0600332 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600333 break;
334 case glslang::EbtBlock:
335 switch (type.getQualifier().storage) {
336 case glslang::EvqUniform:
337 case glslang::EvqBuffer:
338 switch (type.getQualifier().layoutPacking) {
339 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600340 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
341 default:
John Kessenich4016e382016-07-15 11:53:56 -0600342 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600343 }
344 case glslang::EvqVaryingIn:
345 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700346 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600347 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600348 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700349 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600350 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600351 }
352 }
353 }
354}
355
356// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600357// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700358// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800359spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600360{
Rex Xubbceed72016-05-21 09:40:44 +0800361 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700362 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600363 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800364 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700365 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700366 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600367 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800368#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800369 else if (qualifier.explicitInterp) {
370 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800371 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800372 }
Rex Xu9d93a232016-05-05 12:30:44 +0800373#endif
Rex Xubbceed72016-05-21 09:40:44 +0800374 else
John Kessenich4016e382016-07-15 11:53:56 -0600375 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800376}
377
378// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600379// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800380// should be applied.
381spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
382{
383 if (qualifier.patch)
384 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700385 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600386 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700387 else if (qualifier.sample) {
388 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600389 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700390 } else
John Kessenich4016e382016-07-15 11:53:56 -0600391 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600392}
393
John Kessenich92187592016-02-01 13:45:25 -0700394// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700395spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600396{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600398 return spv::DecorationInvariant;
399 else
John Kessenich4016e382016-07-15 11:53:56 -0600400 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600401}
402
qining9220dbb2016-05-04 17:34:38 -0400403// If glslang type is noContraction, return SPIR-V NoContraction decoration.
404spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
405{
406 if (qualifier.noContraction)
407 return spv::DecorationNoContraction;
408 else
John Kessenich4016e382016-07-15 11:53:56 -0600409 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400410}
411
David Netoa901ffe2016-06-08 14:11:40 +0100412// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
413// associated capabilities when required. For some built-in variables, a capability
414// is generated only when using the variable in an executable instruction, but not when
415// just declaring a struct member variable with it. This is true for PointSize,
416// ClipDistance, and CullDistance.
417spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600418{
419 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700420 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600421 // Defer adding the capability until the built-in is actually used.
422 if (! memberDeclaration) {
423 switch (glslangIntermediate->getStage()) {
424 case EShLangGeometry:
425 builder.addCapability(spv::CapabilityGeometryPointSize);
426 break;
427 case EShLangTessControl:
428 case EShLangTessEvaluation:
429 builder.addCapability(spv::CapabilityTessellationPointSize);
430 break;
431 default:
432 break;
433 }
John Kessenich92187592016-02-01 13:45:25 -0700434 }
435 return spv::BuiltInPointSize;
436
John Kessenichebb50532016-05-16 19:22:05 -0600437 // These *Distance capabilities logically belong here, but if the member is declared and
438 // then never used, consumers of SPIR-V prefer the capability not be declared.
439 // They are now generated when used, rather than here when declared.
440 // Potentially, the specification should be more clear what the minimum
441 // use needed is to trigger the capability.
442 //
John Kessenich92187592016-02-01 13:45:25 -0700443 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100444 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800445 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700446 return spv::BuiltInClipDistance;
447
448 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100449 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800450 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700451 return spv::BuiltInCullDistance;
452
453 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800454 if (!memberDeclaration) {
455 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800456#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800457 if (glslangIntermediate->getStage() == EShLangVertex ||
458 glslangIntermediate->getStage() == EShLangTessControl ||
459 glslangIntermediate->getStage() == EShLangTessEvaluation) {
460
461 builder.addExtension(spv::E_SPV_NV_viewport_array2);
462 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
463 }
chaoc771d89f2017-01-13 01:10:53 -0800464#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800465 }
John Kessenich92187592016-02-01 13:45:25 -0700466 return spv::BuiltInViewportIndex;
467
John Kessenich5e801132016-02-15 11:09:46 -0700468 case glslang::EbvSampleId:
469 builder.addCapability(spv::CapabilitySampleRateShading);
470 return spv::BuiltInSampleId;
471
472 case glslang::EbvSamplePosition:
473 builder.addCapability(spv::CapabilitySampleRateShading);
474 return spv::BuiltInSamplePosition;
475
476 case glslang::EbvSampleMask:
477 builder.addCapability(spv::CapabilitySampleRateShading);
478 return spv::BuiltInSampleMask;
479
John Kessenich78a45572016-07-08 14:05:15 -0600480 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800481 if (!memberDeclaration) {
482 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800483#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800484 if (glslangIntermediate->getStage() == EShLangVertex ||
485 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 glslangIntermediate->getStage() == EShLangTessEvaluation) {
487
chaoc771d89f2017-01-13 01:10:53 -0800488 builder.addExtension(spv::E_SPV_NV_viewport_array2);
489 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
490 }
chaoc771d89f2017-01-13 01:10:53 -0800491#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800492 }
493
John Kessenich78a45572016-07-08 14:05:15 -0600494 return spv::BuiltInLayer;
495
John Kessenich140f3df2015-06-26 16:58:36 -0600496 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvVertexId: return spv::BuiltInVertexId;
498 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700499 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
500 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800501
John Kessenichda581a22015-10-14 14:10:30 -0600502 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800503 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
504 builder.addCapability(spv::CapabilityDrawParameters);
505 return spv::BuiltInBaseVertex;
506
John Kessenichda581a22015-10-14 14:10:30 -0600507 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800508 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
509 builder.addCapability(spv::CapabilityDrawParameters);
510 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200511
John Kessenichda581a22015-10-14 14:10:30 -0600512 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800513 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
514 builder.addCapability(spv::CapabilityDrawParameters);
515 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200516
517 case glslang::EbvPrimitiveId:
518 if (glslangIntermediate->getStage() == EShLangFragment)
519 builder.addCapability(spv::CapabilityGeometry);
520 return spv::BuiltInPrimitiveId;
521
John Kessenich140f3df2015-06-26 16:58:36 -0600522 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
524 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
525 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
526 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
527 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
528 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
529 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600530 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
531 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
532 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
533 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
534 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
535 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
536 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
537 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800538
Rex Xu574ab042016-04-14 16:53:07 +0800539 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800540 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800541 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
542 return spv::BuiltInSubgroupSize;
543
Rex Xu574ab042016-04-14 16:53:07 +0800544 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800545 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800546 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
547 return spv::BuiltInSubgroupLocalInvocationId;
548
Rex Xu574ab042016-04-14 16:53:07 +0800549 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800550 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
551 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
552 return spv::BuiltInSubgroupEqMaskKHR;
553
Rex Xu574ab042016-04-14 16:53:07 +0800554 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800555 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
556 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
557 return spv::BuiltInSubgroupGeMaskKHR;
558
Rex Xu574ab042016-04-14 16:53:07 +0800559 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800560 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
561 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
562 return spv::BuiltInSubgroupGtMaskKHR;
563
Rex Xu574ab042016-04-14 16:53:07 +0800564 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800565 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
566 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
567 return spv::BuiltInSubgroupLeMaskKHR;
568
Rex Xu574ab042016-04-14 16:53:07 +0800569 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800570 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
571 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
572 return spv::BuiltInSubgroupLtMaskKHR;
573
Rex Xu9d93a232016-05-05 12:30:44 +0800574#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800575 case glslang::EbvBaryCoordNoPersp:
576 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
577 return spv::BuiltInBaryCoordNoPerspAMD;
578
579 case glslang::EbvBaryCoordNoPerspCentroid:
580 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
581 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
582
583 case glslang::EbvBaryCoordNoPerspSample:
584 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
585 return spv::BuiltInBaryCoordNoPerspSampleAMD;
586
587 case glslang::EbvBaryCoordSmooth:
588 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
589 return spv::BuiltInBaryCoordSmoothAMD;
590
591 case glslang::EbvBaryCoordSmoothCentroid:
592 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
593 return spv::BuiltInBaryCoordSmoothCentroidAMD;
594
595 case glslang::EbvBaryCoordSmoothSample:
596 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
597 return spv::BuiltInBaryCoordSmoothSampleAMD;
598
599 case glslang::EbvBaryCoordPullModel:
600 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
601 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800602#endif
chaoc771d89f2017-01-13 01:10:53 -0800603
John Kessenich6c8aaac2017-02-27 01:20:51 -0700604 case glslang::EbvDeviceIndex:
605 builder.addExtension(spv::E_SPV_KHR_device_group);
606 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700607 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700608
609 case glslang::EbvViewIndex:
610 builder.addExtension(spv::E_SPV_KHR_multiview);
611 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700612 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700613
chaoc771d89f2017-01-13 01:10:53 -0800614#ifdef NV_EXTENSIONS
615 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800616 if (!memberDeclaration) {
617 builder.addExtension(spv::E_SPV_NV_viewport_array2);
618 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
619 }
chaoc771d89f2017-01-13 01:10:53 -0800620 return spv::BuiltInViewportMaskNV;
621 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800622 if (!memberDeclaration) {
623 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
624 builder.addCapability(spv::CapabilityShaderStereoViewNV);
625 }
chaoc771d89f2017-01-13 01:10:53 -0800626 return spv::BuiltInSecondaryPositionNV;
627 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800628 if (!memberDeclaration) {
629 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
630 builder.addCapability(spv::CapabilityShaderStereoViewNV);
631 }
chaoc771d89f2017-01-13 01:10:53 -0800632 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800633 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800634 if (!memberDeclaration) {
635 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
636 builder.addCapability(spv::CapabilityPerViewAttributesNV);
637 }
chaocdf3956c2017-02-14 14:52:34 -0800638 return spv::BuiltInPositionPerViewNV;
639 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800640 if (!memberDeclaration) {
641 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
642 builder.addCapability(spv::CapabilityPerViewAttributesNV);
643 }
chaocdf3956c2017-02-14 14:52:34 -0800644 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800645#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800646 default:
647 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600648 }
649}
650
Rex Xufc618912015-09-09 16:42:49 +0800651// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700652spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800653{
654 assert(type.getBasicType() == glslang::EbtSampler);
655
John Kessenich5d0fa972016-02-15 11:57:00 -0700656 // Check for capabilities
657 switch (type.getQualifier().layoutFormat) {
658 case glslang::ElfRg32f:
659 case glslang::ElfRg16f:
660 case glslang::ElfR11fG11fB10f:
661 case glslang::ElfR16f:
662 case glslang::ElfRgba16:
663 case glslang::ElfRgb10A2:
664 case glslang::ElfRg16:
665 case glslang::ElfRg8:
666 case glslang::ElfR16:
667 case glslang::ElfR8:
668 case glslang::ElfRgba16Snorm:
669 case glslang::ElfRg16Snorm:
670 case glslang::ElfRg8Snorm:
671 case glslang::ElfR16Snorm:
672 case glslang::ElfR8Snorm:
673
674 case glslang::ElfRg32i:
675 case glslang::ElfRg16i:
676 case glslang::ElfRg8i:
677 case glslang::ElfR16i:
678 case glslang::ElfR8i:
679
680 case glslang::ElfRgb10a2ui:
681 case glslang::ElfRg32ui:
682 case glslang::ElfRg16ui:
683 case glslang::ElfRg8ui:
684 case glslang::ElfR16ui:
685 case glslang::ElfR8ui:
686 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
687 break;
688
689 default:
690 break;
691 }
692
693 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800694 switch (type.getQualifier().layoutFormat) {
695 case glslang::ElfNone: return spv::ImageFormatUnknown;
696 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
697 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
698 case glslang::ElfR32f: return spv::ImageFormatR32f;
699 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
700 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
701 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
702 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
703 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
704 case glslang::ElfR16f: return spv::ImageFormatR16f;
705 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
706 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
707 case glslang::ElfRg16: return spv::ImageFormatRg16;
708 case glslang::ElfRg8: return spv::ImageFormatRg8;
709 case glslang::ElfR16: return spv::ImageFormatR16;
710 case glslang::ElfR8: return spv::ImageFormatR8;
711 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
712 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
713 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
714 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
715 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
716 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
717 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
718 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
719 case glslang::ElfR32i: return spv::ImageFormatR32i;
720 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
721 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
722 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
723 case glslang::ElfR16i: return spv::ImageFormatR16i;
724 case glslang::ElfR8i: return spv::ImageFormatR8i;
725 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
726 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
727 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
728 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
729 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
730 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
731 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
732 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
733 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
734 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600735 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800736 }
737}
738
steve-lunargf1709e72017-05-02 20:14:50 -0600739spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
740{
741 switch (loopControl) {
742 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
743 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
744 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
745 // TODO: DependencyInfinite
746 // TODO: DependencyLength
747 default: return spv::LoopControlMaskNone;
748 }
749}
750
John Kessenicha5c5fb62017-05-05 05:09:58 -0600751// Translate glslang type to SPIR-V storage class.
752spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
753{
754 if (type.getQualifier().isPipeInput())
755 return spv::StorageClassInput;
756 else if (type.getQualifier().isPipeOutput())
757 return spv::StorageClassOutput;
758 else if (type.getBasicType() == glslang::EbtAtomicUint)
759 return spv::StorageClassAtomicCounter;
760 else if (type.containsOpaque())
761 return spv::StorageClassUniformConstant;
762 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
763 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
764 return spv::StorageClassStorageBuffer;
765 } else if (type.getQualifier().isUniformOrBuffer()) {
766 if (type.getQualifier().layoutPushConstant)
767 return spv::StorageClassPushConstant;
768 if (type.getBasicType() == glslang::EbtBlock)
769 return spv::StorageClassUniform;
770 else
771 return spv::StorageClassUniformConstant;
772 } else {
773 switch (type.getQualifier().storage) {
774 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
775 case glslang::EvqGlobal: return spv::StorageClassPrivate;
776 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
777 case glslang::EvqTemporary: return spv::StorageClassFunction;
778 default:
779 assert(0);
780 return spv::StorageClassFunction;
781 }
782 }
783}
784
qining25262b32016-05-06 17:25:16 -0400785// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700786// descriptor set.
787bool IsDescriptorResource(const glslang::TType& type)
788{
John Kessenichf7497e22016-03-08 21:36:22 -0700789 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700790 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700791 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700792
793 // non block...
794 // basically samplerXXX/subpass/sampler/texture are all included
795 // if they are the global-scope-class, not the function parameter
796 // (or local, if they ever exist) class.
797 if (type.getBasicType() == glslang::EbtSampler)
798 return type.getQualifier().isUniformOrBuffer();
799
800 // None of the above.
801 return false;
802}
803
John Kesseniche0b6cad2015-12-24 10:30:13 -0700804void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
805{
806 if (child.layoutMatrix == glslang::ElmNone)
807 child.layoutMatrix = parent.layoutMatrix;
808
809 if (parent.invariant)
810 child.invariant = true;
811 if (parent.nopersp)
812 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800813#ifdef AMD_EXTENSIONS
814 if (parent.explicitInterp)
815 child.explicitInterp = true;
816#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700817 if (parent.flat)
818 child.flat = true;
819 if (parent.centroid)
820 child.centroid = true;
821 if (parent.patch)
822 child.patch = true;
823 if (parent.sample)
824 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800825 if (parent.coherent)
826 child.coherent = true;
827 if (parent.volatil)
828 child.volatil = true;
829 if (parent.restrict)
830 child.restrict = true;
831 if (parent.readonly)
832 child.readonly = true;
833 if (parent.writeonly)
834 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700835}
836
John Kessenichf2b7f332016-09-01 17:05:23 -0600837bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700838{
John Kessenich7b9fa252016-01-21 18:56:57 -0700839 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600840 // - struct members might inherit from a struct declaration
841 // (note that non-block structs don't explicitly inherit,
842 // only implicitly, meaning no decoration involved)
843 // - affect decorations on the struct members
844 // (note smooth does not, and expecting something like volatile
845 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700846 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600847 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700848}
849
John Kessenich140f3df2015-06-26 16:58:36 -0600850//
851// Implement the TGlslangToSpvTraverser class.
852//
853
Lei Zhang17535f72016-05-04 15:55:59 -0400854TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate, spv::SpvBuildLogger* buildLogger)
John Kesseniched33e052016-10-06 12:59:51 -0600855 : TIntermTraverser(true, false, true), shaderEntry(nullptr), currentFunction(nullptr),
856 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400857 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700858 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600859 glslangIntermediate(glslangIntermediate)
860{
861 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
862
863 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700864 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich140f3df2015-06-26 16:58:36 -0600865 stdBuiltins = builder.import("GLSL.std.450");
866 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600867 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
868 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600869
870 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600871 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
872 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600873 builder.addSourceExtension(it->c_str());
874
875 // Add the top-level modes for this shader.
876
John Kessenich92187592016-02-01 13:45:25 -0700877 if (glslangIntermediate->getXfbMode()) {
878 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600879 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700880 }
John Kessenich140f3df2015-06-26 16:58:36 -0600881
882 unsigned int mode;
883 switch (glslangIntermediate->getStage()) {
884 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600885 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600886 break;
887
steve-lunarge7412492017-03-23 11:56:07 -0600888 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600889 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600890 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600891
steve-lunarge7412492017-03-23 11:56:07 -0600892 glslang::TLayoutGeometry primitive;
893
894 if (glslangIntermediate->getStage() == EShLangTessControl) {
895 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
896 primitive = glslangIntermediate->getOutputPrimitive();
897 } else {
898 primitive = glslangIntermediate->getInputPrimitive();
899 }
900
901 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700902 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
903 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
904 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600905 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600906 }
John Kessenich4016e382016-07-15 11:53:56 -0600907 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600908 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
909
John Kesseniche6903322015-10-13 16:29:02 -0600910 switch (glslangIntermediate->getVertexSpacing()) {
911 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
912 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
913 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600914 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600915 }
John Kessenich4016e382016-07-15 11:53:56 -0600916 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600917 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
918
919 switch (glslangIntermediate->getVertexOrder()) {
920 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
921 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600922 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600923 }
John Kessenich4016e382016-07-15 11:53:56 -0600924 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600925 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
926
927 if (glslangIntermediate->getPointMode())
928 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600929 break;
930
931 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600932 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600933 switch (glslangIntermediate->getInputPrimitive()) {
934 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
935 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
936 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700937 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600938 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600939 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600940 }
John Kessenich4016e382016-07-15 11:53:56 -0600941 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600942 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600943
John Kessenich140f3df2015-06-26 16:58:36 -0600944 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
945
946 switch (glslangIntermediate->getOutputPrimitive()) {
947 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
948 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
949 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600950 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600951 }
John Kessenich4016e382016-07-15 11:53:56 -0600952 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600953 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
954 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
955 break;
956
957 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600958 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600959 if (glslangIntermediate->getPixelCenterInteger())
960 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600961
John Kessenich140f3df2015-06-26 16:58:36 -0600962 if (glslangIntermediate->getOriginUpperLeft())
963 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600964 else
965 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600966
967 if (glslangIntermediate->getEarlyFragmentTests())
968 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
969
970 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600971 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
972 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600973 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600974 }
John Kessenich4016e382016-07-15 11:53:56 -0600975 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600976 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
977
978 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
979 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600980 break;
981
982 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600983 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600984 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
985 glslangIntermediate->getLocalSize(1),
986 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600987 break;
988
989 default:
990 break;
991 }
John Kessenich140f3df2015-06-26 16:58:36 -0600992}
993
John Kessenichfca82622016-11-26 13:23:20 -0700994// Finish creating SPV, after the traversal is complete.
995void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -0700996{
John Kessenich517fe7a2016-11-26 13:31:47 -0700997 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -0700998 builder.setBuildPoint(shaderEntry->getLastBlock());
999 builder.leaveFunction();
1000 }
1001
John Kessenich7ba63412015-12-20 17:37:07 -07001002 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001003 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1004 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001005
qiningda397332016-03-09 19:54:03 -05001006 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001007}
1008
John Kessenichfca82622016-11-26 13:23:20 -07001009// Write the SPV into 'out'.
1010void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001011{
John Kessenichfca82622016-11-26 13:23:20 -07001012 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001013}
1014
1015//
1016// Implement the traversal functions.
1017//
1018// Return true from interior nodes to have the external traversal
1019// continue on to children. Return false if children were
1020// already processed.
1021//
1022
1023//
qining25262b32016-05-06 17:25:16 -04001024// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001025// - uniform/input reads
1026// - output writes
1027// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1028// - something simple that degenerates into the last bullet
1029//
1030void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1031{
qining75d1d802016-04-06 14:42:01 -04001032 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1033 if (symbol->getType().getQualifier().isSpecConstant())
1034 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1035
John Kessenich140f3df2015-06-26 16:58:36 -06001036 // getSymbolId() will set up all the IO decorations on the first call.
1037 // Formal function parameters were mapped during makeFunctions().
1038 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001039
1040 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1041 if (builder.isPointer(id)) {
1042 spv::StorageClass sc = builder.getStorageClass(id);
1043 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1044 iOSet.insert(id);
1045 }
1046
1047 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001048 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001049 // Prepare to generate code for the access
1050
1051 // L-value chains will be computed left to right. We're on the symbol now,
1052 // which is the left-most part of the access chain, so now is "clear" time,
1053 // followed by setting the base.
1054 builder.clearAccessChain();
1055
1056 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001057 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001058 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001059 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001060 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001061 // These are also pure R-values.
1062 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001063 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001064 builder.setAccessChainRValue(id);
1065 else
1066 builder.setAccessChainLValue(id);
1067 }
1068}
1069
1070bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1071{
qining40887662016-04-03 22:20:42 -04001072 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1073 if (node->getType().getQualifier().isSpecConstant())
1074 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1075
John Kessenich140f3df2015-06-26 16:58:36 -06001076 // First, handle special cases
1077 switch (node->getOp()) {
1078 case glslang::EOpAssign:
1079 case glslang::EOpAddAssign:
1080 case glslang::EOpSubAssign:
1081 case glslang::EOpMulAssign:
1082 case glslang::EOpVectorTimesMatrixAssign:
1083 case glslang::EOpVectorTimesScalarAssign:
1084 case glslang::EOpMatrixTimesScalarAssign:
1085 case glslang::EOpMatrixTimesMatrixAssign:
1086 case glslang::EOpDivAssign:
1087 case glslang::EOpModAssign:
1088 case glslang::EOpAndAssign:
1089 case glslang::EOpInclusiveOrAssign:
1090 case glslang::EOpExclusiveOrAssign:
1091 case glslang::EOpLeftShiftAssign:
1092 case glslang::EOpRightShiftAssign:
1093 // A bin-op assign "a += b" means the same thing as "a = a + b"
1094 // where a is evaluated before b. For a simple assignment, GLSL
1095 // says to evaluate the left before the right. So, always, left
1096 // node then right node.
1097 {
1098 // get the left l-value, save it away
1099 builder.clearAccessChain();
1100 node->getLeft()->traverse(this);
1101 spv::Builder::AccessChain lValue = builder.getAccessChain();
1102
1103 // evaluate the right
1104 builder.clearAccessChain();
1105 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001106 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001107
1108 if (node->getOp() != glslang::EOpAssign) {
1109 // the left is also an r-value
1110 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001111 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001112
1113 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001114 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001115 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001116 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1117 node->getType().getBasicType());
1118
1119 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001120 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001121 }
1122
1123 // store the result
1124 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001125 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001126
1127 // assignments are expressions having an rValue after they are evaluated...
1128 builder.clearAccessChain();
1129 builder.setAccessChainRValue(rValue);
1130 }
1131 return false;
1132 case glslang::EOpIndexDirect:
1133 case glslang::EOpIndexDirectStruct:
1134 {
1135 // Get the left part of the access chain.
1136 node->getLeft()->traverse(this);
1137
1138 // Add the next element in the chain
1139
David Netoa901ffe2016-06-08 14:11:40 +01001140 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001141 if (! node->getLeft()->getType().isArray() &&
1142 node->getLeft()->getType().isVector() &&
1143 node->getOp() == glslang::EOpIndexDirect) {
1144 // This is essentially a hard-coded vector swizzle of size 1,
1145 // so short circuit the access-chain stuff with a swizzle.
1146 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001147 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001148 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001149 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001150 int spvIndex = glslangIndex;
1151 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1152 node->getOp() == glslang::EOpIndexDirectStruct)
1153 {
1154 // This may be, e.g., an anonymous block-member selection, which generally need
1155 // index remapping due to hidden members in anonymous blocks.
1156 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1157 assert(remapper.size() > 0);
1158 spvIndex = remapper[glslangIndex];
1159 }
John Kessenichebb50532016-05-16 19:22:05 -06001160
David Netoa901ffe2016-06-08 14:11:40 +01001161 // normal case for indexing array or structure or block
1162 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1163
1164 // Add capabilities here for accessing PointSize and clip/cull distance.
1165 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001166 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001167 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001168 }
1169 }
1170 return false;
1171 case glslang::EOpIndexIndirect:
1172 {
1173 // Structure or array or vector indirection.
1174 // Will use native SPIR-V access-chain for struct and array indirection;
1175 // matrices are arrays of vectors, so will also work for a matrix.
1176 // Will use the access chain's 'component' for variable index into a vector.
1177
1178 // This adapter is building access chains left to right.
1179 // Set up the access chain to the left.
1180 node->getLeft()->traverse(this);
1181
1182 // save it so that computing the right side doesn't trash it
1183 spv::Builder::AccessChain partial = builder.getAccessChain();
1184
1185 // compute the next index in the chain
1186 builder.clearAccessChain();
1187 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001188 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001189
1190 // restore the saved access chain
1191 builder.setAccessChain(partial);
1192
1193 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001194 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001195 else
John Kessenichfa668da2015-09-13 14:46:30 -06001196 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001197 }
1198 return false;
1199 case glslang::EOpVectorSwizzle:
1200 {
1201 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001202 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001203 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001204 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001205 }
1206 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001207 case glslang::EOpMatrixSwizzle:
1208 logger->missingFunctionality("matrix swizzle");
1209 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001210 case glslang::EOpLogicalOr:
1211 case glslang::EOpLogicalAnd:
1212 {
1213
1214 // These may require short circuiting, but can sometimes be done as straight
1215 // binary operations. The right operand must be short circuited if it has
1216 // side effects, and should probably be if it is complex.
1217 if (isTrivial(node->getRight()->getAsTyped()))
1218 break; // handle below as a normal binary operation
1219 // otherwise, we need to do dynamic short circuiting on the right operand
1220 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1221 builder.clearAccessChain();
1222 builder.setAccessChainRValue(result);
1223 }
1224 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001225 default:
1226 break;
1227 }
1228
1229 // Assume generic binary op...
1230
John Kessenich32cfd492016-02-02 12:37:46 -07001231 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001232 builder.clearAccessChain();
1233 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001234 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001235
John Kessenich32cfd492016-02-02 12:37:46 -07001236 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001237 builder.clearAccessChain();
1238 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001239 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001240
John Kessenich32cfd492016-02-02 12:37:46 -07001241 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001242 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001243 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001244 convertGlslangToSpvType(node->getType()), left, right,
1245 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001246
John Kessenich50e57562015-12-21 21:21:11 -07001247 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001248 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001249 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001250 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001251 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001252 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001253 return false;
1254 }
John Kessenich140f3df2015-06-26 16:58:36 -06001255}
1256
1257bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1258{
qining40887662016-04-03 22:20:42 -04001259 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1260 if (node->getType().getQualifier().isSpecConstant())
1261 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1262
John Kessenichfc51d282015-08-19 13:34:18 -06001263 spv::Id result = spv::NoResult;
1264
1265 // try texturing first
1266 result = createImageTextureFunctionCall(node);
1267 if (result != spv::NoResult) {
1268 builder.clearAccessChain();
1269 builder.setAccessChainRValue(result);
1270
1271 return false; // done with this node
1272 }
1273
1274 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001275
1276 if (node->getOp() == glslang::EOpArrayLength) {
1277 // Quite special; won't want to evaluate the operand.
1278
1279 // Normal .length() would have been constant folded by the front-end.
1280 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001281 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001282 assert(node->getOperand()->getType().isRuntimeSizedArray());
1283 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1284 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001285 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1286 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001287
1288 builder.clearAccessChain();
1289 builder.setAccessChainRValue(length);
1290
1291 return false;
1292 }
1293
John Kessenichfc51d282015-08-19 13:34:18 -06001294 // Start by evaluating the operand
1295
John Kessenich8c8505c2016-07-26 12:50:38 -06001296 // Does it need a swizzle inversion? If so, evaluation is inverted;
1297 // operate first on the swizzle base, then apply the swizzle.
1298 spv::Id invertedType = spv::NoType;
1299 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1300 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1301 invertedType = getInvertedSwizzleType(*node->getOperand());
1302
John Kessenich140f3df2015-06-26 16:58:36 -06001303 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001304 if (invertedType != spv::NoType)
1305 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1306 else
1307 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001308
Rex Xufc618912015-09-09 16:42:49 +08001309 spv::Id operand = spv::NoResult;
1310
1311 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1312 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001313 node->getOp() == glslang::EOpAtomicCounter ||
1314 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001315 operand = builder.accessChainGetLValue(); // Special case l-value operands
1316 else
John Kessenich32cfd492016-02-02 12:37:46 -07001317 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001318
John Kessenichf6640762016-08-01 19:44:00 -06001319 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001320 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001321
1322 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001323 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001324 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001325
1326 // if not, then possibly an operation
1327 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001328 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001331 if (invertedType)
1332 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1333
John Kessenich140f3df2015-06-26 16:58:36 -06001334 builder.clearAccessChain();
1335 builder.setAccessChainRValue(result);
1336
1337 return false; // done with this node
1338 }
1339
1340 // it must be a special case, check...
1341 switch (node->getOp()) {
1342 case glslang::EOpPostIncrement:
1343 case glslang::EOpPostDecrement:
1344 case glslang::EOpPreIncrement:
1345 case glslang::EOpPreDecrement:
1346 {
1347 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001348 spv::Id one = 0;
1349 if (node->getBasicType() == glslang::EbtFloat)
1350 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001351 else if (node->getBasicType() == glslang::EbtDouble)
1352 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001353#ifdef AMD_EXTENSIONS
1354 else if (node->getBasicType() == glslang::EbtFloat16)
1355 one = builder.makeFloat16Constant(1.0F);
1356#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001357 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1358 one = builder.makeInt64Constant(1);
1359 else
1360 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001361 glslang::TOperator op;
1362 if (node->getOp() == glslang::EOpPreIncrement ||
1363 node->getOp() == glslang::EOpPostIncrement)
1364 op = glslang::EOpAdd;
1365 else
1366 op = glslang::EOpSub;
1367
John Kessenichf6640762016-08-01 19:44:00 -06001368 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001369 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001370 convertGlslangToSpvType(node->getType()), operand, one,
1371 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001372 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001373
1374 // The result of operation is always stored, but conditionally the
1375 // consumed result. The consumed result is always an r-value.
1376 builder.accessChainStore(result);
1377 builder.clearAccessChain();
1378 if (node->getOp() == glslang::EOpPreIncrement ||
1379 node->getOp() == glslang::EOpPreDecrement)
1380 builder.setAccessChainRValue(result);
1381 else
1382 builder.setAccessChainRValue(operand);
1383 }
1384
1385 return false;
1386
1387 case glslang::EOpEmitStreamVertex:
1388 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1389 return false;
1390 case glslang::EOpEndStreamPrimitive:
1391 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1392 return false;
1393
1394 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001395 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001396 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001397 }
John Kessenich140f3df2015-06-26 16:58:36 -06001398}
1399
1400bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1401{
qining27e04a02016-04-14 16:40:20 -04001402 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1403 if (node->getType().getQualifier().isSpecConstant())
1404 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1405
John Kessenichfc51d282015-08-19 13:34:18 -06001406 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001407 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1408 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001409
1410 // try texturing
1411 result = createImageTextureFunctionCall(node);
1412 if (result != spv::NoResult) {
1413 builder.clearAccessChain();
1414 builder.setAccessChainRValue(result);
1415
1416 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001417 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001418 // "imageStore" is a special case, which has no result
1419 return false;
1420 }
John Kessenichfc51d282015-08-19 13:34:18 -06001421
John Kessenich140f3df2015-06-26 16:58:36 -06001422 glslang::TOperator binOp = glslang::EOpNull;
1423 bool reduceComparison = true;
1424 bool isMatrix = false;
1425 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001426 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001427
1428 assert(node->getOp());
1429
John Kessenichf6640762016-08-01 19:44:00 -06001430 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001431
1432 switch (node->getOp()) {
1433 case glslang::EOpSequence:
1434 {
1435 if (preVisit)
1436 ++sequenceDepth;
1437 else
1438 --sequenceDepth;
1439
1440 if (sequenceDepth == 1) {
1441 // If this is the parent node of all the functions, we want to see them
1442 // early, so all call points have actual SPIR-V functions to reference.
1443 // In all cases, still let the traverser visit the children for us.
1444 makeFunctions(node->getAsAggregate()->getSequence());
1445
John Kessenich6fccb3c2016-09-19 16:01:41 -06001446 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001447 // anything else gets there, so visit out of order, doing them all now.
1448 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1449
John Kessenich6a60c2f2016-12-08 21:01:59 -07001450 // Initializers are done, don't want to visit again, but functions and link objects need to be processed,
John Kessenich140f3df2015-06-26 16:58:36 -06001451 // so do them manually.
1452 visitFunctions(node->getAsAggregate()->getSequence());
1453
1454 return false;
1455 }
1456
1457 return true;
1458 }
1459 case glslang::EOpLinkerObjects:
1460 {
1461 if (visit == glslang::EvPreVisit)
1462 linkageOnly = true;
1463 else
1464 linkageOnly = false;
1465
1466 return true;
1467 }
1468 case glslang::EOpComma:
1469 {
1470 // processing from left to right naturally leaves the right-most
1471 // lying around in the access chain
1472 glslang::TIntermSequence& glslangOperands = node->getSequence();
1473 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1474 glslangOperands[i]->traverse(this);
1475
1476 return false;
1477 }
1478 case glslang::EOpFunction:
1479 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001480 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001481 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001482 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001483 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001484 } else {
1485 handleFunctionEntry(node);
1486 }
1487 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001488 if (inEntryPoint)
1489 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001490 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001491 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001492 }
1493
1494 return true;
1495 case glslang::EOpParameters:
1496 // Parameters will have been consumed by EOpFunction processing, but not
1497 // the body, so we still visited the function node's children, making this
1498 // child redundant.
1499 return false;
1500 case glslang::EOpFunctionCall:
1501 {
1502 if (node->isUserDefined())
1503 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001504 // assert(result); // this can happen for bad shaders because the call graph completeness checking is not yet done
John Kessenich6c292d32016-02-15 20:58:50 -07001505 if (result) {
1506 builder.clearAccessChain();
1507 builder.setAccessChainRValue(result);
1508 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001509 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001510
1511 return false;
1512 }
1513 case glslang::EOpConstructMat2x2:
1514 case glslang::EOpConstructMat2x3:
1515 case glslang::EOpConstructMat2x4:
1516 case glslang::EOpConstructMat3x2:
1517 case glslang::EOpConstructMat3x3:
1518 case glslang::EOpConstructMat3x4:
1519 case glslang::EOpConstructMat4x2:
1520 case glslang::EOpConstructMat4x3:
1521 case glslang::EOpConstructMat4x4:
1522 case glslang::EOpConstructDMat2x2:
1523 case glslang::EOpConstructDMat2x3:
1524 case glslang::EOpConstructDMat2x4:
1525 case glslang::EOpConstructDMat3x2:
1526 case glslang::EOpConstructDMat3x3:
1527 case glslang::EOpConstructDMat3x4:
1528 case glslang::EOpConstructDMat4x2:
1529 case glslang::EOpConstructDMat4x3:
1530 case glslang::EOpConstructDMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001531#ifdef AMD_EXTENSIONS
1532 case glslang::EOpConstructF16Mat2x2:
1533 case glslang::EOpConstructF16Mat2x3:
1534 case glslang::EOpConstructF16Mat2x4:
1535 case glslang::EOpConstructF16Mat3x2:
1536 case glslang::EOpConstructF16Mat3x3:
1537 case glslang::EOpConstructF16Mat3x4:
1538 case glslang::EOpConstructF16Mat4x2:
1539 case glslang::EOpConstructF16Mat4x3:
1540 case glslang::EOpConstructF16Mat4x4:
1541#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001542 isMatrix = true;
1543 // fall through
1544 case glslang::EOpConstructFloat:
1545 case glslang::EOpConstructVec2:
1546 case glslang::EOpConstructVec3:
1547 case glslang::EOpConstructVec4:
1548 case glslang::EOpConstructDouble:
1549 case glslang::EOpConstructDVec2:
1550 case glslang::EOpConstructDVec3:
1551 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001552#ifdef AMD_EXTENSIONS
1553 case glslang::EOpConstructFloat16:
1554 case glslang::EOpConstructF16Vec2:
1555 case glslang::EOpConstructF16Vec3:
1556 case glslang::EOpConstructF16Vec4:
1557#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001558 case glslang::EOpConstructBool:
1559 case glslang::EOpConstructBVec2:
1560 case glslang::EOpConstructBVec3:
1561 case glslang::EOpConstructBVec4:
1562 case glslang::EOpConstructInt:
1563 case glslang::EOpConstructIVec2:
1564 case glslang::EOpConstructIVec3:
1565 case glslang::EOpConstructIVec4:
1566 case glslang::EOpConstructUint:
1567 case glslang::EOpConstructUVec2:
1568 case glslang::EOpConstructUVec3:
1569 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001570 case glslang::EOpConstructInt64:
1571 case glslang::EOpConstructI64Vec2:
1572 case glslang::EOpConstructI64Vec3:
1573 case glslang::EOpConstructI64Vec4:
1574 case glslang::EOpConstructUint64:
1575 case glslang::EOpConstructU64Vec2:
1576 case glslang::EOpConstructU64Vec3:
1577 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001578 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001579 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001580 {
1581 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001582 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001583 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001584 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001585 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001586 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001587 std::vector<spv::Id> constituents;
1588 for (int c = 0; c < (int)arguments.size(); ++c)
1589 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001590 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001591 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001592 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001593 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001594 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001595
1596 builder.clearAccessChain();
1597 builder.setAccessChainRValue(constructed);
1598
1599 return false;
1600 }
1601
1602 // These six are component-wise compares with component-wise results.
1603 // Forward on to createBinaryOperation(), requesting a vector result.
1604 case glslang::EOpLessThan:
1605 case glslang::EOpGreaterThan:
1606 case glslang::EOpLessThanEqual:
1607 case glslang::EOpGreaterThanEqual:
1608 case glslang::EOpVectorEqual:
1609 case glslang::EOpVectorNotEqual:
1610 {
1611 // Map the operation to a binary
1612 binOp = node->getOp();
1613 reduceComparison = false;
1614 switch (node->getOp()) {
1615 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1616 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1617 default: binOp = node->getOp(); break;
1618 }
1619
1620 break;
1621 }
1622 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001623 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001624 binOp = glslang::EOpMul;
1625 break;
1626 case glslang::EOpOuterProduct:
1627 // two vectors multiplied to make a matrix
1628 binOp = glslang::EOpOuterProduct;
1629 break;
1630 case glslang::EOpDot:
1631 {
qining25262b32016-05-06 17:25:16 -04001632 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001633 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001634 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001635 binOp = glslang::EOpMul;
1636 break;
1637 }
1638 case glslang::EOpMod:
1639 // when an aggregate, this is the floating-point mod built-in function,
1640 // which can be emitted by the one in createBinaryOperation()
1641 binOp = glslang::EOpMod;
1642 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001643 case glslang::EOpEmitVertex:
1644 case glslang::EOpEndPrimitive:
1645 case glslang::EOpBarrier:
1646 case glslang::EOpMemoryBarrier:
1647 case glslang::EOpMemoryBarrierAtomicCounter:
1648 case glslang::EOpMemoryBarrierBuffer:
1649 case glslang::EOpMemoryBarrierImage:
1650 case glslang::EOpMemoryBarrierShared:
1651 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001652 case glslang::EOpAllMemoryBarrierWithGroupSync:
1653 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1654 case glslang::EOpWorkgroupMemoryBarrier:
1655 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001656 noReturnValue = true;
1657 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1658 break;
1659
John Kessenich426394d2015-07-23 10:22:48 -06001660 case glslang::EOpAtomicAdd:
1661 case glslang::EOpAtomicMin:
1662 case glslang::EOpAtomicMax:
1663 case glslang::EOpAtomicAnd:
1664 case glslang::EOpAtomicOr:
1665 case glslang::EOpAtomicXor:
1666 case glslang::EOpAtomicExchange:
1667 case glslang::EOpAtomicCompSwap:
1668 atomic = true;
1669 break;
1670
John Kessenich140f3df2015-06-26 16:58:36 -06001671 default:
1672 break;
1673 }
1674
1675 //
1676 // See if it maps to a regular operation.
1677 //
John Kessenich140f3df2015-06-26 16:58:36 -06001678 if (binOp != glslang::EOpNull) {
1679 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1680 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1681 assert(left && right);
1682
1683 builder.clearAccessChain();
1684 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001685 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001686
1687 builder.clearAccessChain();
1688 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001689 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001690
qining25262b32016-05-06 17:25:16 -04001691 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001692 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001693 left->getType().getBasicType(), reduceComparison);
1694
1695 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001696 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001697 builder.clearAccessChain();
1698 builder.setAccessChainRValue(result);
1699
1700 return false;
1701 }
1702
John Kessenich426394d2015-07-23 10:22:48 -06001703 //
1704 // Create the list of operands.
1705 //
John Kessenich140f3df2015-06-26 16:58:36 -06001706 glslang::TIntermSequence& glslangOperands = node->getSequence();
1707 std::vector<spv::Id> operands;
1708 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001709 // special case l-value operands; there are just a few
1710 bool lvalue = false;
1711 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001712 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001713 case glslang::EOpModf:
1714 if (arg == 1)
1715 lvalue = true;
1716 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001717 case glslang::EOpInterpolateAtSample:
1718 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001719#ifdef AMD_EXTENSIONS
1720 case glslang::EOpInterpolateAtVertex:
1721#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001722 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001723 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001724
1725 // Does it need a swizzle inversion? If so, evaluation is inverted;
1726 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001727 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001728 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1729 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1730 }
Rex Xu7a26c172015-12-08 17:12:09 +08001731 break;
Rex Xud4782c12015-09-06 16:30:11 +08001732 case glslang::EOpAtomicAdd:
1733 case glslang::EOpAtomicMin:
1734 case glslang::EOpAtomicMax:
1735 case glslang::EOpAtomicAnd:
1736 case glslang::EOpAtomicOr:
1737 case glslang::EOpAtomicXor:
1738 case glslang::EOpAtomicExchange:
1739 case glslang::EOpAtomicCompSwap:
1740 if (arg == 0)
1741 lvalue = true;
1742 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001743 case glslang::EOpAddCarry:
1744 case glslang::EOpSubBorrow:
1745 if (arg == 2)
1746 lvalue = true;
1747 break;
1748 case glslang::EOpUMulExtended:
1749 case glslang::EOpIMulExtended:
1750 if (arg >= 2)
1751 lvalue = true;
1752 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001753 default:
1754 break;
1755 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001756 builder.clearAccessChain();
1757 if (invertedType != spv::NoType && arg == 0)
1758 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1759 else
1760 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001761 if (lvalue)
1762 operands.push_back(builder.accessChainGetLValue());
1763 else
John Kessenich32cfd492016-02-02 12:37:46 -07001764 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001765 }
John Kessenich426394d2015-07-23 10:22:48 -06001766
1767 if (atomic) {
1768 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001769 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001770 } else {
1771 // Pass through to generic operations.
1772 switch (glslangOperands.size()) {
1773 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001774 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001775 break;
1776 case 1:
qining25262b32016-05-06 17:25:16 -04001777 result = createUnaryOperation(
1778 node->getOp(), precision,
1779 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001780 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001781 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001782 break;
1783 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001784 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001785 break;
1786 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001787 if (invertedType)
1788 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001789 }
1790
1791 if (noReturnValue)
1792 return false;
1793
1794 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001795 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001796 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001797 } else {
1798 builder.clearAccessChain();
1799 builder.setAccessChainRValue(result);
1800 return false;
1801 }
1802}
1803
John Kessenich433e9ff2017-01-26 20:31:11 -07001804// This path handles both if-then-else and ?:
1805// The if-then-else has a node type of void, while
1806// ?: has either a void or a non-void node type
1807//
1808// Leaving the result, when not void:
1809// GLSL only has r-values as the result of a :?, but
1810// if we have an l-value, that can be more efficient if it will
1811// become the base of a complex r-value expression, because the
1812// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001813bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1814{
John Kessenich433e9ff2017-01-26 20:31:11 -07001815 // See if it simple and safe to generate OpSelect instead of using control flow.
1816 // Crucially, side effects must be avoided, and there are performance trade-offs.
1817 // Return true if good idea (and safe) for OpSelect, false otherwise.
1818 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001819 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1820 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001821 return false;
1822
1823 if (node->getTrueBlock() == nullptr ||
1824 node->getFalseBlock() == nullptr)
1825 return false;
1826
1827 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1828 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1829
1830 // return true if a single operand to ? : is okay for OpSelect
1831 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001832 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001833 };
1834
1835 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1836 operandOkay(node->getFalseBlock()->getAsTyped());
1837 };
1838
1839 // Emit OpSelect for this selection.
1840 const auto handleAsOpSelect = [&]() {
1841 node->getCondition()->traverse(this);
1842 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1843 node->getTrueBlock()->traverse(this);
1844 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1845 node->getFalseBlock()->traverse(this);
1846 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1847
John Kesseniche434ad92017-03-30 10:09:28 -06001848 // smear condition to vector, if necessary (AST is always scalar)
1849 if (builder.isVector(trueValue))
1850 condition = builder.smearScalar(spv::NoPrecision, condition,
1851 builder.makeVectorType(builder.makeBoolType(),
1852 builder.getNumComponents(trueValue)));
1853
1854 spv::Id select = builder.createTriOp(spv::OpSelect,
1855 convertGlslangToSpvType(node->getType()), condition,
1856 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001857 builder.clearAccessChain();
1858 builder.setAccessChainRValue(select);
1859 };
1860
1861 // Try for OpSelect
1862
1863 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001864 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1865 if (node->getType().getQualifier().isSpecConstant())
1866 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1867
John Kessenich433e9ff2017-01-26 20:31:11 -07001868 handleAsOpSelect();
1869 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001870 }
1871
John Kessenich433e9ff2017-01-26 20:31:11 -07001872 // Instead, emit control flow...
1873
1874 // Don't handle results as temporaries, because there will be two names
1875 // and better to leave SSA to later passes.
1876 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1877 ? spv::NoResult
1878 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1879
John Kessenich140f3df2015-06-26 16:58:36 -06001880 // emit the condition before doing anything with selection
1881 node->getCondition()->traverse(this);
1882
1883 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001884 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001885
John Kessenich433e9ff2017-01-26 20:31:11 -07001886 // emit the "then" statement
1887 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001888 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001889 if (result != spv::NoResult)
1890 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001891 }
1892
John Kessenich433e9ff2017-01-26 20:31:11 -07001893 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001894 ifBuilder.makeBeginElse();
1895 // emit the "else" statement
1896 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001897 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001898 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001899 }
1900
John Kessenich433e9ff2017-01-26 20:31:11 -07001901 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001902 ifBuilder.makeEndIf();
1903
John Kessenich433e9ff2017-01-26 20:31:11 -07001904 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001905 // GLSL only has r-values as the result of a :?, but
1906 // if we have an l-value, that can be more efficient if it will
1907 // become the base of a complex r-value expression, because the
1908 // next layer copies r-values into memory to use the access-chain mechanism
1909 builder.clearAccessChain();
1910 builder.setAccessChainLValue(result);
1911 }
1912
1913 return false;
1914}
1915
1916bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1917{
1918 // emit and get the condition before doing anything with switch
1919 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001920 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001921
1922 // browse the children to sort out code segments
1923 int defaultSegment = -1;
1924 std::vector<TIntermNode*> codeSegments;
1925 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1926 std::vector<int> caseValues;
1927 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1928 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1929 TIntermNode* child = *c;
1930 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001931 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001932 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001933 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001934 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1935 } else
1936 codeSegments.push_back(child);
1937 }
1938
qining25262b32016-05-06 17:25:16 -04001939 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001940 // statements between the last case and the end of the switch statement
1941 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1942 (int)codeSegments.size() == defaultSegment)
1943 codeSegments.push_back(nullptr);
1944
1945 // make the switch statement
1946 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001947 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001948
1949 // emit all the code in the segments
1950 breakForLoop.push(false);
1951 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1952 builder.nextSwitchSegment(segmentBlocks, s);
1953 if (codeSegments[s])
1954 codeSegments[s]->traverse(this);
1955 else
1956 builder.addSwitchBreak();
1957 }
1958 breakForLoop.pop();
1959
1960 builder.endSwitch(segmentBlocks);
1961
1962 return false;
1963}
1964
1965void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
1966{
1967 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04001968 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06001969
1970 builder.clearAccessChain();
1971 builder.setAccessChainRValue(constant);
1972}
1973
1974bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
1975{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001976 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05001977 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06001978
1979 // Loop control:
1980 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
1981
1982 // TODO: dependency length
1983
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001984 // Spec requires back edges to target header blocks, and every header block
1985 // must dominate its merge block. Make a header block first to ensure these
1986 // conditions are met. By definition, it will contain OpLoopMerge, followed
1987 // by a block-ending branch. But we don't want to put any other body/test
1988 // instructions in it, since the body/test may have arbitrary instructions,
1989 // including merges of its own.
1990 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06001991 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001992 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05001993 spv::Block& test = builder.makeNewBlock();
1994 builder.createBranch(&test);
1995
1996 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06001997 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05001998 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07001999 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002000 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2001
2002 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002003 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002004 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002005 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002006 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002007 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002008
2009 builder.setBuildPoint(&blocks.continue_target);
2010 if (node->getTerminal())
2011 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002012 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002013 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002014 builder.createBranch(&blocks.body);
2015
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002016 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002017 builder.setBuildPoint(&blocks.body);
2018 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002019 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002020 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002021 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002022
2023 builder.setBuildPoint(&blocks.continue_target);
2024 if (node->getTerminal())
2025 node->getTerminal()->traverse(this);
2026 if (node->getTest()) {
2027 node->getTest()->traverse(this);
2028 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002029 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002030 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002031 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002032 // TODO: unless there was a break/return/discard instruction
2033 // somewhere in the body, this is an infinite loop, so we should
2034 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002035 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002036 }
John Kessenich140f3df2015-06-26 16:58:36 -06002037 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002038 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002039 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002040 return false;
2041}
2042
2043bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2044{
2045 if (node->getExpression())
2046 node->getExpression()->traverse(this);
2047
2048 switch (node->getFlowOp()) {
2049 case glslang::EOpKill:
2050 builder.makeDiscard();
2051 break;
2052 case glslang::EOpBreak:
2053 if (breakForLoop.top())
2054 builder.createLoopExit();
2055 else
2056 builder.addSwitchBreak();
2057 break;
2058 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002059 builder.createLoopContinue();
2060 break;
2061 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002062 if (node->getExpression()) {
2063 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2064 spv::Id returnId = accessChainLoad(glslangReturnType);
2065 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2066 builder.clearAccessChain();
2067 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2068 builder.setAccessChainLValue(copyId);
2069 multiTypeStore(glslangReturnType, returnId);
2070 returnId = builder.createLoad(copyId);
2071 }
2072 builder.makeReturn(false, returnId);
2073 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002074 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002075
2076 builder.clearAccessChain();
2077 break;
2078
2079 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002080 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002081 break;
2082 }
2083
2084 return false;
2085}
2086
2087spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2088{
qining25262b32016-05-06 17:25:16 -04002089 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002090 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002091 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002092 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002093 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002094 }
2095
2096 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002097 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002098 spv::Id spvType = convertGlslangToSpvType(node->getType());
2099
Rex Xuf89ad982017-04-07 23:22:33 +08002100#ifdef AMD_EXTENSIONS
2101 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16);
2102 if (contains16BitType) {
2103 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2104 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2105 builder.addCapability(spv::CapabilityStorageInputOutput16);
2106 } else if (storageClass == spv::StorageClassPushConstant) {
2107 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2108 builder.addCapability(spv::CapabilityStoragePushConstant16);
2109 } else if (storageClass == spv::StorageClassUniform) {
2110 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2111 builder.addCapability(spv::CapabilityStorageUniform16);
2112 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2113 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2114 }
2115 }
2116#endif
2117
John Kessenich140f3df2015-06-26 16:58:36 -06002118 const char* name = node->getName().c_str();
2119 if (glslang::IsAnonymous(name))
2120 name = "";
2121
2122 return builder.createVariable(storageClass, spvType, name);
2123}
2124
2125// Return type Id of the sampled type.
2126spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2127{
2128 switch (sampler.type) {
2129 case glslang::EbtFloat: return builder.makeFloatType(32);
2130 case glslang::EbtInt: return builder.makeIntType(32);
2131 case glslang::EbtUint: return builder.makeUintType(32);
2132 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002133 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002134 return builder.makeFloatType(32);
2135 }
2136}
2137
John Kessenich8c8505c2016-07-26 12:50:38 -06002138// If node is a swizzle operation, return the type that should be used if
2139// the swizzle base is first consumed by another operation, before the swizzle
2140// is applied.
2141spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2142{
John Kessenichecba76f2017-01-06 00:34:48 -07002143 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002144 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2145 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2146 else
2147 return spv::NoType;
2148}
2149
2150// When inverting a swizzle with a parent op, this function
2151// will apply the swizzle operation to a completed parent operation.
2152spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2153{
2154 std::vector<unsigned> swizzle;
2155 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2156 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2157}
2158
John Kessenich8c8505c2016-07-26 12:50:38 -06002159// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2160void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2161{
2162 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2163 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2164 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2165}
2166
John Kessenich3ac051e2015-12-20 11:29:16 -07002167// Convert from a glslang type to an SPV type, by calling into a
2168// recursive version of this function. This establishes the inherited
2169// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002170spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2171{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002172 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002173}
2174
2175// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002176// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002177// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002178spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002179{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002180 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002181
2182 switch (type.getBasicType()) {
2183 case glslang::EbtVoid:
2184 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002185 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002186 break;
2187 case glslang::EbtFloat:
2188 spvType = builder.makeFloatType(32);
2189 break;
2190 case glslang::EbtDouble:
2191 spvType = builder.makeFloatType(64);
2192 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002193#ifdef AMD_EXTENSIONS
2194 case glslang::EbtFloat16:
2195 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002196 spvType = builder.makeFloatType(16);
2197 break;
2198#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002199 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002200 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2201 // a 32-bit int where non-0 means true.
2202 if (explicitLayout != glslang::ElpNone)
2203 spvType = builder.makeUintType(32);
2204 else
2205 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002206 break;
2207 case glslang::EbtInt:
2208 spvType = builder.makeIntType(32);
2209 break;
2210 case glslang::EbtUint:
2211 spvType = builder.makeUintType(32);
2212 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002213 case glslang::EbtInt64:
2214 builder.addCapability(spv::CapabilityInt64);
2215 spvType = builder.makeIntType(64);
2216 break;
2217 case glslang::EbtUint64:
2218 builder.addCapability(spv::CapabilityInt64);
2219 spvType = builder.makeUintType(64);
2220 break;
John Kessenich426394d2015-07-23 10:22:48 -06002221 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002222 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002223 spvType = builder.makeUintType(32);
2224 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002225 case glslang::EbtSampler:
2226 {
2227 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002228 if (sampler.sampler) {
2229 // pure sampler
2230 spvType = builder.makeSamplerType();
2231 } else {
2232 // an image is present, make its type
2233 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2234 sampler.image ? 2 : 1, TranslateImageFormat(type));
2235 if (sampler.combined) {
2236 // already has both image and sampler, make the combined type
2237 spvType = builder.makeSampledImageType(spvType);
2238 }
John Kessenich55e7d112015-11-15 21:33:39 -07002239 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002240 }
John Kessenich140f3df2015-06-26 16:58:36 -06002241 break;
2242 case glslang::EbtStruct:
2243 case glslang::EbtBlock:
2244 {
2245 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002246 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002247
2248 // Try to share structs for different layouts, but not yet for other
2249 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002250 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002251 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002252 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002253 break;
2254
2255 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002256 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002257 memberRemapper[glslangMembers].resize(glslangMembers->size());
2258 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002259 }
2260 break;
2261 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002262 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002263 break;
2264 }
2265
2266 if (type.isMatrix())
2267 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2268 else {
2269 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2270 if (type.getVectorSize() > 1)
2271 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2272 }
2273
2274 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002275 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2276
John Kessenichc9a80832015-09-12 12:17:44 -06002277 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002278 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002279 // We need to decorate array strides for types needing explicit layout, except blocks.
2280 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002281 // Use a dummy glslang type for querying internal strides of
2282 // arrays of arrays, but using just a one-dimensional array.
2283 glslang::TType simpleArrayType(type, 0); // deference type of the array
2284 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2285 simpleArrayType.getArraySizes().dereference();
2286
2287 // Will compute the higher-order strides here, rather than making a whole
2288 // pile of types and doing repetitive recursion on their contents.
2289 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2290 }
John Kessenichf8842e52016-01-04 19:22:56 -07002291
2292 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002293 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002294 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002295 if (stride > 0)
2296 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002297 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002298 }
2299 } else {
2300 // single-dimensional array, and don't yet have stride
2301
John Kessenichf8842e52016-01-04 19:22:56 -07002302 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002303 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2304 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002305 }
John Kessenich31ed4832015-09-09 17:51:38 -06002306
John Kessenichc9a80832015-09-12 12:17:44 -06002307 // Do the outer dimension, which might not be known for a runtime-sized array
2308 if (type.isRuntimeSizedArray()) {
2309 spvType = builder.makeRuntimeArray(spvType);
2310 } else {
2311 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002312 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002313 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002314 if (stride > 0)
2315 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002316 }
2317
2318 return spvType;
2319}
2320
John Kessenich0e737842017-03-24 18:38:16 -06002321// TODO: this functionality should exist at a higher level, in creating the AST
2322//
2323// Identify interface members that don't have their required extension turned on.
2324//
2325bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2326{
2327 auto& extensions = glslangIntermediate->getRequestedExtensions();
2328
Rex Xubcf291a2017-03-29 23:01:36 +08002329 if (member.getFieldName() == "gl_ViewportMask" &&
2330 extensions.find("GL_NV_viewport_array2") == extensions.end())
2331 return true;
2332 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2333 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2334 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002335 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2336 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2337 return true;
2338 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2339 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2340 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002341 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2342 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2343 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002344
2345 return false;
2346};
2347
John Kessenich6090df02016-06-30 21:18:02 -06002348// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2349// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2350// Mutually recursive with convertGlslangToSpvType().
2351spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2352 const glslang::TTypeList* glslangMembers,
2353 glslang::TLayoutPacking explicitLayout,
2354 const glslang::TQualifier& qualifier)
2355{
2356 // Create a vector of struct types for SPIR-V to consume
2357 std::vector<spv::Id> spvMembers;
2358 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2359 int locationOffset = 0; // for use across struct members, when they are called recursively
2360 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2361 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2362 if (glslangMember.hiddenMember()) {
2363 ++memberDelta;
2364 if (type.getBasicType() == glslang::EbtBlock)
2365 memberRemapper[glslangMembers][i] = -1;
2366 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002367 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002368 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002369 if (filterMember(glslangMember))
2370 continue;
2371 }
John Kessenich6090df02016-06-30 21:18:02 -06002372 // modify just this child's view of the qualifier
2373 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2374 InheritQualifiers(memberQualifier, qualifier);
2375
2376 // manually inherit location; it's more complex
2377 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2378 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2379 if (qualifier.hasLocation())
2380 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2381
2382 // recurse
2383 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2384 }
2385 }
2386
2387 // Make the SPIR-V type
2388 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002389 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002390 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2391
2392 // Decorate it
2393 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2394
2395 return spvType;
2396}
2397
2398void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2399 const glslang::TTypeList* glslangMembers,
2400 glslang::TLayoutPacking explicitLayout,
2401 const glslang::TQualifier& qualifier,
2402 spv::Id spvType)
2403{
2404 // Name and decorate the non-hidden members
2405 int offset = -1;
2406 int locationOffset = 0; // for use within the members of this struct
2407 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2408 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2409 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002410 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002411 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002412 if (filterMember(glslangMember))
2413 continue;
2414 }
John Kessenich6090df02016-06-30 21:18:02 -06002415
2416 // modify just this child's view of the qualifier
2417 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2418 InheritQualifiers(memberQualifier, qualifier);
2419
2420 // using -1 above to indicate a hidden member
2421 if (member >= 0) {
2422 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2423 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2424 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2425 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002426 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2427 type.getQualifier().storage == glslang::EvqVaryingOut) {
2428 if (type.getBasicType() == glslang::EbtBlock ||
2429 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002430 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2431 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2432 }
2433 }
2434 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2435
2436 if (qualifier.storage == glslang::EvqBuffer) {
2437 std::vector<spv::Decoration> memory;
2438 TranslateMemoryDecoration(memberQualifier, memory);
2439 for (unsigned int i = 0; i < memory.size(); ++i)
2440 addMemberDecoration(spvType, member, memory[i]);
2441 }
2442
John Kessenich2f47bc92016-06-30 21:47:35 -06002443 // Compute location decoration; tricky based on whether inheritance is at play and
2444 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002445 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2446 // probably move to the linker stage of the front end proper, and just have the
2447 // answer sitting already distributed throughout the individual member locations.
2448 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002449 // Ignore member locations if the container is an array, as that's
2450 // ill-specified and decisions have been made to not allow this anyway.
2451 // The object itself must have a location, and that comes out from decorating the object,
2452 // not the type (this code decorates types).
2453 if (! type.isArray()) {
2454 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2455 // struct members should not have explicit locations
2456 assert(type.getBasicType() != glslang::EbtStruct);
2457 location = memberQualifier.layoutLocation;
2458 } else if (type.getBasicType() != glslang::EbtBlock) {
2459 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2460 // The members, and their nested types, must not themselves have Location decorations.
2461 } else if (qualifier.hasLocation()) // inheritance
2462 location = qualifier.layoutLocation + locationOffset;
2463 }
John Kessenich6090df02016-06-30 21:18:02 -06002464 if (location >= 0)
2465 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2466
John Kessenich2f47bc92016-06-30 21:47:35 -06002467 if (qualifier.hasLocation()) // track for upcoming inheritance
2468 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2469
John Kessenich6090df02016-06-30 21:18:02 -06002470 // component, XFB, others
2471 if (glslangMember.getQualifier().hasComponent())
2472 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2473 if (glslangMember.getQualifier().hasXfbOffset())
2474 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2475 else if (explicitLayout != glslang::ElpNone) {
2476 // figure out what to do with offset, which is accumulating
2477 int nextOffset;
2478 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2479 if (offset >= 0)
2480 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2481 offset = nextOffset;
2482 }
2483
2484 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2485 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2486
2487 // built-in variable decorations
2488 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002489 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002490 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002491
2492#ifdef NV_EXTENSIONS
2493 if (builtIn == spv::BuiltInLayer) {
2494 // SPV_NV_viewport_array2 extension
2495 if (glslangMember.getQualifier().layoutViewportRelative){
2496 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2497 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2498 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2499 }
2500 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2501 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2502 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2503 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2504 }
2505 }
chaocdf3956c2017-02-14 14:52:34 -08002506 if (glslangMember.getQualifier().layoutPassthrough) {
2507 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2508 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2509 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2510 }
chaoc771d89f2017-01-13 01:10:53 -08002511#endif
John Kessenich6090df02016-06-30 21:18:02 -06002512 }
2513 }
2514
2515 // Decorate the structure
2516 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002517 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002518 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2519 builder.addCapability(spv::CapabilityGeometryStreams);
2520 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2521 }
2522 if (glslangIntermediate->getXfbMode()) {
2523 builder.addCapability(spv::CapabilityTransformFeedback);
2524 if (type.getQualifier().hasXfbStride())
2525 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2526 if (type.getQualifier().hasXfbBuffer())
2527 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2528 }
2529}
2530
John Kessenich6c292d32016-02-15 20:58:50 -07002531// Turn the expression forming the array size into an id.
2532// This is not quite trivial, because of specialization constants.
2533// Sometimes, a raw constant is turned into an Id, and sometimes
2534// a specialization constant expression is.
2535spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2536{
2537 // First, see if this is sized with a node, meaning a specialization constant:
2538 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2539 if (specNode != nullptr) {
2540 builder.clearAccessChain();
2541 specNode->traverse(this);
2542 return accessChainLoad(specNode->getAsTyped()->getType());
2543 }
qining25262b32016-05-06 17:25:16 -04002544
John Kessenich6c292d32016-02-15 20:58:50 -07002545 // Otherwise, need a compile-time (front end) size, get it:
2546 int size = arraySizes.getDimSize(dim);
2547 assert(size > 0);
2548 return builder.makeUintConstant(size);
2549}
2550
John Kessenich103bef92016-02-08 21:38:15 -07002551// Wrap the builder's accessChainLoad to:
2552// - localize handling of RelaxedPrecision
2553// - use the SPIR-V inferred type instead of another conversion of the glslang type
2554// (avoids unnecessary work and possible type punning for structures)
2555// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002556spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2557{
John Kessenich103bef92016-02-08 21:38:15 -07002558 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2559 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2560
2561 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002562 if (type.getBasicType() == glslang::EbtBool) {
2563 if (builder.isScalarType(nominalTypeId)) {
2564 // Conversion for bool
2565 spv::Id boolType = builder.makeBoolType();
2566 if (nominalTypeId != boolType)
2567 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2568 } else if (builder.isVectorType(nominalTypeId)) {
2569 // Conversion for bvec
2570 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2571 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2572 if (nominalTypeId != bvecType)
2573 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2574 }
2575 }
John Kessenich103bef92016-02-08 21:38:15 -07002576
2577 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002578}
2579
Rex Xu27253232016-02-23 17:51:09 +08002580// Wrap the builder's accessChainStore to:
2581// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002582//
2583// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002584void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2585{
2586 // Need to convert to abstract types when necessary
2587 if (type.getBasicType() == glslang::EbtBool) {
2588 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2589
2590 if (builder.isScalarType(nominalTypeId)) {
2591 // Conversion for bool
2592 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002593 if (nominalTypeId != boolType) {
2594 // keep these outside arguments, for determinant order-of-evaluation
2595 spv::Id one = builder.makeUintConstant(1);
2596 spv::Id zero = builder.makeUintConstant(0);
2597 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2598 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002599 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002600 } else if (builder.isVectorType(nominalTypeId)) {
2601 // Conversion for bvec
2602 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2603 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002604 if (nominalTypeId != bvecType) {
2605 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002606 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2607 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2608 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002609 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002610 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2611 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002612 }
2613 }
2614
2615 builder.accessChainStore(rvalue);
2616}
2617
John Kessenich4bf71552016-09-02 11:20:21 -06002618// For storing when types match at the glslang level, but not might match at the
2619// SPIR-V level.
2620//
2621// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002622// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002623// as in a member-decorated way.
2624//
2625// NOTE: This function can handle any store request; if it's not special it
2626// simplifies to a simple OpStore.
2627//
2628// Implicitly uses the existing builder.accessChain as the storage target.
2629void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2630{
John Kessenichb3e24e42016-09-11 12:33:43 -06002631 // we only do the complex path here if it's an aggregate
2632 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002633 accessChainStore(type, rValue);
2634 return;
2635 }
2636
John Kessenichb3e24e42016-09-11 12:33:43 -06002637 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002638 spv::Id rType = builder.getTypeId(rValue);
2639 spv::Id lValue = builder.accessChainGetLValue();
2640 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2641 if (lType == rType) {
2642 accessChainStore(type, rValue);
2643 return;
2644 }
2645
John Kessenichb3e24e42016-09-11 12:33:43 -06002646 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002647 // where the two types were the same type in GLSL. This requires member
2648 // by member copy, recursively.
2649
John Kessenichb3e24e42016-09-11 12:33:43 -06002650 // If an array, copy element by element.
2651 if (type.isArray()) {
2652 glslang::TType glslangElementType(type, 0);
2653 spv::Id elementRType = builder.getContainedTypeId(rType);
2654 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2655 // get the source member
2656 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002657
John Kessenichb3e24e42016-09-11 12:33:43 -06002658 // set up the target storage
2659 builder.clearAccessChain();
2660 builder.setAccessChainLValue(lValue);
2661 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002662
John Kessenichb3e24e42016-09-11 12:33:43 -06002663 // store the member
2664 multiTypeStore(glslangElementType, elementRValue);
2665 }
2666 } else {
2667 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002668
John Kessenichb3e24e42016-09-11 12:33:43 -06002669 // loop over structure members
2670 const glslang::TTypeList& members = *type.getStruct();
2671 for (int m = 0; m < (int)members.size(); ++m) {
2672 const glslang::TType& glslangMemberType = *members[m].type;
2673
2674 // get the source member
2675 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2676 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2677
2678 // set up the target storage
2679 builder.clearAccessChain();
2680 builder.setAccessChainLValue(lValue);
2681 builder.accessChainPush(builder.makeIntConstant(m));
2682
2683 // store the member
2684 multiTypeStore(glslangMemberType, memberRValue);
2685 }
John Kessenich4bf71552016-09-02 11:20:21 -06002686 }
2687}
2688
John Kessenichf85e8062015-12-19 13:57:10 -07002689// Decide whether or not this type should be
2690// decorated with offsets and strides, and if so
2691// whether std140 or std430 rules should be applied.
2692glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002693{
John Kessenichf85e8062015-12-19 13:57:10 -07002694 // has to be a block
2695 if (type.getBasicType() != glslang::EbtBlock)
2696 return glslang::ElpNone;
2697
2698 // has to be a uniform or buffer block
2699 if (type.getQualifier().storage != glslang::EvqUniform &&
2700 type.getQualifier().storage != glslang::EvqBuffer)
2701 return glslang::ElpNone;
2702
2703 // return the layout to use
2704 switch (type.getQualifier().layoutPacking) {
2705 case glslang::ElpStd140:
2706 case glslang::ElpStd430:
2707 return type.getQualifier().layoutPacking;
2708 default:
2709 return glslang::ElpNone;
2710 }
John Kessenich31ed4832015-09-09 17:51:38 -06002711}
2712
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002713// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002714int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002715{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002716 int size;
John Kessenich49987892015-12-29 17:11:44 -07002717 int stride;
2718 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002719
2720 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002721}
2722
John Kessenich49987892015-12-29 17:11:44 -07002723// 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 -07002724// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002725int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002726{
John Kessenich49987892015-12-29 17:11:44 -07002727 glslang::TType elementType;
2728 elementType.shallowCopy(matrixType);
2729 elementType.clearArraySizes();
2730
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002731 int size;
John Kessenich49987892015-12-29 17:11:44 -07002732 int stride;
2733 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2734
2735 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002736}
2737
John Kessenich5e4b1242015-08-06 22:53:06 -06002738// Given a member type of a struct, realign the current offset for it, and compute
2739// the next (not yet aligned) offset for the next member, which will get aligned
2740// on the next call.
2741// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2742// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2743// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002744void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002745 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002746{
2747 // this will get a positive value when deemed necessary
2748 nextOffset = -1;
2749
John Kessenich5e4b1242015-08-06 22:53:06 -06002750 // override anything in currentOffset with user-set offset
2751 if (memberType.getQualifier().hasOffset())
2752 currentOffset = memberType.getQualifier().layoutOffset;
2753
2754 // It could be that current linker usage in glslang updated all the layoutOffset,
2755 // in which case the following code does not matter. But, that's not quite right
2756 // once cross-compilation unit GLSL validation is done, as the original user
2757 // settings are needed in layoutOffset, and then the following will come into play.
2758
John Kessenichf85e8062015-12-19 13:57:10 -07002759 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002760 if (! memberType.getQualifier().hasOffset())
2761 currentOffset = -1;
2762
2763 return;
2764 }
2765
John Kessenichf85e8062015-12-19 13:57:10 -07002766 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002767 if (currentOffset < 0)
2768 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002769
John Kessenich5e4b1242015-08-06 22:53:06 -06002770 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2771 // but possibly not yet correctly aligned.
2772
2773 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002774 int dummyStride;
2775 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002776
2777 // Adjust alignment for HLSL rules
2778 if (glslangIntermediate->usingHlslOFfsets() &&
2779 ! memberType.isArray() && memberType.isVector()) {
2780 int dummySize;
2781 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2782 if (componentAlignment <= 4)
2783 memberAlignment = componentAlignment;
2784 }
2785
2786 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002787 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002788
2789 // Bump up to vec4 if there is a bad straddle
2790 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2791 glslang::RoundToPow2(currentOffset, 16);
2792
John Kessenich5e4b1242015-08-06 22:53:06 -06002793 nextOffset = currentOffset + memberSize;
2794}
2795
David Netoa901ffe2016-06-08 14:11:40 +01002796void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002797{
David Netoa901ffe2016-06-08 14:11:40 +01002798 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2799 switch (glslangBuiltIn)
2800 {
2801 case glslang::EbvClipDistance:
2802 case glslang::EbvCullDistance:
2803 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002804#ifdef NV_EXTENSIONS
2805 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002806 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002807 case glslang::EbvViewportMaskNV:
2808 case glslang::EbvSecondaryPositionNV:
2809 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002810 case glslang::EbvPositionPerViewNV:
2811 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002812#endif
David Netoa901ffe2016-06-08 14:11:40 +01002813 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2814 // Alternately, we could just call this for any glslang built-in, since the
2815 // capability already guards against duplicates.
2816 TranslateBuiltInDecoration(glslangBuiltIn, false);
2817 break;
2818 default:
2819 // Capabilities were already generated when the struct was declared.
2820 break;
2821 }
John Kessenichebb50532016-05-16 19:22:05 -06002822}
2823
John Kessenich6fccb3c2016-09-19 16:01:41 -06002824bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002825{
John Kessenicheee9d532016-09-19 18:09:30 -06002826 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002827}
2828
2829// Make all the functions, skeletally, without actually visiting their bodies.
2830void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2831{
2832 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2833 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002834 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002835 continue;
2836
2837 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002838 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002839 //
qining25262b32016-05-06 17:25:16 -04002840 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002841 // function. What it is an address of varies:
2842 //
John Kessenich4bf71552016-09-02 11:20:21 -06002843 // - "in" parameters not marked as "const" can be written to without modifying the calling
2844 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002845 //
2846 // - "const in" parameters can just be the r-value, as no writes need occur.
2847 //
John Kessenich4bf71552016-09-02 11:20:21 -06002848 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2849 // GLSL has copy-in/copy-out semantics. They can be handled though with a pointer to a copy.
John Kessenich140f3df2015-06-26 16:58:36 -06002850
2851 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002852 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002853 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2854
John Kessenich37789792017-03-21 23:56:40 -06002855 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2856
John Kessenich140f3df2015-06-26 16:58:36 -06002857 for (int p = 0; p < (int)parameters.size(); ++p) {
2858 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2859 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002860 // can we pass by reference?
2861 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002862 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002863 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002864 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002865 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002866 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002867 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2868 else
John Kessenich4bf71552016-09-02 11:20:21 -06002869 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002870 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002871 paramTypes.push_back(typeId);
2872 }
2873
2874 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002875 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2876 convertGlslangToSpvType(glslFunction->getType()),
2877 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002878 if (implicitThis)
2879 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002880
2881 // Track function to emit/call later
2882 functionMap[glslFunction->getName().c_str()] = function;
2883
2884 // Set the parameter id's
2885 for (int p = 0; p < (int)parameters.size(); ++p) {
2886 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2887 // give a name too
2888 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2889 }
2890 }
2891}
2892
2893// Process all the initializers, while skipping the functions and link objects
2894void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2895{
2896 builder.setBuildPoint(shaderEntry->getLastBlock());
2897 for (int i = 0; i < (int)initializers.size(); ++i) {
2898 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2899 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2900
2901 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002902 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002903 initializer->traverse(this);
2904 }
2905 }
2906}
2907
2908// Process all the functions, while skipping initializers.
2909void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2910{
2911 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2912 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002913 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002914 node->traverse(this);
2915 }
2916}
2917
2918void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2919{
qining25262b32016-05-06 17:25:16 -04002920 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002921 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002922 currentFunction = functionMap[node->getName().c_str()];
2923 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002924 builder.setBuildPoint(functionBlock);
2925}
2926
Rex Xu04db3f52015-09-16 11:44:02 +08002927void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002928{
Rex Xufc618912015-09-09 16:42:49 +08002929 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002930
2931 glslang::TSampler sampler = {};
2932 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002933 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002934 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2935 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2936 }
2937
John Kessenich140f3df2015-06-26 16:58:36 -06002938 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2939 builder.clearAccessChain();
2940 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002941
2942 // Special case l-value operands
2943 bool lvalue = false;
2944 switch (node.getOp()) {
2945 case glslang::EOpImageAtomicAdd:
2946 case glslang::EOpImageAtomicMin:
2947 case glslang::EOpImageAtomicMax:
2948 case glslang::EOpImageAtomicAnd:
2949 case glslang::EOpImageAtomicOr:
2950 case glslang::EOpImageAtomicXor:
2951 case glslang::EOpImageAtomicExchange:
2952 case glslang::EOpImageAtomicCompSwap:
2953 if (i == 0)
2954 lvalue = true;
2955 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002956 case glslang::EOpSparseImageLoad:
2957 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2958 lvalue = true;
2959 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002960 case glslang::EOpSparseTexture:
2961 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2962 lvalue = true;
2963 break;
2964 case glslang::EOpSparseTextureClamp:
2965 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
2966 lvalue = true;
2967 break;
2968 case glslang::EOpSparseTextureLod:
2969 case glslang::EOpSparseTextureOffset:
2970 if (i == 3)
2971 lvalue = true;
2972 break;
2973 case glslang::EOpSparseTextureFetch:
2974 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
2975 lvalue = true;
2976 break;
2977 case glslang::EOpSparseTextureFetchOffset:
2978 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
2979 lvalue = true;
2980 break;
2981 case glslang::EOpSparseTextureLodOffset:
2982 case glslang::EOpSparseTextureGrad:
2983 case glslang::EOpSparseTextureOffsetClamp:
2984 if (i == 4)
2985 lvalue = true;
2986 break;
2987 case glslang::EOpSparseTextureGradOffset:
2988 case glslang::EOpSparseTextureGradClamp:
2989 if (i == 5)
2990 lvalue = true;
2991 break;
2992 case glslang::EOpSparseTextureGradOffsetClamp:
2993 if (i == 6)
2994 lvalue = true;
2995 break;
2996 case glslang::EOpSparseTextureGather:
2997 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
2998 lvalue = true;
2999 break;
3000 case glslang::EOpSparseTextureGatherOffset:
3001 case glslang::EOpSparseTextureGatherOffsets:
3002 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3003 lvalue = true;
3004 break;
Rex Xufc618912015-09-09 16:42:49 +08003005 default:
3006 break;
3007 }
3008
Rex Xu6b86d492015-09-16 17:48:22 +08003009 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003010 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003011 else
John Kessenich32cfd492016-02-02 12:37:46 -07003012 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003013 }
3014}
3015
John Kessenichfc51d282015-08-19 13:34:18 -06003016void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003017{
John Kessenichfc51d282015-08-19 13:34:18 -06003018 builder.clearAccessChain();
3019 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003020 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003021}
John Kessenich140f3df2015-06-26 16:58:36 -06003022
John Kessenichfc51d282015-08-19 13:34:18 -06003023spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3024{
Rex Xufc618912015-09-09 16:42:49 +08003025 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06003026 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003027 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003028 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003029
John Kessenichfc51d282015-08-19 13:34:18 -06003030 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003031 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3032 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3033 std::vector<spv::Id> arguments;
3034 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003035 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003036 else
3037 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003038 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003039
3040 spv::Builder::TextureParameters params = { };
3041 params.sampler = arguments[0];
3042
Rex Xu04db3f52015-09-16 11:44:02 +08003043 glslang::TCrackedTextureOp cracked;
3044 node->crackTexture(sampler, cracked);
3045
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003046 const bool isUnsignedResult =
3047 node->getType().getBasicType() == glslang::EbtUint64 ||
3048 node->getType().getBasicType() == glslang::EbtUint;
3049
John Kessenichfc51d282015-08-19 13:34:18 -06003050 // Check for queries
3051 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003052 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3053 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003054 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003055
John Kessenichfc51d282015-08-19 13:34:18 -06003056 switch (node->getOp()) {
3057 case glslang::EOpImageQuerySize:
3058 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003059 if (arguments.size() > 1) {
3060 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003061 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003062 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003063 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003064 case glslang::EOpImageQuerySamples:
3065 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003066 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003067 case glslang::EOpTextureQueryLod:
3068 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003069 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003070 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003071 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003072 case glslang::EOpSparseTexelsResident:
3073 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003074 default:
3075 assert(0);
3076 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003077 }
John Kessenich140f3df2015-06-26 16:58:36 -06003078 }
3079
Rex Xufc618912015-09-09 16:42:49 +08003080 // Check for image functions other than queries
3081 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003082 std::vector<spv::Id> operands;
3083 auto opIt = arguments.begin();
3084 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003085
3086 // Handle subpass operations
3087 // TODO: GLSL should change to have the "MS" only on the type rather than the
3088 // built-in function.
3089 if (cracked.subpass) {
3090 // add on the (0,0) coordinate
3091 spv::Id zero = builder.makeIntConstant(0);
3092 std::vector<spv::Id> comps;
3093 comps.push_back(zero);
3094 comps.push_back(zero);
3095 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3096 if (sampler.ms) {
3097 operands.push_back(spv::ImageOperandsSampleMask);
3098 operands.push_back(*(opIt++));
3099 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003100 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003101 }
3102
John Kessenich56bab042015-09-16 10:54:31 -06003103 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003104 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003105 if (sampler.ms) {
3106 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003107 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003108 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003109 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3110 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003111 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003112 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003113 if (sampler.ms) {
3114 operands.push_back(*(opIt + 1));
3115 operands.push_back(spv::ImageOperandsSampleMask);
3116 operands.push_back(*opIt);
3117 } else
3118 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003119 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003120 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3121 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003122 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003123 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3124 builder.addCapability(spv::CapabilitySparseResidency);
3125 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3126 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3127
3128 if (sampler.ms) {
3129 operands.push_back(spv::ImageOperandsSampleMask);
3130 operands.push_back(*opIt++);
3131 }
3132
3133 // Create the return type that was a special structure
3134 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003135 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003136 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3137 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3138
3139 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3140
3141 // Decode the return type
3142 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3143 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003144 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003145 // Process image atomic operations
3146
3147 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3148 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003149 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003150
John Kessenich8c8505c2016-07-26 12:50:38 -06003151 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003152 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003153
3154 std::vector<spv::Id> operands;
3155 operands.push_back(pointer);
3156 for (; opIt != arguments.end(); ++opIt)
3157 operands.push_back(*opIt);
3158
John Kessenich8c8505c2016-07-26 12:50:38 -06003159 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003160 }
3161 }
3162
3163 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003164 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003165 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3166
John Kessenichfc51d282015-08-19 13:34:18 -06003167 // check for bias argument
3168 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003169 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003170 int nonBiasArgCount = 2;
3171 if (cracked.offset)
3172 ++nonBiasArgCount;
3173 if (cracked.grad)
3174 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003175 if (cracked.lodClamp)
3176 ++nonBiasArgCount;
3177 if (sparse)
3178 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003179
3180 if ((int)arguments.size() > nonBiasArgCount)
3181 bias = true;
3182 }
3183
John Kessenicha5c33d62016-06-02 23:45:21 -06003184 // See if the sampler param should really be just the SPV image part
3185 if (cracked.fetch) {
3186 // a fetch needs to have the image extracted first
3187 if (builder.isSampledImage(params.sampler))
3188 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3189 }
3190
John Kessenichfc51d282015-08-19 13:34:18 -06003191 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003192
John Kessenichfc51d282015-08-19 13:34:18 -06003193 params.coords = arguments[1];
3194 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003195 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003196
3197 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003198 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003199 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003200 ++extraArgs;
3201 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003202 params.Dref = arguments[2];
3203 ++extraArgs;
3204 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003205 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003206 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003207 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003208 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003209 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003210 dRefComp = builder.getNumComponents(params.coords) - 1;
3211 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003212 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3213 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003214
3215 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003216 if (cracked.lod) {
3217 params.lod = arguments[2];
3218 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003219 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3220 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3221 noImplicitLod = true;
3222 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003223
3224 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003225 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003226 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003227 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003228 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003229
3230 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003231 if (cracked.grad) {
3232 params.gradX = arguments[2 + extraArgs];
3233 params.gradY = arguments[3 + extraArgs];
3234 extraArgs += 2;
3235 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003236
3237 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003238 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003239 params.offset = arguments[2 + extraArgs];
3240 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003241 } else if (cracked.offsets) {
3242 params.offsets = arguments[2 + extraArgs];
3243 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003244 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003245
3246 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003247 if (cracked.lodClamp) {
3248 params.lodClamp = arguments[2 + extraArgs];
3249 ++extraArgs;
3250 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003251
3252 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003253 if (sparse) {
3254 params.texelOut = arguments[2 + extraArgs];
3255 ++extraArgs;
3256 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003257
3258 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003259 if (bias) {
3260 params.bias = arguments[2 + extraArgs];
3261 ++extraArgs;
3262 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003263
3264 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003265 if (cracked.gather && ! sampler.shadow) {
3266 // default component is 0, if missing, otherwise an argument
3267 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003268 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003269 ++extraArgs;
3270 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003271 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003272 }
3273 }
John Kessenichfc51d282015-08-19 13:34:18 -06003274
John Kessenich65336482016-06-16 14:06:26 -06003275 // projective component (might not to move)
3276 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3277 // are divided by the last component of P."
3278 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3279 // unused components will appear after all used components."
3280 if (cracked.proj) {
3281 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3282 int projTargetComp;
3283 switch (sampler.dim) {
3284 case glslang::Esd1D: projTargetComp = 1; break;
3285 case glslang::Esd2D: projTargetComp = 2; break;
3286 case glslang::EsdRect: projTargetComp = 2; break;
3287 default: projTargetComp = projSourceComp; break;
3288 }
3289 // copy the projective coordinate if we have to
3290 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003291 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003292 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3293 projSourceComp);
3294 params.coords = builder.createCompositeInsert(projComp, params.coords,
3295 builder.getTypeId(params.coords), projTargetComp);
3296 }
3297 }
3298
John Kessenich8c8505c2016-07-26 12:50:38 -06003299 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003300}
3301
3302spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3303{
3304 // Grab the function's pointer from the previously created function
3305 spv::Function* function = functionMap[node->getName().c_str()];
3306 if (! function)
3307 return 0;
3308
3309 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3310 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3311
3312 // See comments in makeFunctions() for details about the semantics for parameter passing.
3313 //
3314 // These imply we need a four step process:
3315 // 1. Evaluate the arguments
3316 // 2. Allocate and make copies of in, out, and inout arguments
3317 // 3. Make the call
3318 // 4. Copy back the results
3319
3320 // 1. Evaluate the arguments
3321 std::vector<spv::Builder::AccessChain> lValues;
3322 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003323 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003324 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003325 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003326 // build l-value
3327 builder.clearAccessChain();
3328 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003329 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003330 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003331 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003332 // save l-value
3333 lValues.push_back(builder.getAccessChain());
3334 } else {
3335 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003336 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003337 }
3338 }
3339
3340 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3341 // copy the original into that space.
3342 //
3343 // Also, build up the list of actual arguments to pass in for the call
3344 int lValueCount = 0;
3345 int rValueCount = 0;
3346 std::vector<spv::Id> spvArgs;
3347 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003348 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003349 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003350 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003351 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3352 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003353 builder.setAccessChain(lValues[lValueCount]);
3354 arg = builder.accessChainGetLValue();
3355 ++lValueCount;
3356 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003357 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003358 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3359 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3360 // need to copy the input into output space
3361 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003362 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003363 builder.clearAccessChain();
3364 builder.setAccessChainLValue(arg);
3365 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003366 }
3367 ++lValueCount;
3368 } else {
3369 arg = rValues[rValueCount];
3370 ++rValueCount;
3371 }
3372 spvArgs.push_back(arg);
3373 }
3374
3375 // 3. Make the call.
3376 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003377 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003378
3379 // 4. Copy back out an "out" arguments.
3380 lValueCount = 0;
3381 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003382 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003383 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3384 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3385 spv::Id copy = builder.createLoad(spvArgs[a]);
3386 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003387 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003388 }
3389 ++lValueCount;
3390 }
3391 }
3392
3393 return result;
3394}
3395
3396// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003397spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3398 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003399 spv::Id typeId, spv::Id left, spv::Id right,
3400 glslang::TBasicType typeProxy, bool reduceComparison)
3401{
Rex Xu8ff43de2016-04-22 16:51:45 +08003402 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003403#ifdef AMD_EXTENSIONS
3404 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3405#else
John Kessenich140f3df2015-06-26 16:58:36 -06003406 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003407#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003408 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003409
3410 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003411 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003412 bool comparison = false;
3413
3414 switch (op) {
3415 case glslang::EOpAdd:
3416 case glslang::EOpAddAssign:
3417 if (isFloat)
3418 binOp = spv::OpFAdd;
3419 else
3420 binOp = spv::OpIAdd;
3421 break;
3422 case glslang::EOpSub:
3423 case glslang::EOpSubAssign:
3424 if (isFloat)
3425 binOp = spv::OpFSub;
3426 else
3427 binOp = spv::OpISub;
3428 break;
3429 case glslang::EOpMul:
3430 case glslang::EOpMulAssign:
3431 if (isFloat)
3432 binOp = spv::OpFMul;
3433 else
3434 binOp = spv::OpIMul;
3435 break;
3436 case glslang::EOpVectorTimesScalar:
3437 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003438 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003439 if (builder.isVector(right))
3440 std::swap(left, right);
3441 assert(builder.isScalar(right));
3442 needMatchingVectors = false;
3443 binOp = spv::OpVectorTimesScalar;
3444 } else
3445 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003446 break;
3447 case glslang::EOpVectorTimesMatrix:
3448 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003449 binOp = spv::OpVectorTimesMatrix;
3450 break;
3451 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003452 binOp = spv::OpMatrixTimesVector;
3453 break;
3454 case glslang::EOpMatrixTimesScalar:
3455 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003456 binOp = spv::OpMatrixTimesScalar;
3457 break;
3458 case glslang::EOpMatrixTimesMatrix:
3459 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003460 binOp = spv::OpMatrixTimesMatrix;
3461 break;
3462 case glslang::EOpOuterProduct:
3463 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003464 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003465 break;
3466
3467 case glslang::EOpDiv:
3468 case glslang::EOpDivAssign:
3469 if (isFloat)
3470 binOp = spv::OpFDiv;
3471 else if (isUnsigned)
3472 binOp = spv::OpUDiv;
3473 else
3474 binOp = spv::OpSDiv;
3475 break;
3476 case glslang::EOpMod:
3477 case glslang::EOpModAssign:
3478 if (isFloat)
3479 binOp = spv::OpFMod;
3480 else if (isUnsigned)
3481 binOp = spv::OpUMod;
3482 else
3483 binOp = spv::OpSMod;
3484 break;
3485 case glslang::EOpRightShift:
3486 case glslang::EOpRightShiftAssign:
3487 if (isUnsigned)
3488 binOp = spv::OpShiftRightLogical;
3489 else
3490 binOp = spv::OpShiftRightArithmetic;
3491 break;
3492 case glslang::EOpLeftShift:
3493 case glslang::EOpLeftShiftAssign:
3494 binOp = spv::OpShiftLeftLogical;
3495 break;
3496 case glslang::EOpAnd:
3497 case glslang::EOpAndAssign:
3498 binOp = spv::OpBitwiseAnd;
3499 break;
3500 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003501 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003502 binOp = spv::OpLogicalAnd;
3503 break;
3504 case glslang::EOpInclusiveOr:
3505 case glslang::EOpInclusiveOrAssign:
3506 binOp = spv::OpBitwiseOr;
3507 break;
3508 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003509 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003510 binOp = spv::OpLogicalOr;
3511 break;
3512 case glslang::EOpExclusiveOr:
3513 case glslang::EOpExclusiveOrAssign:
3514 binOp = spv::OpBitwiseXor;
3515 break;
3516 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003517 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003518 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003519 break;
3520
3521 case glslang::EOpLessThan:
3522 case glslang::EOpGreaterThan:
3523 case glslang::EOpLessThanEqual:
3524 case glslang::EOpGreaterThanEqual:
3525 case glslang::EOpEqual:
3526 case glslang::EOpNotEqual:
3527 case glslang::EOpVectorEqual:
3528 case glslang::EOpVectorNotEqual:
3529 comparison = true;
3530 break;
3531 default:
3532 break;
3533 }
3534
John Kessenich7c1aa102015-10-15 13:29:11 -06003535 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003536 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003537 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003538 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003539 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003540
3541 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003542 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003543 builder.promoteScalar(precision, left, right);
3544
qining25262b32016-05-06 17:25:16 -04003545 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3546 addDecoration(result, noContraction);
3547 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003548 }
3549
3550 if (! comparison)
3551 return 0;
3552
John Kessenich7c1aa102015-10-15 13:29:11 -06003553 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003554
John Kessenich4583b612016-08-07 19:14:22 -06003555 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3556 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003557 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003558
3559 switch (op) {
3560 case glslang::EOpLessThan:
3561 if (isFloat)
3562 binOp = spv::OpFOrdLessThan;
3563 else if (isUnsigned)
3564 binOp = spv::OpULessThan;
3565 else
3566 binOp = spv::OpSLessThan;
3567 break;
3568 case glslang::EOpGreaterThan:
3569 if (isFloat)
3570 binOp = spv::OpFOrdGreaterThan;
3571 else if (isUnsigned)
3572 binOp = spv::OpUGreaterThan;
3573 else
3574 binOp = spv::OpSGreaterThan;
3575 break;
3576 case glslang::EOpLessThanEqual:
3577 if (isFloat)
3578 binOp = spv::OpFOrdLessThanEqual;
3579 else if (isUnsigned)
3580 binOp = spv::OpULessThanEqual;
3581 else
3582 binOp = spv::OpSLessThanEqual;
3583 break;
3584 case glslang::EOpGreaterThanEqual:
3585 if (isFloat)
3586 binOp = spv::OpFOrdGreaterThanEqual;
3587 else if (isUnsigned)
3588 binOp = spv::OpUGreaterThanEqual;
3589 else
3590 binOp = spv::OpSGreaterThanEqual;
3591 break;
3592 case glslang::EOpEqual:
3593 case glslang::EOpVectorEqual:
3594 if (isFloat)
3595 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003596 else if (isBool)
3597 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003598 else
3599 binOp = spv::OpIEqual;
3600 break;
3601 case glslang::EOpNotEqual:
3602 case glslang::EOpVectorNotEqual:
3603 if (isFloat)
3604 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003605 else if (isBool)
3606 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003607 else
3608 binOp = spv::OpINotEqual;
3609 break;
3610 default:
3611 break;
3612 }
3613
qining25262b32016-05-06 17:25:16 -04003614 if (binOp != spv::OpNop) {
3615 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3616 addDecoration(result, noContraction);
3617 return builder.setPrecision(result, precision);
3618 }
John Kessenich140f3df2015-06-26 16:58:36 -06003619
3620 return 0;
3621}
3622
John Kessenich04bb8a02015-12-12 12:28:14 -07003623//
3624// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3625// These can be any of:
3626//
3627// matrix * scalar
3628// scalar * matrix
3629// matrix * matrix linear algebraic
3630// matrix * vector
3631// vector * matrix
3632// matrix * matrix componentwise
3633// matrix op matrix op in {+, -, /}
3634// matrix op scalar op in {+, -, /}
3635// scalar op matrix op in {+, -, /}
3636//
qining25262b32016-05-06 17:25:16 -04003637spv::Id TGlslangToSpvTraverser::createBinaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right)
John Kessenich04bb8a02015-12-12 12:28:14 -07003638{
3639 bool firstClass = true;
3640
3641 // First, handle first-class matrix operations (* and matrix/scalar)
3642 switch (op) {
3643 case spv::OpFDiv:
3644 if (builder.isMatrix(left) && builder.isScalar(right)) {
3645 // turn matrix / scalar into a multiply...
3646 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3647 op = spv::OpMatrixTimesScalar;
3648 } else
3649 firstClass = false;
3650 break;
3651 case spv::OpMatrixTimesScalar:
3652 if (builder.isMatrix(right))
3653 std::swap(left, right);
3654 assert(builder.isScalar(right));
3655 break;
3656 case spv::OpVectorTimesMatrix:
3657 assert(builder.isVector(left));
3658 assert(builder.isMatrix(right));
3659 break;
3660 case spv::OpMatrixTimesVector:
3661 assert(builder.isMatrix(left));
3662 assert(builder.isVector(right));
3663 break;
3664 case spv::OpMatrixTimesMatrix:
3665 assert(builder.isMatrix(left));
3666 assert(builder.isMatrix(right));
3667 break;
3668 default:
3669 firstClass = false;
3670 break;
3671 }
3672
qining25262b32016-05-06 17:25:16 -04003673 if (firstClass) {
3674 spv::Id result = builder.createBinOp(op, typeId, left, right);
3675 addDecoration(result, noContraction);
3676 return builder.setPrecision(result, precision);
3677 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003678
LoopDawg592860c2016-06-09 08:57:35 -06003679 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003680 // The result type of all of them is the same type as the (a) matrix operand.
3681 // The algorithm is to:
3682 // - break the matrix(es) into vectors
3683 // - smear any scalar to a vector
3684 // - do vector operations
3685 // - make a matrix out the vector results
3686 switch (op) {
3687 case spv::OpFAdd:
3688 case spv::OpFSub:
3689 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003690 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003691 case spv::OpFMul:
3692 {
3693 // one time set up...
3694 bool leftMat = builder.isMatrix(left);
3695 bool rightMat = builder.isMatrix(right);
3696 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3697 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3698 spv::Id scalarType = builder.getScalarTypeId(typeId);
3699 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3700 std::vector<spv::Id> results;
3701 spv::Id smearVec = spv::NoResult;
3702 if (builder.isScalar(left))
3703 smearVec = builder.smearScalar(precision, left, vecType);
3704 else if (builder.isScalar(right))
3705 smearVec = builder.smearScalar(precision, right, vecType);
3706
3707 // do each vector op
3708 for (unsigned int c = 0; c < numCols; ++c) {
3709 std::vector<unsigned int> indexes;
3710 indexes.push_back(c);
3711 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3712 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003713 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3714 addDecoration(result, noContraction);
3715 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003716 }
3717
3718 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003719 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003720 }
3721 default:
3722 assert(0);
3723 return spv::NoResult;
3724 }
3725}
3726
qining25262b32016-05-06 17:25:16 -04003727spv::Id TGlslangToSpvTraverser::createUnaryOperation(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06003728{
3729 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003730 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003731 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003732 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003733#ifdef AMD_EXTENSIONS
3734 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3735#else
Rex Xu04db3f52015-09-16 11:44:02 +08003736 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003737#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003738
3739 switch (op) {
3740 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003741 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003742 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003743 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003744 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003745 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003746 unaryOp = spv::OpSNegate;
3747 break;
3748
3749 case glslang::EOpLogicalNot:
3750 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003751 unaryOp = spv::OpLogicalNot;
3752 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003753 case glslang::EOpBitwiseNot:
3754 unaryOp = spv::OpNot;
3755 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003756
John Kessenich140f3df2015-06-26 16:58:36 -06003757 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003758 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003759 break;
3760 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003761 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003762 break;
3763 case glslang::EOpTranspose:
3764 unaryOp = spv::OpTranspose;
3765 break;
3766
3767 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003768 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003769 break;
3770 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003771 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003772 break;
3773 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003774 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003775 break;
3776 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003777 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003778 break;
3779 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003780 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003781 break;
3782 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003783 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003784 break;
3785 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003787 break;
3788 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003789 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003790 break;
3791
3792 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003793 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003794 break;
3795 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003796 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003797 break;
3798 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003799 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003800 break;
3801 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003802 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003803 break;
3804 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003805 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003806 break;
3807 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003808 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003809 break;
3810
3811 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003812 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003813 break;
3814 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003815 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003816 break;
3817
3818 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003819 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003820 break;
3821 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003822 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003823 break;
3824 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003825 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003826 break;
3827 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003828 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003829 break;
3830 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003831 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003832 break;
3833 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003834 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003835 break;
3836
3837 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003838 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003839 break;
3840 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003841 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003842 break;
3843 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003844 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003845 break;
3846 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003847 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003848 break;
3849 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003850 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003851 break;
3852 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003853 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003854 break;
3855
3856 case glslang::EOpIsNan:
3857 unaryOp = spv::OpIsNan;
3858 break;
3859 case glslang::EOpIsInf:
3860 unaryOp = spv::OpIsInf;
3861 break;
LoopDawg592860c2016-06-09 08:57:35 -06003862 case glslang::EOpIsFinite:
3863 unaryOp = spv::OpIsFinite;
3864 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003865
Rex Xucbc426e2015-12-15 16:03:10 +08003866 case glslang::EOpFloatBitsToInt:
3867 case glslang::EOpFloatBitsToUint:
3868 case glslang::EOpIntBitsToFloat:
3869 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003870 case glslang::EOpDoubleBitsToInt64:
3871 case glslang::EOpDoubleBitsToUint64:
3872 case glslang::EOpInt64BitsToDouble:
3873 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003874 unaryOp = spv::OpBitcast;
3875 break;
3876
John Kessenich140f3df2015-06-26 16:58:36 -06003877 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003878 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003879 break;
3880 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003881 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003882 break;
3883 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003884 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003885 break;
3886 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003887 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003888 break;
3889 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003890 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003891 break;
3892 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003893 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003894 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003895 case glslang::EOpPackSnorm4x8:
3896 libCall = spv::GLSLstd450PackSnorm4x8;
3897 break;
3898 case glslang::EOpUnpackSnorm4x8:
3899 libCall = spv::GLSLstd450UnpackSnorm4x8;
3900 break;
3901 case glslang::EOpPackUnorm4x8:
3902 libCall = spv::GLSLstd450PackUnorm4x8;
3903 break;
3904 case glslang::EOpUnpackUnorm4x8:
3905 libCall = spv::GLSLstd450UnpackUnorm4x8;
3906 break;
3907 case glslang::EOpPackDouble2x32:
3908 libCall = spv::GLSLstd450PackDouble2x32;
3909 break;
3910 case glslang::EOpUnpackDouble2x32:
3911 libCall = spv::GLSLstd450UnpackDouble2x32;
3912 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003913
Rex Xu8ff43de2016-04-22 16:51:45 +08003914 case glslang::EOpPackInt2x32:
3915 case glslang::EOpUnpackInt2x32:
3916 case glslang::EOpPackUint2x32:
3917 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003918 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003919 break;
3920
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003921#ifdef AMD_EXTENSIONS
3922 case glslang::EOpPackFloat2x16:
3923 case glslang::EOpUnpackFloat2x16:
3924 unaryOp = spv::OpBitcast;
3925 break;
3926#endif
3927
John Kessenich140f3df2015-06-26 16:58:36 -06003928 case glslang::EOpDPdx:
3929 unaryOp = spv::OpDPdx;
3930 break;
3931 case glslang::EOpDPdy:
3932 unaryOp = spv::OpDPdy;
3933 break;
3934 case glslang::EOpFwidth:
3935 unaryOp = spv::OpFwidth;
3936 break;
3937 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003938 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003939 unaryOp = spv::OpDPdxFine;
3940 break;
3941 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003942 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003943 unaryOp = spv::OpDPdyFine;
3944 break;
3945 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003946 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003947 unaryOp = spv::OpFwidthFine;
3948 break;
3949 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003950 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003951 unaryOp = spv::OpDPdxCoarse;
3952 break;
3953 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003954 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003955 unaryOp = spv::OpDPdyCoarse;
3956 break;
3957 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003958 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003959 unaryOp = spv::OpFwidthCoarse;
3960 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003961 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003962 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003963 libCall = spv::GLSLstd450InterpolateAtCentroid;
3964 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003965 case glslang::EOpAny:
3966 unaryOp = spv::OpAny;
3967 break;
3968 case glslang::EOpAll:
3969 unaryOp = spv::OpAll;
3970 break;
3971
3972 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06003973 if (isFloat)
3974 libCall = spv::GLSLstd450FAbs;
3975 else
3976 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06003977 break;
3978 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06003979 if (isFloat)
3980 libCall = spv::GLSLstd450FSign;
3981 else
3982 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06003983 break;
3984
John Kessenichfc51d282015-08-19 13:34:18 -06003985 case glslang::EOpAtomicCounterIncrement:
3986 case glslang::EOpAtomicCounterDecrement:
3987 case glslang::EOpAtomicCounter:
3988 {
3989 // Handle all of the atomics in one place, in createAtomicOperation()
3990 std::vector<spv::Id> operands;
3991 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08003992 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06003993 }
3994
John Kessenichfc51d282015-08-19 13:34:18 -06003995 case glslang::EOpBitFieldReverse:
3996 unaryOp = spv::OpBitReverse;
3997 break;
3998 case glslang::EOpBitCount:
3999 unaryOp = spv::OpBitCount;
4000 break;
4001 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004002 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004003 break;
4004 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004005 if (isUnsigned)
4006 libCall = spv::GLSLstd450FindUMsb;
4007 else
4008 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004009 break;
4010
Rex Xu574ab042016-04-14 16:53:07 +08004011 case glslang::EOpBallot:
4012 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004013 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004014 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004015 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004016#ifdef AMD_EXTENSIONS
4017 case glslang::EOpMinInvocations:
4018 case glslang::EOpMaxInvocations:
4019 case glslang::EOpAddInvocations:
4020 case glslang::EOpMinInvocationsNonUniform:
4021 case glslang::EOpMaxInvocationsNonUniform:
4022 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004023 case glslang::EOpMinInvocationsInclusiveScan:
4024 case glslang::EOpMaxInvocationsInclusiveScan:
4025 case glslang::EOpAddInvocationsInclusiveScan:
4026 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4027 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4028 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4029 case glslang::EOpMinInvocationsExclusiveScan:
4030 case glslang::EOpMaxInvocationsExclusiveScan:
4031 case glslang::EOpAddInvocationsExclusiveScan:
4032 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4033 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4034 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004035#endif
Rex Xu51596642016-09-21 18:56:12 +08004036 {
4037 std::vector<spv::Id> operands;
4038 operands.push_back(operand);
4039 return createInvocationsOperation(op, typeId, operands, typeProxy);
4040 }
Rex Xu9d93a232016-05-05 12:30:44 +08004041
4042#ifdef AMD_EXTENSIONS
4043 case glslang::EOpMbcnt:
4044 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4045 libCall = spv::MbcntAMD;
4046 break;
4047
4048 case glslang::EOpCubeFaceIndex:
4049 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4050 libCall = spv::CubeFaceIndexAMD;
4051 break;
4052
4053 case glslang::EOpCubeFaceCoord:
4054 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4055 libCall = spv::CubeFaceCoordAMD;
4056 break;
4057#endif
Rex Xu338b1852016-05-05 20:38:33 +08004058
John Kessenich140f3df2015-06-26 16:58:36 -06004059 default:
4060 return 0;
4061 }
4062
4063 spv::Id id;
4064 if (libCall >= 0) {
4065 std::vector<spv::Id> args;
4066 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004067 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004068 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004069 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004070 }
John Kessenich140f3df2015-06-26 16:58:36 -06004071
qining25262b32016-05-06 17:25:16 -04004072 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004073 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004074}
4075
John Kessenich7a53f762016-01-20 11:19:27 -07004076// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004077spv::Id TGlslangToSpvTraverser::createUnaryMatrixOperation(spv::Op op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id operand, glslang::TBasicType /* typeProxy */)
John Kessenich7a53f762016-01-20 11:19:27 -07004078{
4079 // Handle unary operations vector by vector.
4080 // The result type is the same type as the original type.
4081 // The algorithm is to:
4082 // - break the matrix into vectors
4083 // - apply the operation to each vector
4084 // - make a matrix out the vector results
4085
4086 // get the types sorted out
4087 int numCols = builder.getNumColumns(operand);
4088 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004089 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4090 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004091 std::vector<spv::Id> results;
4092
4093 // do each vector op
4094 for (int c = 0; c < numCols; ++c) {
4095 std::vector<unsigned int> indexes;
4096 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004097 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4098 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4099 addDecoration(destVec, noContraction);
4100 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004101 }
4102
4103 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004104 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004105}
4106
Rex Xu73e3ce72016-04-27 18:48:17 +08004107spv::Id TGlslangToSpvTraverser::createConversion(glslang::TOperator op, spv::Decoration precision, spv::Decoration noContraction, spv::Id destType, spv::Id operand, glslang::TBasicType typeProxy)
John Kessenich140f3df2015-06-26 16:58:36 -06004108{
4109 spv::Op convOp = spv::OpNop;
4110 spv::Id zero = 0;
4111 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004112 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004113
4114 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4115
4116 switch (op) {
4117 case glslang::EOpConvIntToBool:
4118 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004119 case glslang::EOpConvInt64ToBool:
4120 case glslang::EOpConvUint64ToBool:
4121 zero = (op == glslang::EOpConvInt64ToBool ||
4122 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004123 zero = makeSmearedConstant(zero, vectorSize);
4124 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4125
4126 case glslang::EOpConvFloatToBool:
4127 zero = builder.makeFloatConstant(0.0F);
4128 zero = makeSmearedConstant(zero, vectorSize);
4129 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4130
4131 case glslang::EOpConvDoubleToBool:
4132 zero = builder.makeDoubleConstant(0.0);
4133 zero = makeSmearedConstant(zero, vectorSize);
4134 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4135
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004136#ifdef AMD_EXTENSIONS
4137 case glslang::EOpConvFloat16ToBool:
4138 zero = builder.makeFloat16Constant(0.0F);
4139 zero = makeSmearedConstant(zero, vectorSize);
4140 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4141#endif
4142
John Kessenich140f3df2015-06-26 16:58:36 -06004143 case glslang::EOpConvBoolToFloat:
4144 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004145 zero = builder.makeFloatConstant(0.0F);
4146 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004147 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004148
John Kessenich140f3df2015-06-26 16:58:36 -06004149 case glslang::EOpConvBoolToDouble:
4150 convOp = spv::OpSelect;
4151 zero = builder.makeDoubleConstant(0.0);
4152 one = builder.makeDoubleConstant(1.0);
4153 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004154
4155#ifdef AMD_EXTENSIONS
4156 case glslang::EOpConvBoolToFloat16:
4157 convOp = spv::OpSelect;
4158 zero = builder.makeFloat16Constant(0.0F);
4159 one = builder.makeFloat16Constant(1.0F);
4160 break;
4161#endif
4162
John Kessenich140f3df2015-06-26 16:58:36 -06004163 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004164 case glslang::EOpConvBoolToInt64:
4165 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4166 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004167 convOp = spv::OpSelect;
4168 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004169
John Kessenich140f3df2015-06-26 16:58:36 -06004170 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004171 case glslang::EOpConvBoolToUint64:
4172 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4173 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004174 convOp = spv::OpSelect;
4175 break;
4176
4177 case glslang::EOpConvIntToFloat:
4178 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004179 case glslang::EOpConvInt64ToFloat:
4180 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004181#ifdef AMD_EXTENSIONS
4182 case glslang::EOpConvIntToFloat16:
4183 case glslang::EOpConvInt64ToFloat16:
4184#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004185 convOp = spv::OpConvertSToF;
4186 break;
4187
4188 case glslang::EOpConvUintToFloat:
4189 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004190 case glslang::EOpConvUint64ToFloat:
4191 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004192#ifdef AMD_EXTENSIONS
4193 case glslang::EOpConvUintToFloat16:
4194 case glslang::EOpConvUint64ToFloat16:
4195#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004196 convOp = spv::OpConvertUToF;
4197 break;
4198
4199 case glslang::EOpConvDoubleToFloat:
4200 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004201#ifdef AMD_EXTENSIONS
4202 case glslang::EOpConvDoubleToFloat16:
4203 case glslang::EOpConvFloat16ToDouble:
4204 case glslang::EOpConvFloatToFloat16:
4205 case glslang::EOpConvFloat16ToFloat:
4206#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004207 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004208 if (builder.isMatrixType(destType))
4209 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004210 break;
4211
4212 case glslang::EOpConvFloatToInt:
4213 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004214 case glslang::EOpConvFloatToInt64:
4215 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004216#ifdef AMD_EXTENSIONS
4217 case glslang::EOpConvFloat16ToInt:
4218 case glslang::EOpConvFloat16ToInt64:
4219#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004220 convOp = spv::OpConvertFToS;
4221 break;
4222
4223 case glslang::EOpConvUintToInt:
4224 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004225 case glslang::EOpConvUint64ToInt64:
4226 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004227 if (builder.isInSpecConstCodeGenMode()) {
4228 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004229 zero = (op == glslang::EOpConvUint64ToInt64 ||
4230 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004231 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004232 // Use OpIAdd, instead of OpBitcast to do the conversion when
4233 // generating for OpSpecConstantOp instruction.
4234 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4235 }
4236 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004237 convOp = spv::OpBitcast;
4238 break;
4239
4240 case glslang::EOpConvFloatToUint:
4241 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004242 case glslang::EOpConvFloatToUint64:
4243 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004244#ifdef AMD_EXTENSIONS
4245 case glslang::EOpConvFloat16ToUint:
4246 case glslang::EOpConvFloat16ToUint64:
4247#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004248 convOp = spv::OpConvertFToU;
4249 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004250
4251 case glslang::EOpConvIntToInt64:
4252 case glslang::EOpConvInt64ToInt:
4253 convOp = spv::OpSConvert;
4254 break;
4255
4256 case glslang::EOpConvUintToUint64:
4257 case glslang::EOpConvUint64ToUint:
4258 convOp = spv::OpUConvert;
4259 break;
4260
4261 case glslang::EOpConvIntToUint64:
4262 case glslang::EOpConvInt64ToUint:
4263 case glslang::EOpConvUint64ToInt:
4264 case glslang::EOpConvUintToInt64:
4265 // OpSConvert/OpUConvert + OpBitCast
4266 switch (op) {
4267 case glslang::EOpConvIntToUint64:
4268 convOp = spv::OpSConvert;
4269 type = builder.makeIntType(64);
4270 break;
4271 case glslang::EOpConvInt64ToUint:
4272 convOp = spv::OpSConvert;
4273 type = builder.makeIntType(32);
4274 break;
4275 case glslang::EOpConvUint64ToInt:
4276 convOp = spv::OpUConvert;
4277 type = builder.makeUintType(32);
4278 break;
4279 case glslang::EOpConvUintToInt64:
4280 convOp = spv::OpUConvert;
4281 type = builder.makeUintType(64);
4282 break;
4283 default:
4284 assert(0);
4285 break;
4286 }
4287
4288 if (vectorSize > 0)
4289 type = builder.makeVectorType(type, vectorSize);
4290
4291 operand = builder.createUnaryOp(convOp, type, operand);
4292
4293 if (builder.isInSpecConstCodeGenMode()) {
4294 // Build zero scalar or vector for OpIAdd.
4295 zero = (op == glslang::EOpConvIntToUint64 ||
4296 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4297 zero = makeSmearedConstant(zero, vectorSize);
4298 // Use OpIAdd, instead of OpBitcast to do the conversion when
4299 // generating for OpSpecConstantOp instruction.
4300 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4301 }
4302 // For normal run-time conversion instruction, use OpBitcast.
4303 convOp = spv::OpBitcast;
4304 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004305 default:
4306 break;
4307 }
4308
4309 spv::Id result = 0;
4310 if (convOp == spv::OpNop)
4311 return result;
4312
4313 if (convOp == spv::OpSelect) {
4314 zero = makeSmearedConstant(zero, vectorSize);
4315 one = makeSmearedConstant(one, vectorSize);
4316 result = builder.createTriOp(convOp, destType, operand, one, zero);
4317 } else
4318 result = builder.createUnaryOp(convOp, destType, operand);
4319
John Kessenich32cfd492016-02-02 12:37:46 -07004320 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004321}
4322
4323spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4324{
4325 if (vectorSize == 0)
4326 return constant;
4327
4328 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4329 std::vector<spv::Id> components;
4330 for (int c = 0; c < vectorSize; ++c)
4331 components.push_back(constant);
4332 return builder.makeCompositeConstant(vectorTypeId, components);
4333}
4334
John Kessenich426394d2015-07-23 10:22:48 -06004335// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004336spv::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 -06004337{
4338 spv::Op opCode = spv::OpNop;
4339
4340 switch (op) {
4341 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004342 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004343 opCode = spv::OpAtomicIAdd;
4344 break;
4345 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004346 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004347 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004348 break;
4349 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004350 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004351 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004352 break;
4353 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004354 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004355 opCode = spv::OpAtomicAnd;
4356 break;
4357 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004358 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004359 opCode = spv::OpAtomicOr;
4360 break;
4361 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004362 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004363 opCode = spv::OpAtomicXor;
4364 break;
4365 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004366 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004367 opCode = spv::OpAtomicExchange;
4368 break;
4369 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004370 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004371 opCode = spv::OpAtomicCompareExchange;
4372 break;
4373 case glslang::EOpAtomicCounterIncrement:
4374 opCode = spv::OpAtomicIIncrement;
4375 break;
4376 case glslang::EOpAtomicCounterDecrement:
4377 opCode = spv::OpAtomicIDecrement;
4378 break;
4379 case glslang::EOpAtomicCounter:
4380 opCode = spv::OpAtomicLoad;
4381 break;
4382 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004383 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004384 break;
4385 }
4386
4387 // Sort out the operands
4388 // - mapping from glslang -> SPV
4389 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004390 // - compare-exchange swaps the value and comparator
4391 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004392 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4393 auto opIt = operands.begin(); // walk the glslang operands
4394 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004395 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4396 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4397 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004398 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4399 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004400 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004401 spvAtomicOperands.push_back(*(opIt + 1));
4402 spvAtomicOperands.push_back(*opIt);
4403 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004404 }
John Kessenich426394d2015-07-23 10:22:48 -06004405
John Kessenich3e60a6f2015-09-14 22:45:16 -06004406 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004407 for (; opIt != operands.end(); ++opIt)
4408 spvAtomicOperands.push_back(*opIt);
4409
4410 return builder.createOp(opCode, typeId, spvAtomicOperands);
4411}
4412
John Kessenich91cef522016-05-05 16:45:40 -06004413// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004414spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004415{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004416#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004417 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004418 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004419#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004420
Rex Xu51596642016-09-21 18:56:12 +08004421 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004422 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004423 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4424
chaocf200da82016-12-20 12:44:35 -08004425 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4426 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004427 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4428 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004429 } else if (op == glslang::EOpAnyInvocation ||
4430 op == glslang::EOpAllInvocations ||
4431 op == glslang::EOpAllInvocationsEqual) {
4432 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4433 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004434 } else {
4435 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004436#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004437 if (op == glslang::EOpMinInvocationsNonUniform ||
4438 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004439 op == glslang::EOpAddInvocationsNonUniform ||
4440 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4441 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4442 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4443 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4444 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4445 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004446 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004447#endif
Rex Xu51596642016-09-21 18:56:12 +08004448
4449 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004450#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004451 switch (op) {
4452 case glslang::EOpMinInvocations:
4453 case glslang::EOpMaxInvocations:
4454 case glslang::EOpAddInvocations:
4455 case glslang::EOpMinInvocationsNonUniform:
4456 case glslang::EOpMaxInvocationsNonUniform:
4457 case glslang::EOpAddInvocationsNonUniform:
4458 groupOperation = spv::GroupOperationReduce;
4459 spvGroupOperands.push_back(groupOperation);
4460 break;
4461 case glslang::EOpMinInvocationsInclusiveScan:
4462 case glslang::EOpMaxInvocationsInclusiveScan:
4463 case glslang::EOpAddInvocationsInclusiveScan:
4464 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4465 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4466 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4467 groupOperation = spv::GroupOperationInclusiveScan;
4468 spvGroupOperands.push_back(groupOperation);
4469 break;
4470 case glslang::EOpMinInvocationsExclusiveScan:
4471 case glslang::EOpMaxInvocationsExclusiveScan:
4472 case glslang::EOpAddInvocationsExclusiveScan:
4473 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4474 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4475 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4476 groupOperation = spv::GroupOperationExclusiveScan;
4477 spvGroupOperands.push_back(groupOperation);
4478 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004479 default:
4480 break;
Rex Xu430ef402016-10-14 17:22:23 +08004481 }
Rex Xu9d93a232016-05-05 12:30:44 +08004482#endif
Rex Xu51596642016-09-21 18:56:12 +08004483 }
4484
4485 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4486 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004487
4488 switch (op) {
4489 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004490 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004491 break;
John Kessenich91cef522016-05-05 16:45:40 -06004492 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004493 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004494 break;
John Kessenich91cef522016-05-05 16:45:40 -06004495 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004496 opCode = spv::OpSubgroupAllEqualKHR;
4497 break;
Rex Xu51596642016-09-21 18:56:12 +08004498 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004499 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004500 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004501 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004502 break;
4503 case glslang::EOpReadFirstInvocation:
4504 opCode = spv::OpSubgroupFirstInvocationKHR;
4505 break;
4506 case glslang::EOpBallot:
4507 {
4508 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4509 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4510 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4511 //
4512 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4513 //
4514 spv::Id uintType = builder.makeUintType(32);
4515 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4516 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4517
4518 std::vector<spv::Id> components;
4519 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4520 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4521
4522 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4523 return builder.createUnaryOp(spv::OpBitcast, typeId,
4524 builder.createCompositeConstruct(uvec2Type, components));
4525 }
4526
Rex Xu9d93a232016-05-05 12:30:44 +08004527#ifdef AMD_EXTENSIONS
4528 case glslang::EOpMinInvocations:
4529 case glslang::EOpMaxInvocations:
4530 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004531 case glslang::EOpMinInvocationsInclusiveScan:
4532 case glslang::EOpMaxInvocationsInclusiveScan:
4533 case glslang::EOpAddInvocationsInclusiveScan:
4534 case glslang::EOpMinInvocationsExclusiveScan:
4535 case glslang::EOpMaxInvocationsExclusiveScan:
4536 case glslang::EOpAddInvocationsExclusiveScan:
4537 if (op == glslang::EOpMinInvocations ||
4538 op == glslang::EOpMinInvocationsInclusiveScan ||
4539 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004540 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004541 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004542 else {
4543 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004544 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004545 else
Rex Xu51596642016-09-21 18:56:12 +08004546 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004547 }
Rex Xu430ef402016-10-14 17:22:23 +08004548 } else if (op == glslang::EOpMaxInvocations ||
4549 op == glslang::EOpMaxInvocationsInclusiveScan ||
4550 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004551 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004552 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004553 else {
4554 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004555 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004556 else
Rex Xu51596642016-09-21 18:56:12 +08004557 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004558 }
4559 } else {
4560 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004561 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004562 else
Rex Xu51596642016-09-21 18:56:12 +08004563 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004564 }
4565
Rex Xu2bbbe062016-08-23 15:41:05 +08004566 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004567 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004568
4569 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004570 case glslang::EOpMinInvocationsNonUniform:
4571 case glslang::EOpMaxInvocationsNonUniform:
4572 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004573 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4574 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4575 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4576 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4577 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4578 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4579 if (op == glslang::EOpMinInvocationsNonUniform ||
4580 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4581 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004582 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004583 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004584 else {
4585 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004586 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004587 else
Rex Xu51596642016-09-21 18:56:12 +08004588 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004589 }
4590 }
Rex Xu430ef402016-10-14 17:22:23 +08004591 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4592 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4593 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004594 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004595 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004596 else {
4597 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004598 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004599 else
Rex Xu51596642016-09-21 18:56:12 +08004600 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004601 }
4602 }
4603 else {
4604 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004605 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004606 else
Rex Xu51596642016-09-21 18:56:12 +08004607 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004608 }
4609
Rex Xu2bbbe062016-08-23 15:41:05 +08004610 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004611 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004612
4613 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004614#endif
John Kessenich91cef522016-05-05 16:45:40 -06004615 default:
4616 logger->missingFunctionality("invocation operation");
4617 return spv::NoResult;
4618 }
Rex Xu51596642016-09-21 18:56:12 +08004619
4620 assert(opCode != spv::OpNop);
4621 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004622}
4623
Rex Xu2bbbe062016-08-23 15:41:05 +08004624// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004625spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004626{
Rex Xub7072052016-09-26 15:53:40 +08004627#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004628 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4629 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004630 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004631 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004632 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4633 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4634 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004635#else
4636 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4637 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004638 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4639 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004640#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004641
4642 // Handle group invocation operations scalar by scalar.
4643 // The result type is the same type as the original type.
4644 // The algorithm is to:
4645 // - break the vector into scalars
4646 // - apply the operation to each scalar
4647 // - make a vector out the scalar results
4648
4649 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004650 int numComponents = builder.getNumComponents(operands[0]);
4651 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004652 std::vector<spv::Id> results;
4653
4654 // do each scalar op
4655 for (int comp = 0; comp < numComponents; ++comp) {
4656 std::vector<unsigned int> indexes;
4657 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004658 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004659 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004660 if (op == spv::OpSubgroupReadInvocationKHR) {
4661 spvGroupOperands.push_back(scalar);
4662 spvGroupOperands.push_back(operands[1]);
4663 } else if (op == spv::OpGroupBroadcast) {
4664 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004665 spvGroupOperands.push_back(scalar);
4666 spvGroupOperands.push_back(operands[1]);
4667 } else {
chaocf200da82016-12-20 12:44:35 -08004668 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004669 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004670 spvGroupOperands.push_back(scalar);
4671 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004672
Rex Xub7072052016-09-26 15:53:40 +08004673 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004674 }
4675
4676 // put the pieces together
4677 return builder.createCompositeConstruct(typeId, results);
4678}
Rex Xu2bbbe062016-08-23 15:41:05 +08004679
John Kessenich5e4b1242015-08-06 22:53:06 -06004680spv::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 -06004681{
Rex Xu8ff43de2016-04-22 16:51:45 +08004682 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004683#ifdef AMD_EXTENSIONS
4684 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4685#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004686 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004687#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004688
John Kessenich140f3df2015-06-26 16:58:36 -06004689 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004690 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004691 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004692 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004693 spv::Id typeId0 = 0;
4694 if (consumedOperands > 0)
4695 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004696 spv::Id typeId1 = 0;
4697 if (consumedOperands > 1)
4698 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004699 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004700
4701 switch (op) {
4702 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004703 if (isFloat)
4704 libCall = spv::GLSLstd450FMin;
4705 else if (isUnsigned)
4706 libCall = spv::GLSLstd450UMin;
4707 else
4708 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004709 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004710 break;
4711 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004712 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004713 break;
4714 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004715 if (isFloat)
4716 libCall = spv::GLSLstd450FMax;
4717 else if (isUnsigned)
4718 libCall = spv::GLSLstd450UMax;
4719 else
4720 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004721 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004722 break;
4723 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004724 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004725 break;
4726 case glslang::EOpDot:
4727 opCode = spv::OpDot;
4728 break;
4729 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004730 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004731 break;
4732
4733 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004734 if (isFloat)
4735 libCall = spv::GLSLstd450FClamp;
4736 else if (isUnsigned)
4737 libCall = spv::GLSLstd450UClamp;
4738 else
4739 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004740 builder.promoteScalar(precision, operands.front(), operands[1]);
4741 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004742 break;
4743 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004744 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4745 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004746 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004747 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004748 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004749 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004750 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004751 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004752 break;
4753 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004754 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004755 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004756 break;
4757 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004758 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004759 builder.promoteScalar(precision, operands[0], operands[2]);
4760 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004761 break;
4762
4763 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004764 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004765 break;
4766 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004767 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004768 break;
4769 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004770 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004771 break;
4772 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004773 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004774 break;
4775 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004776 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004777 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004778 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004779 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004780 libCall = spv::GLSLstd450InterpolateAtSample;
4781 break;
4782 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004783 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004784 libCall = spv::GLSLstd450InterpolateAtOffset;
4785 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004786 case glslang::EOpAddCarry:
4787 opCode = spv::OpIAddCarry;
4788 typeId = builder.makeStructResultType(typeId0, typeId0);
4789 consumedOperands = 2;
4790 break;
4791 case glslang::EOpSubBorrow:
4792 opCode = spv::OpISubBorrow;
4793 typeId = builder.makeStructResultType(typeId0, typeId0);
4794 consumedOperands = 2;
4795 break;
4796 case glslang::EOpUMulExtended:
4797 opCode = spv::OpUMulExtended;
4798 typeId = builder.makeStructResultType(typeId0, typeId0);
4799 consumedOperands = 2;
4800 break;
4801 case glslang::EOpIMulExtended:
4802 opCode = spv::OpSMulExtended;
4803 typeId = builder.makeStructResultType(typeId0, typeId0);
4804 consumedOperands = 2;
4805 break;
4806 case glslang::EOpBitfieldExtract:
4807 if (isUnsigned)
4808 opCode = spv::OpBitFieldUExtract;
4809 else
4810 opCode = spv::OpBitFieldSExtract;
4811 break;
4812 case glslang::EOpBitfieldInsert:
4813 opCode = spv::OpBitFieldInsert;
4814 break;
4815
4816 case glslang::EOpFma:
4817 libCall = spv::GLSLstd450Fma;
4818 break;
4819 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004820 {
4821 libCall = spv::GLSLstd450FrexpStruct;
4822 assert(builder.isPointerType(typeId1));
4823 typeId1 = builder.getContainedTypeId(typeId1);
4824#ifdef AMD_EXTENSIONS
4825 int width = builder.getScalarTypeWidth(typeId1);
4826#else
4827 int width = 32;
4828#endif
4829 if (builder.getNumComponents(operands[0]) == 1)
4830 frexpIntType = builder.makeIntegerType(width, true);
4831 else
4832 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4833 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4834 consumedOperands = 1;
4835 }
John Kessenich55e7d112015-11-15 21:33:39 -07004836 break;
4837 case glslang::EOpLdexp:
4838 libCall = spv::GLSLstd450Ldexp;
4839 break;
4840
Rex Xu574ab042016-04-14 16:53:07 +08004841 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004842 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004843
Rex Xu9d93a232016-05-05 12:30:44 +08004844#ifdef AMD_EXTENSIONS
4845 case glslang::EOpSwizzleInvocations:
4846 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4847 libCall = spv::SwizzleInvocationsAMD;
4848 break;
4849 case glslang::EOpSwizzleInvocationsMasked:
4850 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4851 libCall = spv::SwizzleInvocationsMaskedAMD;
4852 break;
4853 case glslang::EOpWriteInvocation:
4854 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4855 libCall = spv::WriteInvocationAMD;
4856 break;
4857
4858 case glslang::EOpMin3:
4859 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4860 if (isFloat)
4861 libCall = spv::FMin3AMD;
4862 else {
4863 if (isUnsigned)
4864 libCall = spv::UMin3AMD;
4865 else
4866 libCall = spv::SMin3AMD;
4867 }
4868 break;
4869 case glslang::EOpMax3:
4870 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4871 if (isFloat)
4872 libCall = spv::FMax3AMD;
4873 else {
4874 if (isUnsigned)
4875 libCall = spv::UMax3AMD;
4876 else
4877 libCall = spv::SMax3AMD;
4878 }
4879 break;
4880 case glslang::EOpMid3:
4881 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4882 if (isFloat)
4883 libCall = spv::FMid3AMD;
4884 else {
4885 if (isUnsigned)
4886 libCall = spv::UMid3AMD;
4887 else
4888 libCall = spv::SMid3AMD;
4889 }
4890 break;
4891
4892 case glslang::EOpInterpolateAtVertex:
4893 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4894 libCall = spv::InterpolateAtVertexAMD;
4895 break;
4896#endif
4897
John Kessenich140f3df2015-06-26 16:58:36 -06004898 default:
4899 return 0;
4900 }
4901
4902 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004903 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004904 // Use an extended instruction from the standard library.
4905 // Construct the call arguments, without modifying the original operands vector.
4906 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4907 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004908 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004909 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004910 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004911 case 0:
4912 // should all be handled by visitAggregate and createNoArgOperation
4913 assert(0);
4914 return 0;
4915 case 1:
4916 // should all be handled by createUnaryOperation
4917 assert(0);
4918 return 0;
4919 case 2:
4920 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4921 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004922 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004923 // anything 3 or over doesn't have l-value operands, so all should be consumed
4924 assert(consumedOperands == operands.size());
4925 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004926 break;
4927 }
4928 }
4929
John Kessenich55e7d112015-11-15 21:33:39 -07004930 // Decode the return types that were structures
4931 switch (op) {
4932 case glslang::EOpAddCarry:
4933 case glslang::EOpSubBorrow:
4934 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4935 id = builder.createCompositeExtract(id, typeId0, 0);
4936 break;
4937 case glslang::EOpUMulExtended:
4938 case glslang::EOpIMulExtended:
4939 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4940 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4941 break;
4942 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004943 {
4944 assert(operands.size() == 2);
4945 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4946 // "exp" is floating-point type (from HLSL intrinsic)
4947 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4948 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4949 builder.createStore(member1, operands[1]);
4950 } else
4951 // "exp" is integer type (from GLSL built-in function)
4952 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4953 id = builder.createCompositeExtract(id, typeId0, 0);
4954 }
John Kessenich55e7d112015-11-15 21:33:39 -07004955 break;
4956 default:
4957 break;
4958 }
4959
John Kessenich32cfd492016-02-02 12:37:46 -07004960 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004961}
4962
Rex Xu9d93a232016-05-05 12:30:44 +08004963// Intrinsics with no arguments (or no return value, and no precision).
4964spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06004965{
4966 // TODO: get the barrier operands correct
4967
4968 switch (op) {
4969 case glslang::EOpEmitVertex:
4970 builder.createNoResultOp(spv::OpEmitVertex);
4971 return 0;
4972 case glslang::EOpEndPrimitive:
4973 builder.createNoResultOp(spv::OpEndPrimitive);
4974 return 0;
4975 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01004976 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06004977 return 0;
4978 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06004979 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06004980 return 0;
4981 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06004982 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004983 return 0;
4984 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06004985 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004986 return 0;
4987 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06004988 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004989 return 0;
4990 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07004991 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004992 return 0;
4993 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07004994 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06004995 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06004996 case glslang::EOpAllMemoryBarrierWithGroupSync:
4997 // Control barrier with non-"None" semantic is also a memory barrier.
4998 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
4999 return 0;
5000 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5001 // Control barrier with non-"None" semantic is also a memory barrier.
5002 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5003 return 0;
5004 case glslang::EOpWorkgroupMemoryBarrier:
5005 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5006 return 0;
5007 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5008 // Control barrier with non-"None" semantic is also a memory barrier.
5009 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5010 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005011#ifdef AMD_EXTENSIONS
5012 case glslang::EOpTime:
5013 {
5014 std::vector<spv::Id> args; // Dummy arguments
5015 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5016 return builder.setPrecision(id, precision);
5017 }
5018#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005019 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005020 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005021 return 0;
5022 }
5023}
5024
5025spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5026{
John Kessenich2f273362015-07-18 22:34:27 -06005027 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005028 spv::Id id;
5029 if (symbolValues.end() != iter) {
5030 id = iter->second;
5031 return id;
5032 }
5033
5034 // it was not found, create it
5035 id = createSpvVariable(symbol);
5036 symbolValues[symbol->getId()] = id;
5037
Rex Xuc884b4a2016-06-29 15:03:44 +08005038 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005039 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005040 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005041 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005042 if (symbol->getType().getQualifier().hasSpecConstantId())
5043 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005044 if (symbol->getQualifier().hasIndex())
5045 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5046 if (symbol->getQualifier().hasComponent())
5047 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5048 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005049 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005050 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005051 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005052 if (symbol->getQualifier().hasXfbBuffer())
5053 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5054 if (symbol->getQualifier().hasXfbOffset())
5055 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5056 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005057 // atomic counters use this:
5058 if (symbol->getQualifier().hasOffset())
5059 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005060 }
5061
scygan2c864272016-05-18 18:09:17 +02005062 if (symbol->getQualifier().hasLocation())
5063 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005064 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005065 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005066 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005067 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005068 }
John Kessenich140f3df2015-06-26 16:58:36 -06005069 if (symbol->getQualifier().hasSet())
5070 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005071 else if (IsDescriptorResource(symbol->getType())) {
5072 // default to 0
5073 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5074 }
John Kessenich140f3df2015-06-26 16:58:36 -06005075 if (symbol->getQualifier().hasBinding())
5076 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005077 if (symbol->getQualifier().hasAttachment())
5078 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005079 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005080 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005081 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005082 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005083 if (symbol->getQualifier().hasXfbBuffer())
5084 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5085 }
5086
Rex Xu1da878f2016-02-21 20:59:01 +08005087 if (symbol->getType().isImage()) {
5088 std::vector<spv::Decoration> memory;
5089 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5090 for (unsigned int i = 0; i < memory.size(); ++i)
5091 addDecoration(id, memory[i]);
5092 }
5093
John Kessenich140f3df2015-06-26 16:58:36 -06005094 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005095 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005096 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005097 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005098
John Kessenichecba76f2017-01-06 00:34:48 -07005099#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005100 if (builtIn == spv::BuiltInSampleMask) {
5101 spv::Decoration decoration;
5102 // GL_NV_sample_mask_override_coverage extension
5103 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005104 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005105 else
5106 decoration = (spv::Decoration)spv::DecorationMax;
5107 addDecoration(id, decoration);
5108 if (decoration != spv::DecorationMax) {
5109 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5110 }
5111 }
chaoc771d89f2017-01-13 01:10:53 -08005112 else if (builtIn == spv::BuiltInLayer) {
5113 // SPV_NV_viewport_array2 extension
5114 if (symbol->getQualifier().layoutViewportRelative)
5115 {
5116 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5117 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5118 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5119 }
5120 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5121 {
5122 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5123 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5124 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5125 }
5126 }
5127
chaoc6e5acae2016-12-20 13:28:52 -08005128 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005129 addDecoration(id, spv::DecorationPassthroughNV);
5130 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005131 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5132 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005133#endif
5134
John Kessenich140f3df2015-06-26 16:58:36 -06005135 return id;
5136}
5137
John Kessenich55e7d112015-11-15 21:33:39 -07005138// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005139void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5140{
John Kessenich4016e382016-07-15 11:53:56 -06005141 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005142 builder.addDecoration(id, dec);
5143}
5144
John Kessenich55e7d112015-11-15 21:33:39 -07005145// If 'dec' is valid, add a one-operand decoration to an object
5146void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5147{
John Kessenich4016e382016-07-15 11:53:56 -06005148 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005149 builder.addDecoration(id, dec, value);
5150}
5151
5152// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005153void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5154{
John Kessenich4016e382016-07-15 11:53:56 -06005155 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005156 builder.addMemberDecoration(id, (unsigned)member, dec);
5157}
5158
John Kessenich92187592016-02-01 13:45:25 -07005159// If 'dec' is valid, add a one-operand decoration to a struct member
5160void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5161{
John Kessenich4016e382016-07-15 11:53:56 -06005162 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005163 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5164}
5165
John Kessenich55e7d112015-11-15 21:33:39 -07005166// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005167// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005168//
5169// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5170//
5171// Recursively walk the nodes. The nodes form a tree whose leaves are
5172// regular constants, which themselves are trees that createSpvConstant()
5173// recursively walks. So, this function walks the "top" of the tree:
5174// - emit specialization constant-building instructions for specConstant
5175// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005176spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005177{
John Kessenich7cc0e282016-03-20 00:46:02 -06005178 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005179
qining4f4bb812016-04-03 23:55:17 -04005180 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005181 if (! node.getQualifier().specConstant) {
5182 // hand off to the non-spec-constant path
5183 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5184 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005185 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005186 nextConst, false);
5187 }
5188
5189 // We now know we have a specialization constant to build
5190
John Kessenichd94c0032016-05-30 19:29:40 -06005191 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005192 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5193 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5194 std::vector<spv::Id> dimConstId;
5195 for (int dim = 0; dim < 3; ++dim) {
5196 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5197 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5198 if (specConst)
5199 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5200 }
5201 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5202 }
5203
5204 // An AST node labelled as specialization constant should be a symbol node.
5205 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5206 if (auto* sn = node.getAsSymbolNode()) {
5207 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005208 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5209 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5210 // will set the builder into spec constant op instruction generating mode.
5211 sub_tree->traverse(this);
5212 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005213 } else if (auto* const_union_array = &sn->getConstArray()){
5214 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005215 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5216 builder.addName(id, sn->getName().c_str());
5217 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005218 }
5219 }
qining4f4bb812016-04-03 23:55:17 -04005220
5221 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5222 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005223 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005224 exit(1);
5225 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005226}
5227
John Kessenich140f3df2015-06-26 16:58:36 -06005228// Use 'consts' as the flattened glslang source of scalar constants to recursively
5229// build the aggregate SPIR-V constant.
5230//
5231// If there are not enough elements present in 'consts', 0 will be substituted;
5232// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5233//
qining08408382016-03-21 09:51:37 -04005234spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005235{
5236 // vector of constants for SPIR-V
5237 std::vector<spv::Id> spvConsts;
5238
5239 // Type is used for struct and array constants
5240 spv::Id typeId = convertGlslangToSpvType(glslangType);
5241
5242 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005243 glslang::TType elementType(glslangType, 0);
5244 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005245 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005246 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005247 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005248 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005249 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005250 } else if (glslangType.getStruct()) {
5251 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5252 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005253 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005254 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005255 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5256 bool zero = nextConst >= consts.size();
5257 switch (glslangType.getBasicType()) {
5258 case glslang::EbtInt:
5259 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5260 break;
5261 case glslang::EbtUint:
5262 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5263 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005264 case glslang::EbtInt64:
5265 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5266 break;
5267 case glslang::EbtUint64:
5268 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5269 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005270 case glslang::EbtFloat:
5271 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5272 break;
5273 case glslang::EbtDouble:
5274 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5275 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005276#ifdef AMD_EXTENSIONS
5277 case glslang::EbtFloat16:
5278 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5279 break;
5280#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005281 case glslang::EbtBool:
5282 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5283 break;
5284 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005285 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005286 break;
5287 }
5288 ++nextConst;
5289 }
5290 } else {
5291 // we have a non-aggregate (scalar) constant
5292 bool zero = nextConst >= consts.size();
5293 spv::Id scalar = 0;
5294 switch (glslangType.getBasicType()) {
5295 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005296 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005297 break;
5298 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005299 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005300 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005301 case glslang::EbtInt64:
5302 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5303 break;
5304 case glslang::EbtUint64:
5305 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5306 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005307 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005308 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005309 break;
5310 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005311 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005312 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005313#ifdef AMD_EXTENSIONS
5314 case glslang::EbtFloat16:
5315 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5316 break;
5317#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005318 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005319 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005320 break;
5321 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005322 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005323 break;
5324 }
5325 ++nextConst;
5326 return scalar;
5327 }
5328
5329 return builder.makeCompositeConstant(typeId, spvConsts);
5330}
5331
John Kessenich7c1aa102015-10-15 13:29:11 -06005332// Return true if the node is a constant or symbol whose reading has no
5333// non-trivial observable cost or effect.
5334bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5335{
5336 // don't know what this is
5337 if (node == nullptr)
5338 return false;
5339
5340 // a constant is safe
5341 if (node->getAsConstantUnion() != nullptr)
5342 return true;
5343
5344 // not a symbol means non-trivial
5345 if (node->getAsSymbolNode() == nullptr)
5346 return false;
5347
5348 // a symbol, depends on what's being read
5349 switch (node->getType().getQualifier().storage) {
5350 case glslang::EvqTemporary:
5351 case glslang::EvqGlobal:
5352 case glslang::EvqIn:
5353 case glslang::EvqInOut:
5354 case glslang::EvqConst:
5355 case glslang::EvqConstReadOnly:
5356 case glslang::EvqUniform:
5357 return true;
5358 default:
5359 return false;
5360 }
qining25262b32016-05-06 17:25:16 -04005361}
John Kessenich7c1aa102015-10-15 13:29:11 -06005362
5363// A node is trivial if it is a single operation with no side effects.
John Kessenich0d2b4712017-05-19 20:19:00 -06005364// Vector results seem ill-defined, currently classifying them as trivial too,
5365// to avoid scalar bool-based control-flow logic.
5366// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005367// Return true if trivial.
5368bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5369{
5370 if (node == nullptr)
5371 return false;
5372
John Kessenich0d2b4712017-05-19 20:19:00 -06005373 // count vectors as trivial
5374 if (node->getType().isVector())
5375 return true;
5376
John Kessenich7c1aa102015-10-15 13:29:11 -06005377 // symbols and constants are trivial
5378 if (isTrivialLeaf(node))
5379 return true;
5380
5381 // otherwise, it needs to be a simple operation or one or two leaf nodes
5382
5383 // not a simple operation
5384 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5385 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5386 if (binaryNode == nullptr && unaryNode == nullptr)
5387 return false;
5388
5389 // not on leaf nodes
5390 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5391 return false;
5392
5393 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5394 return false;
5395 }
5396
5397 switch (node->getAsOperator()->getOp()) {
5398 case glslang::EOpLogicalNot:
5399 case glslang::EOpConvIntToBool:
5400 case glslang::EOpConvUintToBool:
5401 case glslang::EOpConvFloatToBool:
5402 case glslang::EOpConvDoubleToBool:
5403 case glslang::EOpEqual:
5404 case glslang::EOpNotEqual:
5405 case glslang::EOpLessThan:
5406 case glslang::EOpGreaterThan:
5407 case glslang::EOpLessThanEqual:
5408 case glslang::EOpGreaterThanEqual:
5409 case glslang::EOpIndexDirect:
5410 case glslang::EOpIndexDirectStruct:
5411 case glslang::EOpLogicalXor:
5412 case glslang::EOpAny:
5413 case glslang::EOpAll:
5414 return true;
5415 default:
5416 return false;
5417 }
5418}
5419
5420// Emit short-circuiting code, where 'right' is never evaluated unless
5421// the left side is true (for &&) or false (for ||).
5422spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5423{
5424 spv::Id boolTypeId = builder.makeBoolType();
5425
5426 // emit left operand
5427 builder.clearAccessChain();
5428 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005429 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005430
5431 // Operands to accumulate OpPhi operands
5432 std::vector<spv::Id> phiOperands;
5433 // accumulate left operand's phi information
5434 phiOperands.push_back(leftId);
5435 phiOperands.push_back(builder.getBuildPoint()->getId());
5436
5437 // Make the two kinds of operation symmetric with a "!"
5438 // || => emit "if (! left) result = right"
5439 // && => emit "if ( left) result = right"
5440 //
5441 // TODO: this runtime "not" for || could be avoided by adding functionality
5442 // to 'builder' to have an "else" without an "then"
5443 if (op == glslang::EOpLogicalOr)
5444 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5445
5446 // make an "if" based on the left value
5447 spv::Builder::If ifBuilder(leftId, builder);
5448
5449 // emit right operand as the "then" part of the "if"
5450 builder.clearAccessChain();
5451 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005452 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005453
5454 // accumulate left operand's phi information
5455 phiOperands.push_back(rightId);
5456 phiOperands.push_back(builder.getBuildPoint()->getId());
5457
5458 // finish the "if"
5459 ifBuilder.makeEndIf();
5460
5461 // phi together the two results
5462 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5463}
5464
Rex Xu9d93a232016-05-05 12:30:44 +08005465// Return type Id of the imported set of extended instructions corresponds to the name.
5466// Import this set if it has not been imported yet.
5467spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5468{
5469 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5470 return extBuiltinMap[name];
5471 else {
Rex Xu51596642016-09-21 18:56:12 +08005472 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005473 spv::Id extBuiltins = builder.import(name);
5474 extBuiltinMap[name] = extBuiltins;
5475 return extBuiltins;
5476 }
5477}
5478
John Kessenich140f3df2015-06-26 16:58:36 -06005479}; // end anonymous namespace
5480
5481namespace glslang {
5482
John Kessenich68d78fd2015-07-12 19:28:10 -06005483void GetSpirvVersion(std::string& version)
5484{
John Kessenich9e55f632015-07-15 10:03:39 -06005485 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005486 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005487 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005488 version = buf;
5489}
5490
John Kessenich140f3df2015-06-26 16:58:36 -06005491// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005492void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005493{
5494 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005495 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005496 if (out.fail())
5497 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005498 for (int i = 0; i < (int)spirv.size(); ++i) {
5499 unsigned int word = spirv[i];
5500 out.write((const char*)&word, 4);
5501 }
5502 out.close();
5503}
5504
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005505// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005506void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005507{
5508 std::ofstream out;
5509 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005510 if (out.fail())
5511 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005512 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005513 if (varName != nullptr) {
5514 out << "\t #pragma once" << std::endl;
5515 out << "const uint32_t " << varName << "[] = {" << std::endl;
5516 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005517 const int WORDS_PER_LINE = 8;
5518 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5519 out << "\t";
5520 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5521 const unsigned int word = spirv[i + j];
5522 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5523 if (i + j + 1 < (int)spirv.size()) {
5524 out << ",";
5525 }
5526 }
5527 out << std::endl;
5528 }
Flavio15017db2017-02-15 14:29:33 -08005529 if (varName != nullptr) {
5530 out << "};";
5531 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005532 out.close();
5533}
5534
John Kessenich140f3df2015-06-26 16:58:36 -06005535//
5536// Set up the glslang traversal
5537//
5538void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv)
5539{
Lei Zhang17535f72016-05-04 15:55:59 -04005540 spv::SpvBuildLogger logger;
5541 GlslangToSpv(intermediate, spirv, &logger);
Lei Zhang09caf122016-05-02 18:11:54 -04005542}
5543
Lei Zhang17535f72016-05-04 15:55:59 -04005544void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, spv::SpvBuildLogger* logger)
Lei Zhang09caf122016-05-02 18:11:54 -04005545{
John Kessenich140f3df2015-06-26 16:58:36 -06005546 TIntermNode* root = intermediate.getTreeRoot();
5547
5548 if (root == 0)
5549 return;
5550
5551 glslang::GetThreadPoolAllocator().push();
5552
Lei Zhang17535f72016-05-04 15:55:59 -04005553 TGlslangToSpvTraverser it(&intermediate, logger);
John Kessenich140f3df2015-06-26 16:58:36 -06005554 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005555 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005556 it.dumpSpv(spirv);
5557
5558 glslang::GetThreadPoolAllocator().pop();
5559}
5560
5561}; // end namespace glslang