blob: a2bd8484f85458bdf293e1854951ba1e1f356105 [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:
John Kessenich121853f2017-05-31 17:11:16 -0600104 TGlslangToSpvTraverser(const glslang::TIntermediate*, spv::SpvBuildLogger* logger, glslang::SpvOptions& options);
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
John Kessenich121853f2017-05-31 17:11:16 -0600182 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600183 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600184 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700185 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600186 int sequenceDepth;
187
Lei Zhang17535f72016-05-04 15:55:59 -0400188 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400189
John Kessenich140f3df2015-06-26 16:58:36 -0600190 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
191 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700192 bool inEntryPoint;
193 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700194 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 -0700195 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600196 const glslang::TIntermediate* glslangIntermediate;
197 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800198 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600199
John Kessenich2f273362015-07-18 22:34:27 -0600200 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600201 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600202 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700203 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600204 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 -0600205 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600206};
207
208//
209// Helper functions for translating glslang representations to SPIR-V enumerants.
210//
211
212// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700213spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600214{
John Kessenich66e2faf2016-03-12 18:34:36 -0700215 switch (source) {
216 case glslang::EShSourceGlsl:
217 switch (profile) {
218 case ENoProfile:
219 case ECoreProfile:
220 case ECompatibilityProfile:
221 return spv::SourceLanguageGLSL;
222 case EEsProfile:
223 return spv::SourceLanguageESSL;
224 default:
225 return spv::SourceLanguageUnknown;
226 }
227 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600228 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600229 default:
230 return spv::SourceLanguageUnknown;
231 }
232}
233
234// Translate glslang language (stage) to SPIR-V execution model.
235spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
236{
237 switch (stage) {
238 case EShLangVertex: return spv::ExecutionModelVertex;
239 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
240 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
241 case EShLangGeometry: return spv::ExecutionModelGeometry;
242 case EShLangFragment: return spv::ExecutionModelFragment;
243 case EShLangCompute: return spv::ExecutionModelGLCompute;
244 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700245 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600246 return spv::ExecutionModelFragment;
247 }
248}
249
John Kessenich140f3df2015-06-26 16:58:36 -0600250// Translate glslang sampler type to SPIR-V dimensionality.
251spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
252{
253 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700254 case glslang::Esd1D: return spv::Dim1D;
255 case glslang::Esd2D: return spv::Dim2D;
256 case glslang::Esd3D: return spv::Dim3D;
257 case glslang::EsdCube: return spv::DimCube;
258 case glslang::EsdRect: return spv::DimRect;
259 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700260 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600261 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700262 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600263 return spv::Dim2D;
264 }
265}
266
John Kessenichf6640762016-08-01 19:44:00 -0600267// Translate glslang precision to SPIR-V precision decorations.
268spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600269{
John Kessenichf6640762016-08-01 19:44:00 -0600270 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700271 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600272 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600273 default:
274 return spv::NoPrecision;
275 }
276}
277
John Kessenichf6640762016-08-01 19:44:00 -0600278// Translate glslang type to SPIR-V precision decorations.
279spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
280{
281 return TranslatePrecisionDecoration(type.getQualifier().precision);
282}
283
John Kessenich140f3df2015-06-26 16:58:36 -0600284// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600285spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600286{
287 if (type.getBasicType() == glslang::EbtBlock) {
288 switch (type.getQualifier().storage) {
289 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600290 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600291 case glslang::EvqVaryingIn: return spv::DecorationBlock;
292 case glslang::EvqVaryingOut: return spv::DecorationBlock;
293 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700294 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600295 break;
296 }
297 }
298
John Kessenich4016e382016-07-15 11:53:56 -0600299 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600300}
301
Rex Xu1da878f2016-02-21 20:59:01 +0800302// Translate glslang type to SPIR-V memory decorations.
303void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
304{
305 if (qualifier.coherent)
306 memory.push_back(spv::DecorationCoherent);
307 if (qualifier.volatil)
308 memory.push_back(spv::DecorationVolatile);
309 if (qualifier.restrict)
310 memory.push_back(spv::DecorationRestrict);
311 if (qualifier.readonly)
312 memory.push_back(spv::DecorationNonWritable);
313 if (qualifier.writeonly)
314 memory.push_back(spv::DecorationNonReadable);
315}
316
John Kessenich140f3df2015-06-26 16:58:36 -0600317// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700318spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600319{
320 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700321 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600322 case glslang::ElmRowMajor:
323 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700324 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600325 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700326 default:
327 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600328 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600329 }
330 } else {
331 switch (type.getBasicType()) {
332 default:
John Kessenich4016e382016-07-15 11:53:56 -0600333 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600334 break;
335 case glslang::EbtBlock:
336 switch (type.getQualifier().storage) {
337 case glslang::EvqUniform:
338 case glslang::EvqBuffer:
339 switch (type.getQualifier().layoutPacking) {
340 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600341 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
342 default:
John Kessenich4016e382016-07-15 11:53:56 -0600343 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600344 }
345 case glslang::EvqVaryingIn:
346 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700347 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600348 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600349 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700350 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600351 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600352 }
353 }
354 }
355}
356
357// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600358// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700359// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800360spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600361{
Rex Xubbceed72016-05-21 09:40:44 +0800362 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700363 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600364 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800365 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700366 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700367 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600368 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800369#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800370 else if (qualifier.explicitInterp) {
371 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800372 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800373 }
Rex Xu9d93a232016-05-05 12:30:44 +0800374#endif
Rex Xubbceed72016-05-21 09:40:44 +0800375 else
John Kessenich4016e382016-07-15 11:53:56 -0600376 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800377}
378
379// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600380// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800381// should be applied.
382spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
383{
384 if (qualifier.patch)
385 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700386 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600387 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700388 else if (qualifier.sample) {
389 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600390 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700391 } else
John Kessenich4016e382016-07-15 11:53:56 -0600392 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600393}
394
John Kessenich92187592016-02-01 13:45:25 -0700395// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700396spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600397{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700398 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600399 return spv::DecorationInvariant;
400 else
John Kessenich4016e382016-07-15 11:53:56 -0600401 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600402}
403
qining9220dbb2016-05-04 17:34:38 -0400404// If glslang type is noContraction, return SPIR-V NoContraction decoration.
405spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
406{
407 if (qualifier.noContraction)
408 return spv::DecorationNoContraction;
409 else
John Kessenich4016e382016-07-15 11:53:56 -0600410 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400411}
412
David Netoa901ffe2016-06-08 14:11:40 +0100413// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
414// associated capabilities when required. For some built-in variables, a capability
415// is generated only when using the variable in an executable instruction, but not when
416// just declaring a struct member variable with it. This is true for PointSize,
417// ClipDistance, and CullDistance.
418spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600419{
420 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700421 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600422 // Defer adding the capability until the built-in is actually used.
423 if (! memberDeclaration) {
424 switch (glslangIntermediate->getStage()) {
425 case EShLangGeometry:
426 builder.addCapability(spv::CapabilityGeometryPointSize);
427 break;
428 case EShLangTessControl:
429 case EShLangTessEvaluation:
430 builder.addCapability(spv::CapabilityTessellationPointSize);
431 break;
432 default:
433 break;
434 }
John Kessenich92187592016-02-01 13:45:25 -0700435 }
436 return spv::BuiltInPointSize;
437
John Kessenichebb50532016-05-16 19:22:05 -0600438 // These *Distance capabilities logically belong here, but if the member is declared and
439 // then never used, consumers of SPIR-V prefer the capability not be declared.
440 // They are now generated when used, rather than here when declared.
441 // Potentially, the specification should be more clear what the minimum
442 // use needed is to trigger the capability.
443 //
John Kessenich92187592016-02-01 13:45:25 -0700444 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100445 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800446 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700447 return spv::BuiltInClipDistance;
448
449 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100450 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800451 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700452 return spv::BuiltInCullDistance;
453
454 case glslang::EbvViewportIndex:
Rex Xu5e317ff2017-03-16 23:02:39 +0800455 if (!memberDeclaration) {
456 builder.addCapability(spv::CapabilityMultiViewport);
chaoc771d89f2017-01-13 01:10:53 -0800457#ifdef NV_EXTENSIONS
Rex Xu5e317ff2017-03-16 23:02:39 +0800458 if (glslangIntermediate->getStage() == EShLangVertex ||
459 glslangIntermediate->getStage() == EShLangTessControl ||
460 glslangIntermediate->getStage() == EShLangTessEvaluation) {
461
462 builder.addExtension(spv::E_SPV_NV_viewport_array2);
463 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
464 }
chaoc771d89f2017-01-13 01:10:53 -0800465#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800466 }
John Kessenich92187592016-02-01 13:45:25 -0700467 return spv::BuiltInViewportIndex;
468
John Kessenich5e801132016-02-15 11:09:46 -0700469 case glslang::EbvSampleId:
470 builder.addCapability(spv::CapabilitySampleRateShading);
471 return spv::BuiltInSampleId;
472
473 case glslang::EbvSamplePosition:
474 builder.addCapability(spv::CapabilitySampleRateShading);
475 return spv::BuiltInSamplePosition;
476
477 case glslang::EbvSampleMask:
478 builder.addCapability(spv::CapabilitySampleRateShading);
479 return spv::BuiltInSampleMask;
480
John Kessenich78a45572016-07-08 14:05:15 -0600481 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +0800482 if (!memberDeclaration) {
483 builder.addCapability(spv::CapabilityGeometry);
chaoc771d89f2017-01-13 01:10:53 -0800484#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -0800485 if (glslangIntermediate->getStage() == EShLangVertex ||
486 glslangIntermediate->getStage() == EShLangTessControl ||
Rex Xu5e317ff2017-03-16 23:02:39 +0800487 glslangIntermediate->getStage() == EShLangTessEvaluation) {
488
chaoc771d89f2017-01-13 01:10:53 -0800489 builder.addExtension(spv::E_SPV_NV_viewport_array2);
490 builder.addCapability(spv::CapabilityShaderViewportIndexLayerNV);
491 }
chaoc771d89f2017-01-13 01:10:53 -0800492#endif
Rex Xu5e317ff2017-03-16 23:02:39 +0800493 }
494
John Kessenich78a45572016-07-08 14:05:15 -0600495 return spv::BuiltInLayer;
496
John Kessenich140f3df2015-06-26 16:58:36 -0600497 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600498 case glslang::EbvVertexId: return spv::BuiltInVertexId;
499 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700500 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
501 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800502
John Kessenichda581a22015-10-14 14:10:30 -0600503 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800504 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
505 builder.addCapability(spv::CapabilityDrawParameters);
506 return spv::BuiltInBaseVertex;
507
John Kessenichda581a22015-10-14 14:10:30 -0600508 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800509 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
510 builder.addCapability(spv::CapabilityDrawParameters);
511 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200512
John Kessenichda581a22015-10-14 14:10:30 -0600513 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800514 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
515 builder.addCapability(spv::CapabilityDrawParameters);
516 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200517
518 case glslang::EbvPrimitiveId:
519 if (glslangIntermediate->getStage() == EShLangFragment)
520 builder.addCapability(spv::CapabilityGeometry);
521 return spv::BuiltInPrimitiveId;
522
John Kessenich140f3df2015-06-26 16:58:36 -0600523 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600524 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
525 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
526 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
527 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
528 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
529 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
530 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600531 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
532 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
533 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
534 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
535 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
536 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
537 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
538 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800539
Rex Xu574ab042016-04-14 16:53:07 +0800540 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800541 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800542 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
543 return spv::BuiltInSubgroupSize;
544
Rex Xu574ab042016-04-14 16:53:07 +0800545 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800546 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800547 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
548 return spv::BuiltInSubgroupLocalInvocationId;
549
Rex Xu574ab042016-04-14 16:53:07 +0800550 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800551 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
552 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
553 return spv::BuiltInSubgroupEqMaskKHR;
554
Rex Xu574ab042016-04-14 16:53:07 +0800555 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800556 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
557 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
558 return spv::BuiltInSubgroupGeMaskKHR;
559
Rex Xu574ab042016-04-14 16:53:07 +0800560 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800561 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
562 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
563 return spv::BuiltInSubgroupGtMaskKHR;
564
Rex Xu574ab042016-04-14 16:53:07 +0800565 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800566 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
567 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
568 return spv::BuiltInSubgroupLeMaskKHR;
569
Rex Xu574ab042016-04-14 16:53:07 +0800570 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800571 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
572 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
573 return spv::BuiltInSubgroupLtMaskKHR;
574
Rex Xu9d93a232016-05-05 12:30:44 +0800575#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800576 case glslang::EbvBaryCoordNoPersp:
577 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
578 return spv::BuiltInBaryCoordNoPerspAMD;
579
580 case glslang::EbvBaryCoordNoPerspCentroid:
581 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
582 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
583
584 case glslang::EbvBaryCoordNoPerspSample:
585 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
586 return spv::BuiltInBaryCoordNoPerspSampleAMD;
587
588 case glslang::EbvBaryCoordSmooth:
589 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
590 return spv::BuiltInBaryCoordSmoothAMD;
591
592 case glslang::EbvBaryCoordSmoothCentroid:
593 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
594 return spv::BuiltInBaryCoordSmoothCentroidAMD;
595
596 case glslang::EbvBaryCoordSmoothSample:
597 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
598 return spv::BuiltInBaryCoordSmoothSampleAMD;
599
600 case glslang::EbvBaryCoordPullModel:
601 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
602 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800603#endif
chaoc771d89f2017-01-13 01:10:53 -0800604
John Kessenich6c8aaac2017-02-27 01:20:51 -0700605 case glslang::EbvDeviceIndex:
606 builder.addExtension(spv::E_SPV_KHR_device_group);
607 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700608 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700609
610 case glslang::EbvViewIndex:
611 builder.addExtension(spv::E_SPV_KHR_multiview);
612 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700613 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700614
chaoc771d89f2017-01-13 01:10:53 -0800615#ifdef NV_EXTENSIONS
616 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800617 if (!memberDeclaration) {
618 builder.addExtension(spv::E_SPV_NV_viewport_array2);
619 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
620 }
chaoc771d89f2017-01-13 01:10:53 -0800621 return spv::BuiltInViewportMaskNV;
622 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800623 if (!memberDeclaration) {
624 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
625 builder.addCapability(spv::CapabilityShaderStereoViewNV);
626 }
chaoc771d89f2017-01-13 01:10:53 -0800627 return spv::BuiltInSecondaryPositionNV;
628 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800629 if (!memberDeclaration) {
630 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
631 builder.addCapability(spv::CapabilityShaderStereoViewNV);
632 }
chaoc771d89f2017-01-13 01:10:53 -0800633 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800634 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800635 if (!memberDeclaration) {
636 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
637 builder.addCapability(spv::CapabilityPerViewAttributesNV);
638 }
chaocdf3956c2017-02-14 14:52:34 -0800639 return spv::BuiltInPositionPerViewNV;
640 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800641 if (!memberDeclaration) {
642 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
643 builder.addCapability(spv::CapabilityPerViewAttributesNV);
644 }
chaocdf3956c2017-02-14 14:52:34 -0800645 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800646#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800647 default:
648 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600649 }
650}
651
Rex Xufc618912015-09-09 16:42:49 +0800652// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700653spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800654{
655 assert(type.getBasicType() == glslang::EbtSampler);
656
John Kessenich5d0fa972016-02-15 11:57:00 -0700657 // Check for capabilities
658 switch (type.getQualifier().layoutFormat) {
659 case glslang::ElfRg32f:
660 case glslang::ElfRg16f:
661 case glslang::ElfR11fG11fB10f:
662 case glslang::ElfR16f:
663 case glslang::ElfRgba16:
664 case glslang::ElfRgb10A2:
665 case glslang::ElfRg16:
666 case glslang::ElfRg8:
667 case glslang::ElfR16:
668 case glslang::ElfR8:
669 case glslang::ElfRgba16Snorm:
670 case glslang::ElfRg16Snorm:
671 case glslang::ElfRg8Snorm:
672 case glslang::ElfR16Snorm:
673 case glslang::ElfR8Snorm:
674
675 case glslang::ElfRg32i:
676 case glslang::ElfRg16i:
677 case glslang::ElfRg8i:
678 case glslang::ElfR16i:
679 case glslang::ElfR8i:
680
681 case glslang::ElfRgb10a2ui:
682 case glslang::ElfRg32ui:
683 case glslang::ElfRg16ui:
684 case glslang::ElfRg8ui:
685 case glslang::ElfR16ui:
686 case glslang::ElfR8ui:
687 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
688 break;
689
690 default:
691 break;
692 }
693
694 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800695 switch (type.getQualifier().layoutFormat) {
696 case glslang::ElfNone: return spv::ImageFormatUnknown;
697 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
698 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
699 case glslang::ElfR32f: return spv::ImageFormatR32f;
700 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
701 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
702 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
703 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
704 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
705 case glslang::ElfR16f: return spv::ImageFormatR16f;
706 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
707 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
708 case glslang::ElfRg16: return spv::ImageFormatRg16;
709 case glslang::ElfRg8: return spv::ImageFormatRg8;
710 case glslang::ElfR16: return spv::ImageFormatR16;
711 case glslang::ElfR8: return spv::ImageFormatR8;
712 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
713 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
714 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
715 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
716 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
717 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
718 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
719 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
720 case glslang::ElfR32i: return spv::ImageFormatR32i;
721 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
722 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
723 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
724 case glslang::ElfR16i: return spv::ImageFormatR16i;
725 case glslang::ElfR8i: return spv::ImageFormatR8i;
726 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
727 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
728 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
729 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
730 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
731 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
732 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
733 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
734 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
735 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600736 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800737 }
738}
739
steve-lunargf1709e72017-05-02 20:14:50 -0600740spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
741{
742 switch (loopControl) {
743 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
744 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
745 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
746 // TODO: DependencyInfinite
747 // TODO: DependencyLength
748 default: return spv::LoopControlMaskNone;
749 }
750}
751
John Kessenicha5c5fb62017-05-05 05:09:58 -0600752// Translate glslang type to SPIR-V storage class.
753spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
754{
755 if (type.getQualifier().isPipeInput())
756 return spv::StorageClassInput;
757 else if (type.getQualifier().isPipeOutput())
758 return spv::StorageClassOutput;
759 else if (type.getBasicType() == glslang::EbtAtomicUint)
760 return spv::StorageClassAtomicCounter;
761 else if (type.containsOpaque())
762 return spv::StorageClassUniformConstant;
763 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
764 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
765 return spv::StorageClassStorageBuffer;
766 } else if (type.getQualifier().isUniformOrBuffer()) {
767 if (type.getQualifier().layoutPushConstant)
768 return spv::StorageClassPushConstant;
769 if (type.getBasicType() == glslang::EbtBlock)
770 return spv::StorageClassUniform;
771 else
772 return spv::StorageClassUniformConstant;
773 } else {
774 switch (type.getQualifier().storage) {
775 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
776 case glslang::EvqGlobal: return spv::StorageClassPrivate;
777 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
778 case glslang::EvqTemporary: return spv::StorageClassFunction;
779 default:
780 assert(0);
781 return spv::StorageClassFunction;
782 }
783 }
784}
785
qining25262b32016-05-06 17:25:16 -0400786// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700787// descriptor set.
788bool IsDescriptorResource(const glslang::TType& type)
789{
John Kessenichf7497e22016-03-08 21:36:22 -0700790 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700791 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700792 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700793
794 // non block...
795 // basically samplerXXX/subpass/sampler/texture are all included
796 // if they are the global-scope-class, not the function parameter
797 // (or local, if they ever exist) class.
798 if (type.getBasicType() == glslang::EbtSampler)
799 return type.getQualifier().isUniformOrBuffer();
800
801 // None of the above.
802 return false;
803}
804
John Kesseniche0b6cad2015-12-24 10:30:13 -0700805void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
806{
807 if (child.layoutMatrix == glslang::ElmNone)
808 child.layoutMatrix = parent.layoutMatrix;
809
810 if (parent.invariant)
811 child.invariant = true;
812 if (parent.nopersp)
813 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800814#ifdef AMD_EXTENSIONS
815 if (parent.explicitInterp)
816 child.explicitInterp = true;
817#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700818 if (parent.flat)
819 child.flat = true;
820 if (parent.centroid)
821 child.centroid = true;
822 if (parent.patch)
823 child.patch = true;
824 if (parent.sample)
825 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800826 if (parent.coherent)
827 child.coherent = true;
828 if (parent.volatil)
829 child.volatil = true;
830 if (parent.restrict)
831 child.restrict = true;
832 if (parent.readonly)
833 child.readonly = true;
834 if (parent.writeonly)
835 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700836}
837
John Kessenichf2b7f332016-09-01 17:05:23 -0600838bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700839{
John Kessenich7b9fa252016-01-21 18:56:57 -0700840 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600841 // - struct members might inherit from a struct declaration
842 // (note that non-block structs don't explicitly inherit,
843 // only implicitly, meaning no decoration involved)
844 // - affect decorations on the struct members
845 // (note smooth does not, and expecting something like volatile
846 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700847 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600848 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700849}
850
John Kessenich140f3df2015-06-26 16:58:36 -0600851//
852// Implement the TGlslangToSpvTraverser class.
853//
854
John Kessenich121853f2017-05-31 17:11:16 -0600855TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
856 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
857 : TIntermTraverser(true, false, true),
858 options(options),
859 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600860 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400861 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700862 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600863 glslangIntermediate(glslangIntermediate)
864{
865 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
866
867 builder.clearAccessChain();
John Kessenich66e2faf2016-03-12 18:34:36 -0700868 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()), glslangIntermediate->getVersion());
John Kessenich121853f2017-05-31 17:11:16 -0600869 if (options.generateDebugInfo) {
870 builder.setSourceFile(glslangIntermediate->getSourceFile());
871 builder.setSourceText(glslangIntermediate->getSourceText());
872 }
John Kessenich140f3df2015-06-26 16:58:36 -0600873 stdBuiltins = builder.import("GLSL.std.450");
874 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600875 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
876 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600877
878 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600879 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
880 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600881 builder.addSourceExtension(it->c_str());
882
883 // Add the top-level modes for this shader.
884
John Kessenich92187592016-02-01 13:45:25 -0700885 if (glslangIntermediate->getXfbMode()) {
886 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600887 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700888 }
John Kessenich140f3df2015-06-26 16:58:36 -0600889
890 unsigned int mode;
891 switch (glslangIntermediate->getStage()) {
892 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600893 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600894 break;
895
steve-lunarge7412492017-03-23 11:56:07 -0600896 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600897 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600898 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600899
steve-lunarge7412492017-03-23 11:56:07 -0600900 glslang::TLayoutGeometry primitive;
901
902 if (glslangIntermediate->getStage() == EShLangTessControl) {
903 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
904 primitive = glslangIntermediate->getOutputPrimitive();
905 } else {
906 primitive = glslangIntermediate->getInputPrimitive();
907 }
908
909 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700910 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
911 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
912 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600913 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600914 }
John Kessenich4016e382016-07-15 11:53:56 -0600915 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600916 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
917
John Kesseniche6903322015-10-13 16:29:02 -0600918 switch (glslangIntermediate->getVertexSpacing()) {
919 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
920 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
921 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; 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 switch (glslangIntermediate->getVertexOrder()) {
928 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
929 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600930 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600931 }
John Kessenich4016e382016-07-15 11:53:56 -0600932 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600933 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
934
935 if (glslangIntermediate->getPointMode())
936 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600937 break;
938
939 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600940 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600941 switch (glslangIntermediate->getInputPrimitive()) {
942 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
943 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
944 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700945 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600946 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600947 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600948 }
John Kessenich4016e382016-07-15 11:53:56 -0600949 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600950 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600951
John Kessenich140f3df2015-06-26 16:58:36 -0600952 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
953
954 switch (glslangIntermediate->getOutputPrimitive()) {
955 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
956 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
957 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600958 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600959 }
John Kessenich4016e382016-07-15 11:53:56 -0600960 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600961 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
962 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
963 break;
964
965 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600966 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600967 if (glslangIntermediate->getPixelCenterInteger())
968 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600969
John Kessenich140f3df2015-06-26 16:58:36 -0600970 if (glslangIntermediate->getOriginUpperLeft())
971 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600972 else
973 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -0600974
975 if (glslangIntermediate->getEarlyFragmentTests())
976 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
977
978 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -0600979 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
980 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -0600981 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600982 }
John Kessenich4016e382016-07-15 11:53:56 -0600983 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600984 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
985
986 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
987 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -0600988 break;
989
990 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -0600991 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -0600992 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
993 glslangIntermediate->getLocalSize(1),
994 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -0600995 break;
996
997 default:
998 break;
999 }
John Kessenich140f3df2015-06-26 16:58:36 -06001000}
1001
John Kessenichfca82622016-11-26 13:23:20 -07001002// Finish creating SPV, after the traversal is complete.
1003void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001004{
John Kessenich517fe7a2016-11-26 13:31:47 -07001005 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001006 builder.setBuildPoint(shaderEntry->getLastBlock());
1007 builder.leaveFunction();
1008 }
1009
John Kessenich7ba63412015-12-20 17:37:07 -07001010 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001011 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1012 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001013
qiningda397332016-03-09 19:54:03 -05001014 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001015}
1016
John Kessenichfca82622016-11-26 13:23:20 -07001017// Write the SPV into 'out'.
1018void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001019{
John Kessenichfca82622016-11-26 13:23:20 -07001020 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001021}
1022
1023//
1024// Implement the traversal functions.
1025//
1026// Return true from interior nodes to have the external traversal
1027// continue on to children. Return false if children were
1028// already processed.
1029//
1030
1031//
qining25262b32016-05-06 17:25:16 -04001032// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001033// - uniform/input reads
1034// - output writes
1035// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1036// - something simple that degenerates into the last bullet
1037//
1038void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1039{
qining75d1d802016-04-06 14:42:01 -04001040 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1041 if (symbol->getType().getQualifier().isSpecConstant())
1042 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1043
John Kessenich140f3df2015-06-26 16:58:36 -06001044 // getSymbolId() will set up all the IO decorations on the first call.
1045 // Formal function parameters were mapped during makeFunctions().
1046 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001047
1048 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1049 if (builder.isPointer(id)) {
1050 spv::StorageClass sc = builder.getStorageClass(id);
1051 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput)
1052 iOSet.insert(id);
1053 }
1054
1055 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001056 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001057 // Prepare to generate code for the access
1058
1059 // L-value chains will be computed left to right. We're on the symbol now,
1060 // which is the left-most part of the access chain, so now is "clear" time,
1061 // followed by setting the base.
1062 builder.clearAccessChain();
1063
1064 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001065 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001066 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001067 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001068 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001069 // These are also pure R-values.
1070 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001071 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001072 builder.setAccessChainRValue(id);
1073 else
1074 builder.setAccessChainLValue(id);
1075 }
1076}
1077
1078bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1079{
qining40887662016-04-03 22:20:42 -04001080 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1081 if (node->getType().getQualifier().isSpecConstant())
1082 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1083
John Kessenich140f3df2015-06-26 16:58:36 -06001084 // First, handle special cases
1085 switch (node->getOp()) {
1086 case glslang::EOpAssign:
1087 case glslang::EOpAddAssign:
1088 case glslang::EOpSubAssign:
1089 case glslang::EOpMulAssign:
1090 case glslang::EOpVectorTimesMatrixAssign:
1091 case glslang::EOpVectorTimesScalarAssign:
1092 case glslang::EOpMatrixTimesScalarAssign:
1093 case glslang::EOpMatrixTimesMatrixAssign:
1094 case glslang::EOpDivAssign:
1095 case glslang::EOpModAssign:
1096 case glslang::EOpAndAssign:
1097 case glslang::EOpInclusiveOrAssign:
1098 case glslang::EOpExclusiveOrAssign:
1099 case glslang::EOpLeftShiftAssign:
1100 case glslang::EOpRightShiftAssign:
1101 // A bin-op assign "a += b" means the same thing as "a = a + b"
1102 // where a is evaluated before b. For a simple assignment, GLSL
1103 // says to evaluate the left before the right. So, always, left
1104 // node then right node.
1105 {
1106 // get the left l-value, save it away
1107 builder.clearAccessChain();
1108 node->getLeft()->traverse(this);
1109 spv::Builder::AccessChain lValue = builder.getAccessChain();
1110
1111 // evaluate the right
1112 builder.clearAccessChain();
1113 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001114 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001115
1116 if (node->getOp() != glslang::EOpAssign) {
1117 // the left is also an r-value
1118 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001119 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001120
1121 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001122 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001123 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001124 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1125 node->getType().getBasicType());
1126
1127 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001128 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001129 }
1130
1131 // store the result
1132 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001133 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001134
1135 // assignments are expressions having an rValue after they are evaluated...
1136 builder.clearAccessChain();
1137 builder.setAccessChainRValue(rValue);
1138 }
1139 return false;
1140 case glslang::EOpIndexDirect:
1141 case glslang::EOpIndexDirectStruct:
1142 {
1143 // Get the left part of the access chain.
1144 node->getLeft()->traverse(this);
1145
1146 // Add the next element in the chain
1147
David Netoa901ffe2016-06-08 14:11:40 +01001148 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001149 if (! node->getLeft()->getType().isArray() &&
1150 node->getLeft()->getType().isVector() &&
1151 node->getOp() == glslang::EOpIndexDirect) {
1152 // This is essentially a hard-coded vector swizzle of size 1,
1153 // so short circuit the access-chain stuff with a swizzle.
1154 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001155 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001156 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001157 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001158 int spvIndex = glslangIndex;
1159 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1160 node->getOp() == glslang::EOpIndexDirectStruct)
1161 {
1162 // This may be, e.g., an anonymous block-member selection, which generally need
1163 // index remapping due to hidden members in anonymous blocks.
1164 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1165 assert(remapper.size() > 0);
1166 spvIndex = remapper[glslangIndex];
1167 }
John Kessenichebb50532016-05-16 19:22:05 -06001168
David Netoa901ffe2016-06-08 14:11:40 +01001169 // normal case for indexing array or structure or block
1170 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1171
1172 // Add capabilities here for accessing PointSize and clip/cull distance.
1173 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001174 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001175 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001176 }
1177 }
1178 return false;
1179 case glslang::EOpIndexIndirect:
1180 {
1181 // Structure or array or vector indirection.
1182 // Will use native SPIR-V access-chain for struct and array indirection;
1183 // matrices are arrays of vectors, so will also work for a matrix.
1184 // Will use the access chain's 'component' for variable index into a vector.
1185
1186 // This adapter is building access chains left to right.
1187 // Set up the access chain to the left.
1188 node->getLeft()->traverse(this);
1189
1190 // save it so that computing the right side doesn't trash it
1191 spv::Builder::AccessChain partial = builder.getAccessChain();
1192
1193 // compute the next index in the chain
1194 builder.clearAccessChain();
1195 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001196 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001197
1198 // restore the saved access chain
1199 builder.setAccessChain(partial);
1200
1201 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001202 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001203 else
John Kessenichfa668da2015-09-13 14:46:30 -06001204 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001205 }
1206 return false;
1207 case glslang::EOpVectorSwizzle:
1208 {
1209 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001210 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001211 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001212 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001213 }
1214 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001215 case glslang::EOpMatrixSwizzle:
1216 logger->missingFunctionality("matrix swizzle");
1217 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001218 case glslang::EOpLogicalOr:
1219 case glslang::EOpLogicalAnd:
1220 {
1221
1222 // These may require short circuiting, but can sometimes be done as straight
1223 // binary operations. The right operand must be short circuited if it has
1224 // side effects, and should probably be if it is complex.
1225 if (isTrivial(node->getRight()->getAsTyped()))
1226 break; // handle below as a normal binary operation
1227 // otherwise, we need to do dynamic short circuiting on the right operand
1228 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1229 builder.clearAccessChain();
1230 builder.setAccessChainRValue(result);
1231 }
1232 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001233 default:
1234 break;
1235 }
1236
1237 // Assume generic binary op...
1238
John Kessenich32cfd492016-02-02 12:37:46 -07001239 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001240 builder.clearAccessChain();
1241 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001242 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001243
John Kessenich32cfd492016-02-02 12:37:46 -07001244 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001245 builder.clearAccessChain();
1246 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001247 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001248
John Kessenich32cfd492016-02-02 12:37:46 -07001249 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001250 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001251 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001252 convertGlslangToSpvType(node->getType()), left, right,
1253 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001254
John Kessenich50e57562015-12-21 21:21:11 -07001255 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001256 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001257 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001258 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001259 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001260 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001261 return false;
1262 }
John Kessenich140f3df2015-06-26 16:58:36 -06001263}
1264
1265bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1266{
qining40887662016-04-03 22:20:42 -04001267 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1268 if (node->getType().getQualifier().isSpecConstant())
1269 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1270
John Kessenichfc51d282015-08-19 13:34:18 -06001271 spv::Id result = spv::NoResult;
1272
1273 // try texturing first
1274 result = createImageTextureFunctionCall(node);
1275 if (result != spv::NoResult) {
1276 builder.clearAccessChain();
1277 builder.setAccessChainRValue(result);
1278
1279 return false; // done with this node
1280 }
1281
1282 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001283
1284 if (node->getOp() == glslang::EOpArrayLength) {
1285 // Quite special; won't want to evaluate the operand.
1286
1287 // Normal .length() would have been constant folded by the front-end.
1288 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001289 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001290 assert(node->getOperand()->getType().isRuntimeSizedArray());
1291 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1292 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001293 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1294 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001295
1296 builder.clearAccessChain();
1297 builder.setAccessChainRValue(length);
1298
1299 return false;
1300 }
1301
John Kessenichfc51d282015-08-19 13:34:18 -06001302 // Start by evaluating the operand
1303
John Kessenich8c8505c2016-07-26 12:50:38 -06001304 // Does it need a swizzle inversion? If so, evaluation is inverted;
1305 // operate first on the swizzle base, then apply the swizzle.
1306 spv::Id invertedType = spv::NoType;
1307 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1308 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1309 invertedType = getInvertedSwizzleType(*node->getOperand());
1310
John Kessenich140f3df2015-06-26 16:58:36 -06001311 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001312 if (invertedType != spv::NoType)
1313 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1314 else
1315 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001316
Rex Xufc618912015-09-09 16:42:49 +08001317 spv::Id operand = spv::NoResult;
1318
1319 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1320 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001321 node->getOp() == glslang::EOpAtomicCounter ||
1322 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001323 operand = builder.accessChainGetLValue(); // Special case l-value operands
1324 else
John Kessenich32cfd492016-02-02 12:37:46 -07001325 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001326
John Kessenichf6640762016-08-01 19:44:00 -06001327 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001328 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001329
1330 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001331 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001332 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001333
1334 // if not, then possibly an operation
1335 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001336 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001337
1338 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001339 if (invertedType)
1340 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1341
John Kessenich140f3df2015-06-26 16:58:36 -06001342 builder.clearAccessChain();
1343 builder.setAccessChainRValue(result);
1344
1345 return false; // done with this node
1346 }
1347
1348 // it must be a special case, check...
1349 switch (node->getOp()) {
1350 case glslang::EOpPostIncrement:
1351 case glslang::EOpPostDecrement:
1352 case glslang::EOpPreIncrement:
1353 case glslang::EOpPreDecrement:
1354 {
1355 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001356 spv::Id one = 0;
1357 if (node->getBasicType() == glslang::EbtFloat)
1358 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001359 else if (node->getBasicType() == glslang::EbtDouble)
1360 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001361#ifdef AMD_EXTENSIONS
1362 else if (node->getBasicType() == glslang::EbtFloat16)
1363 one = builder.makeFloat16Constant(1.0F);
1364#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001365 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1366 one = builder.makeInt64Constant(1);
1367 else
1368 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001369 glslang::TOperator op;
1370 if (node->getOp() == glslang::EOpPreIncrement ||
1371 node->getOp() == glslang::EOpPostIncrement)
1372 op = glslang::EOpAdd;
1373 else
1374 op = glslang::EOpSub;
1375
John Kessenichf6640762016-08-01 19:44:00 -06001376 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001377 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001378 convertGlslangToSpvType(node->getType()), operand, one,
1379 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001380 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001381
1382 // The result of operation is always stored, but conditionally the
1383 // consumed result. The consumed result is always an r-value.
1384 builder.accessChainStore(result);
1385 builder.clearAccessChain();
1386 if (node->getOp() == glslang::EOpPreIncrement ||
1387 node->getOp() == glslang::EOpPreDecrement)
1388 builder.setAccessChainRValue(result);
1389 else
1390 builder.setAccessChainRValue(operand);
1391 }
1392
1393 return false;
1394
1395 case glslang::EOpEmitStreamVertex:
1396 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1397 return false;
1398 case glslang::EOpEndStreamPrimitive:
1399 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1400 return false;
1401
1402 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001403 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001404 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001405 }
John Kessenich140f3df2015-06-26 16:58:36 -06001406}
1407
1408bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1409{
qining27e04a02016-04-14 16:40:20 -04001410 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1411 if (node->getType().getQualifier().isSpecConstant())
1412 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1413
John Kessenichfc51d282015-08-19 13:34:18 -06001414 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001415 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1416 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001417
1418 // try texturing
1419 result = createImageTextureFunctionCall(node);
1420 if (result != spv::NoResult) {
1421 builder.clearAccessChain();
1422 builder.setAccessChainRValue(result);
1423
1424 return false;
John Kessenich56bab042015-09-16 10:54:31 -06001425 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xufc618912015-09-09 16:42:49 +08001426 // "imageStore" is a special case, which has no result
1427 return false;
1428 }
John Kessenichfc51d282015-08-19 13:34:18 -06001429
John Kessenich140f3df2015-06-26 16:58:36 -06001430 glslang::TOperator binOp = glslang::EOpNull;
1431 bool reduceComparison = true;
1432 bool isMatrix = false;
1433 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001434 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001435
1436 assert(node->getOp());
1437
John Kessenichf6640762016-08-01 19:44:00 -06001438 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001439
1440 switch (node->getOp()) {
1441 case glslang::EOpSequence:
1442 {
1443 if (preVisit)
1444 ++sequenceDepth;
1445 else
1446 --sequenceDepth;
1447
1448 if (sequenceDepth == 1) {
1449 // If this is the parent node of all the functions, we want to see them
1450 // early, so all call points have actual SPIR-V functions to reference.
1451 // In all cases, still let the traverser visit the children for us.
1452 makeFunctions(node->getAsAggregate()->getSequence());
1453
John Kessenich6fccb3c2016-09-19 16:01:41 -06001454 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001455 // anything else gets there, so visit out of order, doing them all now.
1456 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1457
John Kessenich6a60c2f2016-12-08 21:01:59 -07001458 // 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 -06001459 // so do them manually.
1460 visitFunctions(node->getAsAggregate()->getSequence());
1461
1462 return false;
1463 }
1464
1465 return true;
1466 }
1467 case glslang::EOpLinkerObjects:
1468 {
1469 if (visit == glslang::EvPreVisit)
1470 linkageOnly = true;
1471 else
1472 linkageOnly = false;
1473
1474 return true;
1475 }
1476 case glslang::EOpComma:
1477 {
1478 // processing from left to right naturally leaves the right-most
1479 // lying around in the access chain
1480 glslang::TIntermSequence& glslangOperands = node->getSequence();
1481 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1482 glslangOperands[i]->traverse(this);
1483
1484 return false;
1485 }
1486 case glslang::EOpFunction:
1487 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001488 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001489 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001490 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001491 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001492 } else {
1493 handleFunctionEntry(node);
1494 }
1495 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001496 if (inEntryPoint)
1497 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001498 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001499 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001500 }
1501
1502 return true;
1503 case glslang::EOpParameters:
1504 // Parameters will have been consumed by EOpFunction processing, but not
1505 // the body, so we still visited the function node's children, making this
1506 // child redundant.
1507 return false;
1508 case glslang::EOpFunctionCall:
1509 {
1510 if (node->isUserDefined())
1511 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001512 // 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 -07001513 if (result) {
1514 builder.clearAccessChain();
1515 builder.setAccessChainRValue(result);
1516 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001517 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001518
1519 return false;
1520 }
1521 case glslang::EOpConstructMat2x2:
1522 case glslang::EOpConstructMat2x3:
1523 case glslang::EOpConstructMat2x4:
1524 case glslang::EOpConstructMat3x2:
1525 case glslang::EOpConstructMat3x3:
1526 case glslang::EOpConstructMat3x4:
1527 case glslang::EOpConstructMat4x2:
1528 case glslang::EOpConstructMat4x3:
1529 case glslang::EOpConstructMat4x4:
1530 case glslang::EOpConstructDMat2x2:
1531 case glslang::EOpConstructDMat2x3:
1532 case glslang::EOpConstructDMat2x4:
1533 case glslang::EOpConstructDMat3x2:
1534 case glslang::EOpConstructDMat3x3:
1535 case glslang::EOpConstructDMat3x4:
1536 case glslang::EOpConstructDMat4x2:
1537 case glslang::EOpConstructDMat4x3:
1538 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001539 case glslang::EOpConstructIMat2x2:
1540 case glslang::EOpConstructIMat2x3:
1541 case glslang::EOpConstructIMat2x4:
1542 case glslang::EOpConstructIMat3x2:
1543 case glslang::EOpConstructIMat3x3:
1544 case glslang::EOpConstructIMat3x4:
1545 case glslang::EOpConstructIMat4x2:
1546 case glslang::EOpConstructIMat4x3:
1547 case glslang::EOpConstructIMat4x4:
1548 case glslang::EOpConstructUMat2x2:
1549 case glslang::EOpConstructUMat2x3:
1550 case glslang::EOpConstructUMat2x4:
1551 case glslang::EOpConstructUMat3x2:
1552 case glslang::EOpConstructUMat3x3:
1553 case glslang::EOpConstructUMat3x4:
1554 case glslang::EOpConstructUMat4x2:
1555 case glslang::EOpConstructUMat4x3:
1556 case glslang::EOpConstructUMat4x4:
1557 case glslang::EOpConstructBMat2x2:
1558 case glslang::EOpConstructBMat2x3:
1559 case glslang::EOpConstructBMat2x4:
1560 case glslang::EOpConstructBMat3x2:
1561 case glslang::EOpConstructBMat3x3:
1562 case glslang::EOpConstructBMat3x4:
1563 case glslang::EOpConstructBMat4x2:
1564 case glslang::EOpConstructBMat4x3:
1565 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001566#ifdef AMD_EXTENSIONS
1567 case glslang::EOpConstructF16Mat2x2:
1568 case glslang::EOpConstructF16Mat2x3:
1569 case glslang::EOpConstructF16Mat2x4:
1570 case glslang::EOpConstructF16Mat3x2:
1571 case glslang::EOpConstructF16Mat3x3:
1572 case glslang::EOpConstructF16Mat3x4:
1573 case glslang::EOpConstructF16Mat4x2:
1574 case glslang::EOpConstructF16Mat4x3:
1575 case glslang::EOpConstructF16Mat4x4:
1576#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001577 isMatrix = true;
1578 // fall through
1579 case glslang::EOpConstructFloat:
1580 case glslang::EOpConstructVec2:
1581 case glslang::EOpConstructVec3:
1582 case glslang::EOpConstructVec4:
1583 case glslang::EOpConstructDouble:
1584 case glslang::EOpConstructDVec2:
1585 case glslang::EOpConstructDVec3:
1586 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001587#ifdef AMD_EXTENSIONS
1588 case glslang::EOpConstructFloat16:
1589 case glslang::EOpConstructF16Vec2:
1590 case glslang::EOpConstructF16Vec3:
1591 case glslang::EOpConstructF16Vec4:
1592#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001593 case glslang::EOpConstructBool:
1594 case glslang::EOpConstructBVec2:
1595 case glslang::EOpConstructBVec3:
1596 case glslang::EOpConstructBVec4:
1597 case glslang::EOpConstructInt:
1598 case glslang::EOpConstructIVec2:
1599 case glslang::EOpConstructIVec3:
1600 case glslang::EOpConstructIVec4:
1601 case glslang::EOpConstructUint:
1602 case glslang::EOpConstructUVec2:
1603 case glslang::EOpConstructUVec3:
1604 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001605 case glslang::EOpConstructInt64:
1606 case glslang::EOpConstructI64Vec2:
1607 case glslang::EOpConstructI64Vec3:
1608 case glslang::EOpConstructI64Vec4:
1609 case glslang::EOpConstructUint64:
1610 case glslang::EOpConstructU64Vec2:
1611 case glslang::EOpConstructU64Vec3:
1612 case glslang::EOpConstructU64Vec4:
John Kessenich140f3df2015-06-26 16:58:36 -06001613 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001614 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001615 {
1616 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001617 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001618 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001619 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001620 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001621 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001622 std::vector<spv::Id> constituents;
1623 for (int c = 0; c < (int)arguments.size(); ++c)
1624 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001625 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001626 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001627 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001628 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001629 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001630
1631 builder.clearAccessChain();
1632 builder.setAccessChainRValue(constructed);
1633
1634 return false;
1635 }
1636
1637 // These six are component-wise compares with component-wise results.
1638 // Forward on to createBinaryOperation(), requesting a vector result.
1639 case glslang::EOpLessThan:
1640 case glslang::EOpGreaterThan:
1641 case glslang::EOpLessThanEqual:
1642 case glslang::EOpGreaterThanEqual:
1643 case glslang::EOpVectorEqual:
1644 case glslang::EOpVectorNotEqual:
1645 {
1646 // Map the operation to a binary
1647 binOp = node->getOp();
1648 reduceComparison = false;
1649 switch (node->getOp()) {
1650 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1651 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1652 default: binOp = node->getOp(); break;
1653 }
1654
1655 break;
1656 }
1657 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001658 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001659 binOp = glslang::EOpMul;
1660 break;
1661 case glslang::EOpOuterProduct:
1662 // two vectors multiplied to make a matrix
1663 binOp = glslang::EOpOuterProduct;
1664 break;
1665 case glslang::EOpDot:
1666 {
qining25262b32016-05-06 17:25:16 -04001667 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001668 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001669 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001670 binOp = glslang::EOpMul;
1671 break;
1672 }
1673 case glslang::EOpMod:
1674 // when an aggregate, this is the floating-point mod built-in function,
1675 // which can be emitted by the one in createBinaryOperation()
1676 binOp = glslang::EOpMod;
1677 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001678 case glslang::EOpEmitVertex:
1679 case glslang::EOpEndPrimitive:
1680 case glslang::EOpBarrier:
1681 case glslang::EOpMemoryBarrier:
1682 case glslang::EOpMemoryBarrierAtomicCounter:
1683 case glslang::EOpMemoryBarrierBuffer:
1684 case glslang::EOpMemoryBarrierImage:
1685 case glslang::EOpMemoryBarrierShared:
1686 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001687 case glslang::EOpAllMemoryBarrierWithGroupSync:
1688 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1689 case glslang::EOpWorkgroupMemoryBarrier:
1690 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001691 noReturnValue = true;
1692 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1693 break;
1694
John Kessenich426394d2015-07-23 10:22:48 -06001695 case glslang::EOpAtomicAdd:
1696 case glslang::EOpAtomicMin:
1697 case glslang::EOpAtomicMax:
1698 case glslang::EOpAtomicAnd:
1699 case glslang::EOpAtomicOr:
1700 case glslang::EOpAtomicXor:
1701 case glslang::EOpAtomicExchange:
1702 case glslang::EOpAtomicCompSwap:
1703 atomic = true;
1704 break;
1705
John Kessenich140f3df2015-06-26 16:58:36 -06001706 default:
1707 break;
1708 }
1709
1710 //
1711 // See if it maps to a regular operation.
1712 //
John Kessenich140f3df2015-06-26 16:58:36 -06001713 if (binOp != glslang::EOpNull) {
1714 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1715 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1716 assert(left && right);
1717
1718 builder.clearAccessChain();
1719 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001720 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001721
1722 builder.clearAccessChain();
1723 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001724 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001725
qining25262b32016-05-06 17:25:16 -04001726 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001727 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001728 left->getType().getBasicType(), reduceComparison);
1729
1730 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001731 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001732 builder.clearAccessChain();
1733 builder.setAccessChainRValue(result);
1734
1735 return false;
1736 }
1737
John Kessenich426394d2015-07-23 10:22:48 -06001738 //
1739 // Create the list of operands.
1740 //
John Kessenich140f3df2015-06-26 16:58:36 -06001741 glslang::TIntermSequence& glslangOperands = node->getSequence();
1742 std::vector<spv::Id> operands;
1743 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001744 // special case l-value operands; there are just a few
1745 bool lvalue = false;
1746 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001747 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001748 case glslang::EOpModf:
1749 if (arg == 1)
1750 lvalue = true;
1751 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001752 case glslang::EOpInterpolateAtSample:
1753 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001754#ifdef AMD_EXTENSIONS
1755 case glslang::EOpInterpolateAtVertex:
1756#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001757 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001758 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001759
1760 // Does it need a swizzle inversion? If so, evaluation is inverted;
1761 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001762 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001763 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1764 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1765 }
Rex Xu7a26c172015-12-08 17:12:09 +08001766 break;
Rex Xud4782c12015-09-06 16:30:11 +08001767 case glslang::EOpAtomicAdd:
1768 case glslang::EOpAtomicMin:
1769 case glslang::EOpAtomicMax:
1770 case glslang::EOpAtomicAnd:
1771 case glslang::EOpAtomicOr:
1772 case glslang::EOpAtomicXor:
1773 case glslang::EOpAtomicExchange:
1774 case glslang::EOpAtomicCompSwap:
1775 if (arg == 0)
1776 lvalue = true;
1777 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001778 case glslang::EOpAddCarry:
1779 case glslang::EOpSubBorrow:
1780 if (arg == 2)
1781 lvalue = true;
1782 break;
1783 case glslang::EOpUMulExtended:
1784 case glslang::EOpIMulExtended:
1785 if (arg >= 2)
1786 lvalue = true;
1787 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001788 default:
1789 break;
1790 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001791 builder.clearAccessChain();
1792 if (invertedType != spv::NoType && arg == 0)
1793 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1794 else
1795 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001796 if (lvalue)
1797 operands.push_back(builder.accessChainGetLValue());
1798 else
John Kessenich32cfd492016-02-02 12:37:46 -07001799 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001800 }
John Kessenich426394d2015-07-23 10:22:48 -06001801
1802 if (atomic) {
1803 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001804 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001805 } else {
1806 // Pass through to generic operations.
1807 switch (glslangOperands.size()) {
1808 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001809 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001810 break;
1811 case 1:
qining25262b32016-05-06 17:25:16 -04001812 result = createUnaryOperation(
1813 node->getOp(), precision,
1814 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001815 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001816 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001817 break;
1818 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001819 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001820 break;
1821 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001822 if (invertedType)
1823 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001824 }
1825
1826 if (noReturnValue)
1827 return false;
1828
1829 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001830 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001831 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001832 } else {
1833 builder.clearAccessChain();
1834 builder.setAccessChainRValue(result);
1835 return false;
1836 }
1837}
1838
John Kessenich433e9ff2017-01-26 20:31:11 -07001839// This path handles both if-then-else and ?:
1840// The if-then-else has a node type of void, while
1841// ?: has either a void or a non-void node type
1842//
1843// Leaving the result, when not void:
1844// GLSL only has r-values as the result of a :?, but
1845// if we have an l-value, that can be more efficient if it will
1846// become the base of a complex r-value expression, because the
1847// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001848bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1849{
John Kessenich433e9ff2017-01-26 20:31:11 -07001850 // See if it simple and safe to generate OpSelect instead of using control flow.
1851 // Crucially, side effects must be avoided, and there are performance trade-offs.
1852 // Return true if good idea (and safe) for OpSelect, false otherwise.
1853 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001854 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1855 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001856 return false;
1857
1858 if (node->getTrueBlock() == nullptr ||
1859 node->getFalseBlock() == nullptr)
1860 return false;
1861
1862 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1863 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1864
1865 // return true if a single operand to ? : is okay for OpSelect
1866 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001867 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001868 };
1869
1870 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1871 operandOkay(node->getFalseBlock()->getAsTyped());
1872 };
1873
1874 // Emit OpSelect for this selection.
1875 const auto handleAsOpSelect = [&]() {
1876 node->getCondition()->traverse(this);
1877 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1878 node->getTrueBlock()->traverse(this);
1879 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1880 node->getFalseBlock()->traverse(this);
1881 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1882
John Kesseniche434ad92017-03-30 10:09:28 -06001883 // smear condition to vector, if necessary (AST is always scalar)
1884 if (builder.isVector(trueValue))
1885 condition = builder.smearScalar(spv::NoPrecision, condition,
1886 builder.makeVectorType(builder.makeBoolType(),
1887 builder.getNumComponents(trueValue)));
1888
1889 spv::Id select = builder.createTriOp(spv::OpSelect,
1890 convertGlslangToSpvType(node->getType()), condition,
1891 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001892 builder.clearAccessChain();
1893 builder.setAccessChainRValue(select);
1894 };
1895
1896 // Try for OpSelect
1897
1898 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001899 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1900 if (node->getType().getQualifier().isSpecConstant())
1901 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1902
John Kessenich433e9ff2017-01-26 20:31:11 -07001903 handleAsOpSelect();
1904 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001905 }
1906
John Kessenich433e9ff2017-01-26 20:31:11 -07001907 // Instead, emit control flow...
1908
1909 // Don't handle results as temporaries, because there will be two names
1910 // and better to leave SSA to later passes.
1911 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1912 ? spv::NoResult
1913 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
1914
John Kessenich140f3df2015-06-26 16:58:36 -06001915 // emit the condition before doing anything with selection
1916 node->getCondition()->traverse(this);
1917
1918 // make an "if" based on the value created by the condition
John Kessenich32cfd492016-02-02 12:37:46 -07001919 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), builder);
John Kessenich140f3df2015-06-26 16:58:36 -06001920
John Kessenich433e9ff2017-01-26 20:31:11 -07001921 // emit the "then" statement
1922 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001923 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001924 if (result != spv::NoResult)
1925 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001926 }
1927
John Kessenich433e9ff2017-01-26 20:31:11 -07001928 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06001929 ifBuilder.makeBeginElse();
1930 // emit the "else" statement
1931 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07001932 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07001933 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001934 }
1935
John Kessenich433e9ff2017-01-26 20:31:11 -07001936 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06001937 ifBuilder.makeEndIf();
1938
John Kessenich433e9ff2017-01-26 20:31:11 -07001939 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06001940 // GLSL only has r-values as the result of a :?, but
1941 // if we have an l-value, that can be more efficient if it will
1942 // become the base of a complex r-value expression, because the
1943 // next layer copies r-values into memory to use the access-chain mechanism
1944 builder.clearAccessChain();
1945 builder.setAccessChainLValue(result);
1946 }
1947
1948 return false;
1949}
1950
1951bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
1952{
1953 // emit and get the condition before doing anything with switch
1954 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001955 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001956
1957 // browse the children to sort out code segments
1958 int defaultSegment = -1;
1959 std::vector<TIntermNode*> codeSegments;
1960 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
1961 std::vector<int> caseValues;
1962 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
1963 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
1964 TIntermNode* child = *c;
1965 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02001966 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001967 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02001968 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06001969 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
1970 } else
1971 codeSegments.push_back(child);
1972 }
1973
qining25262b32016-05-06 17:25:16 -04001974 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06001975 // statements between the last case and the end of the switch statement
1976 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
1977 (int)codeSegments.size() == defaultSegment)
1978 codeSegments.push_back(nullptr);
1979
1980 // make the switch statement
1981 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
baldurkd76692d2015-07-12 11:32:58 +02001982 builder.makeSwitch(selector, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06001983
1984 // emit all the code in the segments
1985 breakForLoop.push(false);
1986 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
1987 builder.nextSwitchSegment(segmentBlocks, s);
1988 if (codeSegments[s])
1989 codeSegments[s]->traverse(this);
1990 else
1991 builder.addSwitchBreak();
1992 }
1993 breakForLoop.pop();
1994
1995 builder.endSwitch(segmentBlocks);
1996
1997 return false;
1998}
1999
2000void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2001{
2002 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002003 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002004
2005 builder.clearAccessChain();
2006 builder.setAccessChainRValue(constant);
2007}
2008
2009bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2010{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002011 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002012 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002013
2014 // Loop control:
2015 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2016
2017 // TODO: dependency length
2018
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002019 // Spec requires back edges to target header blocks, and every header block
2020 // must dominate its merge block. Make a header block first to ensure these
2021 // conditions are met. By definition, it will contain OpLoopMerge, followed
2022 // by a block-ending branch. But we don't want to put any other body/test
2023 // instructions in it, since the body/test may have arbitrary instructions,
2024 // including merges of its own.
2025 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002026 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002027 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002028 spv::Block& test = builder.makeNewBlock();
2029 builder.createBranch(&test);
2030
2031 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002032 node->getTest()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002033 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002034 accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002035 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2036
2037 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002038 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002039 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002040 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002041 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002042 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002043
2044 builder.setBuildPoint(&blocks.continue_target);
2045 if (node->getTerminal())
2046 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002047 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002048 } else {
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002049 builder.createBranch(&blocks.body);
2050
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002051 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002052 builder.setBuildPoint(&blocks.body);
2053 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002054 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002055 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002056 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002057
2058 builder.setBuildPoint(&blocks.continue_target);
2059 if (node->getTerminal())
2060 node->getTerminal()->traverse(this);
2061 if (node->getTest()) {
2062 node->getTest()->traverse(this);
2063 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002064 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002065 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002066 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002067 // TODO: unless there was a break/return/discard instruction
2068 // somewhere in the body, this is an infinite loop, so we should
2069 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002070 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002071 }
John Kessenich140f3df2015-06-26 16:58:36 -06002072 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002073 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002074 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002075 return false;
2076}
2077
2078bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2079{
2080 if (node->getExpression())
2081 node->getExpression()->traverse(this);
2082
2083 switch (node->getFlowOp()) {
2084 case glslang::EOpKill:
2085 builder.makeDiscard();
2086 break;
2087 case glslang::EOpBreak:
2088 if (breakForLoop.top())
2089 builder.createLoopExit();
2090 else
2091 builder.addSwitchBreak();
2092 break;
2093 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002094 builder.createLoopContinue();
2095 break;
2096 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002097 if (node->getExpression()) {
2098 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2099 spv::Id returnId = accessChainLoad(glslangReturnType);
2100 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2101 builder.clearAccessChain();
2102 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2103 builder.setAccessChainLValue(copyId);
2104 multiTypeStore(glslangReturnType, returnId);
2105 returnId = builder.createLoad(copyId);
2106 }
2107 builder.makeReturn(false, returnId);
2108 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002109 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002110
2111 builder.clearAccessChain();
2112 break;
2113
2114 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002115 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002116 break;
2117 }
2118
2119 return false;
2120}
2121
2122spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2123{
qining25262b32016-05-06 17:25:16 -04002124 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002125 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002126 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002127 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002128 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002129 }
2130
2131 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002132 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002133 spv::Id spvType = convertGlslangToSpvType(node->getType());
2134
Rex Xuf89ad982017-04-07 23:22:33 +08002135#ifdef AMD_EXTENSIONS
2136 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16);
2137 if (contains16BitType) {
2138 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2139 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2140 builder.addCapability(spv::CapabilityStorageInputOutput16);
2141 } else if (storageClass == spv::StorageClassPushConstant) {
2142 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2143 builder.addCapability(spv::CapabilityStoragePushConstant16);
2144 } else if (storageClass == spv::StorageClassUniform) {
2145 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2146 builder.addCapability(spv::CapabilityStorageUniform16);
2147 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2148 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2149 }
2150 }
2151#endif
2152
John Kessenich140f3df2015-06-26 16:58:36 -06002153 const char* name = node->getName().c_str();
2154 if (glslang::IsAnonymous(name))
2155 name = "";
2156
2157 return builder.createVariable(storageClass, spvType, name);
2158}
2159
2160// Return type Id of the sampled type.
2161spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2162{
2163 switch (sampler.type) {
2164 case glslang::EbtFloat: return builder.makeFloatType(32);
2165 case glslang::EbtInt: return builder.makeIntType(32);
2166 case glslang::EbtUint: return builder.makeUintType(32);
2167 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002168 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002169 return builder.makeFloatType(32);
2170 }
2171}
2172
John Kessenich8c8505c2016-07-26 12:50:38 -06002173// If node is a swizzle operation, return the type that should be used if
2174// the swizzle base is first consumed by another operation, before the swizzle
2175// is applied.
2176spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2177{
John Kessenichecba76f2017-01-06 00:34:48 -07002178 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002179 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2180 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2181 else
2182 return spv::NoType;
2183}
2184
2185// When inverting a swizzle with a parent op, this function
2186// will apply the swizzle operation to a completed parent operation.
2187spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2188{
2189 std::vector<unsigned> swizzle;
2190 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2191 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2192}
2193
John Kessenich8c8505c2016-07-26 12:50:38 -06002194// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2195void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2196{
2197 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2198 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2199 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2200}
2201
John Kessenich3ac051e2015-12-20 11:29:16 -07002202// Convert from a glslang type to an SPV type, by calling into a
2203// recursive version of this function. This establishes the inherited
2204// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002205spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2206{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002207 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002208}
2209
2210// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002211// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002212// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002213spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002214{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002215 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002216
2217 switch (type.getBasicType()) {
2218 case glslang::EbtVoid:
2219 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002220 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002221 break;
2222 case glslang::EbtFloat:
2223 spvType = builder.makeFloatType(32);
2224 break;
2225 case glslang::EbtDouble:
2226 spvType = builder.makeFloatType(64);
2227 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002228#ifdef AMD_EXTENSIONS
2229 case glslang::EbtFloat16:
2230 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002231 spvType = builder.makeFloatType(16);
2232 break;
2233#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002234 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002235 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2236 // a 32-bit int where non-0 means true.
2237 if (explicitLayout != glslang::ElpNone)
2238 spvType = builder.makeUintType(32);
2239 else
2240 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002241 break;
2242 case glslang::EbtInt:
2243 spvType = builder.makeIntType(32);
2244 break;
2245 case glslang::EbtUint:
2246 spvType = builder.makeUintType(32);
2247 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002248 case glslang::EbtInt64:
2249 builder.addCapability(spv::CapabilityInt64);
2250 spvType = builder.makeIntType(64);
2251 break;
2252 case glslang::EbtUint64:
2253 builder.addCapability(spv::CapabilityInt64);
2254 spvType = builder.makeUintType(64);
2255 break;
John Kessenich426394d2015-07-23 10:22:48 -06002256 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002257 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002258 spvType = builder.makeUintType(32);
2259 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002260 case glslang::EbtSampler:
2261 {
2262 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002263 if (sampler.sampler) {
2264 // pure sampler
2265 spvType = builder.makeSamplerType();
2266 } else {
2267 // an image is present, make its type
2268 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2269 sampler.image ? 2 : 1, TranslateImageFormat(type));
2270 if (sampler.combined) {
2271 // already has both image and sampler, make the combined type
2272 spvType = builder.makeSampledImageType(spvType);
2273 }
John Kessenich55e7d112015-11-15 21:33:39 -07002274 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002275 }
John Kessenich140f3df2015-06-26 16:58:36 -06002276 break;
2277 case glslang::EbtStruct:
2278 case glslang::EbtBlock:
2279 {
2280 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002281 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002282
2283 // Try to share structs for different layouts, but not yet for other
2284 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002285 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002286 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002287 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002288 break;
2289
2290 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002291 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002292 memberRemapper[glslangMembers].resize(glslangMembers->size());
2293 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002294 }
2295 break;
2296 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002297 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002298 break;
2299 }
2300
2301 if (type.isMatrix())
2302 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2303 else {
2304 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2305 if (type.getVectorSize() > 1)
2306 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2307 }
2308
2309 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002310 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2311
John Kessenichc9a80832015-09-12 12:17:44 -06002312 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002313 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002314 // We need to decorate array strides for types needing explicit layout, except blocks.
2315 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002316 // Use a dummy glslang type for querying internal strides of
2317 // arrays of arrays, but using just a one-dimensional array.
2318 glslang::TType simpleArrayType(type, 0); // deference type of the array
2319 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2320 simpleArrayType.getArraySizes().dereference();
2321
2322 // Will compute the higher-order strides here, rather than making a whole
2323 // pile of types and doing repetitive recursion on their contents.
2324 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2325 }
John Kessenichf8842e52016-01-04 19:22:56 -07002326
2327 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002328 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002329 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002330 if (stride > 0)
2331 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002332 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002333 }
2334 } else {
2335 // single-dimensional array, and don't yet have stride
2336
John Kessenichf8842e52016-01-04 19:22:56 -07002337 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002338 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2339 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002340 }
John Kessenich31ed4832015-09-09 17:51:38 -06002341
John Kessenichc9a80832015-09-12 12:17:44 -06002342 // Do the outer dimension, which might not be known for a runtime-sized array
2343 if (type.isRuntimeSizedArray()) {
2344 spvType = builder.makeRuntimeArray(spvType);
2345 } else {
2346 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002347 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002348 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002349 if (stride > 0)
2350 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002351 }
2352
2353 return spvType;
2354}
2355
John Kessenich0e737842017-03-24 18:38:16 -06002356// TODO: this functionality should exist at a higher level, in creating the AST
2357//
2358// Identify interface members that don't have their required extension turned on.
2359//
2360bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2361{
2362 auto& extensions = glslangIntermediate->getRequestedExtensions();
2363
Rex Xubcf291a2017-03-29 23:01:36 +08002364 if (member.getFieldName() == "gl_ViewportMask" &&
2365 extensions.find("GL_NV_viewport_array2") == extensions.end())
2366 return true;
2367 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2368 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2369 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002370 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2371 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2372 return true;
2373 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2374 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2375 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002376 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2377 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2378 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002379
2380 return false;
2381};
2382
John Kessenich6090df02016-06-30 21:18:02 -06002383// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2384// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2385// Mutually recursive with convertGlslangToSpvType().
2386spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2387 const glslang::TTypeList* glslangMembers,
2388 glslang::TLayoutPacking explicitLayout,
2389 const glslang::TQualifier& qualifier)
2390{
2391 // Create a vector of struct types for SPIR-V to consume
2392 std::vector<spv::Id> spvMembers;
2393 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
2394 int locationOffset = 0; // for use across struct members, when they are called recursively
2395 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2396 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2397 if (glslangMember.hiddenMember()) {
2398 ++memberDelta;
2399 if (type.getBasicType() == glslang::EbtBlock)
2400 memberRemapper[glslangMembers][i] = -1;
2401 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002402 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002403 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002404 if (filterMember(glslangMember))
2405 continue;
2406 }
John Kessenich6090df02016-06-30 21:18:02 -06002407 // modify just this child's view of the qualifier
2408 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2409 InheritQualifiers(memberQualifier, qualifier);
2410
2411 // manually inherit location; it's more complex
2412 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
2413 memberQualifier.layoutLocation = qualifier.layoutLocation + locationOffset;
2414 if (qualifier.hasLocation())
2415 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2416
2417 // recurse
2418 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2419 }
2420 }
2421
2422 // Make the SPIR-V type
2423 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002424 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002425 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2426
2427 // Decorate it
2428 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2429
2430 return spvType;
2431}
2432
2433void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2434 const glslang::TTypeList* glslangMembers,
2435 glslang::TLayoutPacking explicitLayout,
2436 const glslang::TQualifier& qualifier,
2437 spv::Id spvType)
2438{
2439 // Name and decorate the non-hidden members
2440 int offset = -1;
2441 int locationOffset = 0; // for use within the members of this struct
2442 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2443 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2444 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002445 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002446 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002447 if (filterMember(glslangMember))
2448 continue;
2449 }
John Kessenich6090df02016-06-30 21:18:02 -06002450
2451 // modify just this child's view of the qualifier
2452 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2453 InheritQualifiers(memberQualifier, qualifier);
2454
2455 // using -1 above to indicate a hidden member
2456 if (member >= 0) {
2457 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2458 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2459 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2460 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002461 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2462 type.getQualifier().storage == glslang::EvqVaryingOut) {
2463 if (type.getBasicType() == glslang::EbtBlock ||
2464 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002465 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2466 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2467 }
2468 }
2469 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2470
2471 if (qualifier.storage == glslang::EvqBuffer) {
2472 std::vector<spv::Decoration> memory;
2473 TranslateMemoryDecoration(memberQualifier, memory);
2474 for (unsigned int i = 0; i < memory.size(); ++i)
2475 addMemberDecoration(spvType, member, memory[i]);
2476 }
2477
John Kessenich2f47bc92016-06-30 21:47:35 -06002478 // Compute location decoration; tricky based on whether inheritance is at play and
2479 // what kind of container we have, etc.
John Kessenich6090df02016-06-30 21:18:02 -06002480 // TODO: This algorithm (and it's cousin above doing almost the same thing) should
2481 // probably move to the linker stage of the front end proper, and just have the
2482 // answer sitting already distributed throughout the individual member locations.
2483 int location = -1; // will only decorate if present or inherited
John Kessenich2f47bc92016-06-30 21:47:35 -06002484 // Ignore member locations if the container is an array, as that's
2485 // ill-specified and decisions have been made to not allow this anyway.
2486 // The object itself must have a location, and that comes out from decorating the object,
2487 // not the type (this code decorates types).
2488 if (! type.isArray()) {
2489 if (memberQualifier.hasLocation()) { // no inheritance, or override of inheritance
2490 // struct members should not have explicit locations
2491 assert(type.getBasicType() != glslang::EbtStruct);
2492 location = memberQualifier.layoutLocation;
2493 } else if (type.getBasicType() != glslang::EbtBlock) {
2494 // If it is a not a Block, (...) Its members are assigned consecutive locations (...)
2495 // The members, and their nested types, must not themselves have Location decorations.
2496 } else if (qualifier.hasLocation()) // inheritance
2497 location = qualifier.layoutLocation + locationOffset;
2498 }
John Kessenich6090df02016-06-30 21:18:02 -06002499 if (location >= 0)
2500 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, location);
2501
John Kessenich2f47bc92016-06-30 21:47:35 -06002502 if (qualifier.hasLocation()) // track for upcoming inheritance
2503 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2504
John Kessenich6090df02016-06-30 21:18:02 -06002505 // component, XFB, others
2506 if (glslangMember.getQualifier().hasComponent())
2507 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2508 if (glslangMember.getQualifier().hasXfbOffset())
2509 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2510 else if (explicitLayout != glslang::ElpNone) {
2511 // figure out what to do with offset, which is accumulating
2512 int nextOffset;
2513 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2514 if (offset >= 0)
2515 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2516 offset = nextOffset;
2517 }
2518
2519 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2520 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2521
2522 // built-in variable decorations
2523 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002524 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002525 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002526
2527#ifdef NV_EXTENSIONS
2528 if (builtIn == spv::BuiltInLayer) {
2529 // SPV_NV_viewport_array2 extension
2530 if (glslangMember.getQualifier().layoutViewportRelative){
2531 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2532 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2533 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2534 }
2535 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2536 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2537 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2538 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2539 }
2540 }
chaocdf3956c2017-02-14 14:52:34 -08002541 if (glslangMember.getQualifier().layoutPassthrough) {
2542 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2543 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2544 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2545 }
chaoc771d89f2017-01-13 01:10:53 -08002546#endif
John Kessenich6090df02016-06-30 21:18:02 -06002547 }
2548 }
2549
2550 // Decorate the structure
2551 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002552 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002553 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2554 builder.addCapability(spv::CapabilityGeometryStreams);
2555 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2556 }
2557 if (glslangIntermediate->getXfbMode()) {
2558 builder.addCapability(spv::CapabilityTransformFeedback);
2559 if (type.getQualifier().hasXfbStride())
2560 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2561 if (type.getQualifier().hasXfbBuffer())
2562 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2563 }
2564}
2565
John Kessenich6c292d32016-02-15 20:58:50 -07002566// Turn the expression forming the array size into an id.
2567// This is not quite trivial, because of specialization constants.
2568// Sometimes, a raw constant is turned into an Id, and sometimes
2569// a specialization constant expression is.
2570spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2571{
2572 // First, see if this is sized with a node, meaning a specialization constant:
2573 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2574 if (specNode != nullptr) {
2575 builder.clearAccessChain();
2576 specNode->traverse(this);
2577 return accessChainLoad(specNode->getAsTyped()->getType());
2578 }
qining25262b32016-05-06 17:25:16 -04002579
John Kessenich6c292d32016-02-15 20:58:50 -07002580 // Otherwise, need a compile-time (front end) size, get it:
2581 int size = arraySizes.getDimSize(dim);
2582 assert(size > 0);
2583 return builder.makeUintConstant(size);
2584}
2585
John Kessenich103bef92016-02-08 21:38:15 -07002586// Wrap the builder's accessChainLoad to:
2587// - localize handling of RelaxedPrecision
2588// - use the SPIR-V inferred type instead of another conversion of the glslang type
2589// (avoids unnecessary work and possible type punning for structures)
2590// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002591spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2592{
John Kessenich103bef92016-02-08 21:38:15 -07002593 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2594 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2595
2596 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002597 if (type.getBasicType() == glslang::EbtBool) {
2598 if (builder.isScalarType(nominalTypeId)) {
2599 // Conversion for bool
2600 spv::Id boolType = builder.makeBoolType();
2601 if (nominalTypeId != boolType)
2602 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2603 } else if (builder.isVectorType(nominalTypeId)) {
2604 // Conversion for bvec
2605 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2606 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2607 if (nominalTypeId != bvecType)
2608 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2609 }
2610 }
John Kessenich103bef92016-02-08 21:38:15 -07002611
2612 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002613}
2614
Rex Xu27253232016-02-23 17:51:09 +08002615// Wrap the builder's accessChainStore to:
2616// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002617//
2618// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002619void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2620{
2621 // Need to convert to abstract types when necessary
2622 if (type.getBasicType() == glslang::EbtBool) {
2623 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2624
2625 if (builder.isScalarType(nominalTypeId)) {
2626 // Conversion for bool
2627 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002628 if (nominalTypeId != boolType) {
2629 // keep these outside arguments, for determinant order-of-evaluation
2630 spv::Id one = builder.makeUintConstant(1);
2631 spv::Id zero = builder.makeUintConstant(0);
2632 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2633 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002634 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002635 } else if (builder.isVectorType(nominalTypeId)) {
2636 // Conversion for bvec
2637 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2638 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002639 if (nominalTypeId != bvecType) {
2640 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002641 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2642 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2643 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002644 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002645 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2646 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002647 }
2648 }
2649
2650 builder.accessChainStore(rvalue);
2651}
2652
John Kessenich4bf71552016-09-02 11:20:21 -06002653// For storing when types match at the glslang level, but not might match at the
2654// SPIR-V level.
2655//
2656// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002657// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002658// as in a member-decorated way.
2659//
2660// NOTE: This function can handle any store request; if it's not special it
2661// simplifies to a simple OpStore.
2662//
2663// Implicitly uses the existing builder.accessChain as the storage target.
2664void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2665{
John Kessenichb3e24e42016-09-11 12:33:43 -06002666 // we only do the complex path here if it's an aggregate
2667 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002668 accessChainStore(type, rValue);
2669 return;
2670 }
2671
John Kessenichb3e24e42016-09-11 12:33:43 -06002672 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002673 spv::Id rType = builder.getTypeId(rValue);
2674 spv::Id lValue = builder.accessChainGetLValue();
2675 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2676 if (lType == rType) {
2677 accessChainStore(type, rValue);
2678 return;
2679 }
2680
John Kessenichb3e24e42016-09-11 12:33:43 -06002681 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002682 // where the two types were the same type in GLSL. This requires member
2683 // by member copy, recursively.
2684
John Kessenichb3e24e42016-09-11 12:33:43 -06002685 // If an array, copy element by element.
2686 if (type.isArray()) {
2687 glslang::TType glslangElementType(type, 0);
2688 spv::Id elementRType = builder.getContainedTypeId(rType);
2689 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2690 // get the source member
2691 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002692
John Kessenichb3e24e42016-09-11 12:33:43 -06002693 // set up the target storage
2694 builder.clearAccessChain();
2695 builder.setAccessChainLValue(lValue);
2696 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002697
John Kessenichb3e24e42016-09-11 12:33:43 -06002698 // store the member
2699 multiTypeStore(glslangElementType, elementRValue);
2700 }
2701 } else {
2702 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002703
John Kessenichb3e24e42016-09-11 12:33:43 -06002704 // loop over structure members
2705 const glslang::TTypeList& members = *type.getStruct();
2706 for (int m = 0; m < (int)members.size(); ++m) {
2707 const glslang::TType& glslangMemberType = *members[m].type;
2708
2709 // get the source member
2710 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2711 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2712
2713 // set up the target storage
2714 builder.clearAccessChain();
2715 builder.setAccessChainLValue(lValue);
2716 builder.accessChainPush(builder.makeIntConstant(m));
2717
2718 // store the member
2719 multiTypeStore(glslangMemberType, memberRValue);
2720 }
John Kessenich4bf71552016-09-02 11:20:21 -06002721 }
2722}
2723
John Kessenichf85e8062015-12-19 13:57:10 -07002724// Decide whether or not this type should be
2725// decorated with offsets and strides, and if so
2726// whether std140 or std430 rules should be applied.
2727glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002728{
John Kessenichf85e8062015-12-19 13:57:10 -07002729 // has to be a block
2730 if (type.getBasicType() != glslang::EbtBlock)
2731 return glslang::ElpNone;
2732
2733 // has to be a uniform or buffer block
2734 if (type.getQualifier().storage != glslang::EvqUniform &&
2735 type.getQualifier().storage != glslang::EvqBuffer)
2736 return glslang::ElpNone;
2737
2738 // return the layout to use
2739 switch (type.getQualifier().layoutPacking) {
2740 case glslang::ElpStd140:
2741 case glslang::ElpStd430:
2742 return type.getQualifier().layoutPacking;
2743 default:
2744 return glslang::ElpNone;
2745 }
John Kessenich31ed4832015-09-09 17:51:38 -06002746}
2747
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002748// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002749int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002750{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002751 int size;
John Kessenich49987892015-12-29 17:11:44 -07002752 int stride;
2753 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002754
2755 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002756}
2757
John Kessenich49987892015-12-29 17:11:44 -07002758// 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 -07002759// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002760int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002761{
John Kessenich49987892015-12-29 17:11:44 -07002762 glslang::TType elementType;
2763 elementType.shallowCopy(matrixType);
2764 elementType.clearArraySizes();
2765
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002766 int size;
John Kessenich49987892015-12-29 17:11:44 -07002767 int stride;
2768 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2769
2770 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002771}
2772
John Kessenich5e4b1242015-08-06 22:53:06 -06002773// Given a member type of a struct, realign the current offset for it, and compute
2774// the next (not yet aligned) offset for the next member, which will get aligned
2775// on the next call.
2776// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2777// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2778// -1 means a non-forced member offset (no decoration needed).
John Kessenich6c292d32016-02-15 20:58:50 -07002779void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& /*structType*/, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002780 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002781{
2782 // this will get a positive value when deemed necessary
2783 nextOffset = -1;
2784
John Kessenich5e4b1242015-08-06 22:53:06 -06002785 // override anything in currentOffset with user-set offset
2786 if (memberType.getQualifier().hasOffset())
2787 currentOffset = memberType.getQualifier().layoutOffset;
2788
2789 // It could be that current linker usage in glslang updated all the layoutOffset,
2790 // in which case the following code does not matter. But, that's not quite right
2791 // once cross-compilation unit GLSL validation is done, as the original user
2792 // settings are needed in layoutOffset, and then the following will come into play.
2793
John Kessenichf85e8062015-12-19 13:57:10 -07002794 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002795 if (! memberType.getQualifier().hasOffset())
2796 currentOffset = -1;
2797
2798 return;
2799 }
2800
John Kessenichf85e8062015-12-19 13:57:10 -07002801 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002802 if (currentOffset < 0)
2803 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002804
John Kessenich5e4b1242015-08-06 22:53:06 -06002805 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2806 // but possibly not yet correctly aligned.
2807
2808 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002809 int dummyStride;
2810 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002811
2812 // Adjust alignment for HLSL rules
2813 if (glslangIntermediate->usingHlslOFfsets() &&
2814 ! memberType.isArray() && memberType.isVector()) {
2815 int dummySize;
2816 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2817 if (componentAlignment <= 4)
2818 memberAlignment = componentAlignment;
2819 }
2820
2821 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002822 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002823
2824 // Bump up to vec4 if there is a bad straddle
2825 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2826 glslang::RoundToPow2(currentOffset, 16);
2827
John Kessenich5e4b1242015-08-06 22:53:06 -06002828 nextOffset = currentOffset + memberSize;
2829}
2830
David Netoa901ffe2016-06-08 14:11:40 +01002831void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002832{
David Netoa901ffe2016-06-08 14:11:40 +01002833 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2834 switch (glslangBuiltIn)
2835 {
2836 case glslang::EbvClipDistance:
2837 case glslang::EbvCullDistance:
2838 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002839#ifdef NV_EXTENSIONS
2840 case glslang::EbvLayer:
Rex Xu5e317ff2017-03-16 23:02:39 +08002841 case glslang::EbvViewportIndex:
chaoc771d89f2017-01-13 01:10:53 -08002842 case glslang::EbvViewportMaskNV:
2843 case glslang::EbvSecondaryPositionNV:
2844 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002845 case glslang::EbvPositionPerViewNV:
2846 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002847#endif
David Netoa901ffe2016-06-08 14:11:40 +01002848 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2849 // Alternately, we could just call this for any glslang built-in, since the
2850 // capability already guards against duplicates.
2851 TranslateBuiltInDecoration(glslangBuiltIn, false);
2852 break;
2853 default:
2854 // Capabilities were already generated when the struct was declared.
2855 break;
2856 }
John Kessenichebb50532016-05-16 19:22:05 -06002857}
2858
John Kessenich6fccb3c2016-09-19 16:01:41 -06002859bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002860{
John Kessenicheee9d532016-09-19 18:09:30 -06002861 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002862}
2863
2864// Make all the functions, skeletally, without actually visiting their bodies.
2865void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2866{
2867 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2868 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002869 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002870 continue;
2871
2872 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002873 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002874 //
qining25262b32016-05-06 17:25:16 -04002875 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002876 // function. What it is an address of varies:
2877 //
John Kessenich4bf71552016-09-02 11:20:21 -06002878 // - "in" parameters not marked as "const" can be written to without modifying the calling
2879 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002880 //
2881 // - "const in" parameters can just be the r-value, as no writes need occur.
2882 //
John Kessenich4bf71552016-09-02 11:20:21 -06002883 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2884 // 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 -06002885
2886 std::vector<spv::Id> paramTypes;
John Kessenich32cfd492016-02-02 12:37:46 -07002887 std::vector<spv::Decoration> paramPrecisions;
John Kessenich140f3df2015-06-26 16:58:36 -06002888 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2889
John Kessenich37789792017-03-21 23:56:40 -06002890 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() == glslangIntermediate->implicitThisName;
2891
John Kessenich140f3df2015-06-26 16:58:36 -06002892 for (int p = 0; p < (int)parameters.size(); ++p) {
2893 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2894 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002895 // can we pass by reference?
2896 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002897 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002898 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002899 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002900 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07002901 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06002902 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
2903 else
John Kessenich4bf71552016-09-02 11:20:21 -06002904 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenich32cfd492016-02-02 12:37:46 -07002905 paramPrecisions.push_back(TranslatePrecisionDecoration(paramType));
John Kessenich140f3df2015-06-26 16:58:36 -06002906 paramTypes.push_back(typeId);
2907 }
2908
2909 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07002910 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
2911 convertGlslangToSpvType(glslFunction->getType()),
2912 glslFunction->getName().c_str(), paramTypes, paramPrecisions, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06002913 if (implicitThis)
2914 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06002915
2916 // Track function to emit/call later
2917 functionMap[glslFunction->getName().c_str()] = function;
2918
2919 // Set the parameter id's
2920 for (int p = 0; p < (int)parameters.size(); ++p) {
2921 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
2922 // give a name too
2923 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
2924 }
2925 }
2926}
2927
2928// Process all the initializers, while skipping the functions and link objects
2929void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
2930{
2931 builder.setBuildPoint(shaderEntry->getLastBlock());
2932 for (int i = 0; i < (int)initializers.size(); ++i) {
2933 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
2934 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
2935
2936 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06002937 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06002938 initializer->traverse(this);
2939 }
2940 }
2941}
2942
2943// Process all the functions, while skipping initializers.
2944void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
2945{
2946 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2947 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07002948 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06002949 node->traverse(this);
2950 }
2951}
2952
2953void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
2954{
qining25262b32016-05-06 17:25:16 -04002955 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06002956 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06002957 currentFunction = functionMap[node->getName().c_str()];
2958 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06002959 builder.setBuildPoint(functionBlock);
2960}
2961
Rex Xu04db3f52015-09-16 11:44:02 +08002962void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06002963{
Rex Xufc618912015-09-09 16:42:49 +08002964 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08002965
2966 glslang::TSampler sampler = {};
2967 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08002968 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08002969 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
2970 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
2971 }
2972
John Kessenich140f3df2015-06-26 16:58:36 -06002973 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
2974 builder.clearAccessChain();
2975 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08002976
2977 // Special case l-value operands
2978 bool lvalue = false;
2979 switch (node.getOp()) {
2980 case glslang::EOpImageAtomicAdd:
2981 case glslang::EOpImageAtomicMin:
2982 case glslang::EOpImageAtomicMax:
2983 case glslang::EOpImageAtomicAnd:
2984 case glslang::EOpImageAtomicOr:
2985 case glslang::EOpImageAtomicXor:
2986 case glslang::EOpImageAtomicExchange:
2987 case glslang::EOpImageAtomicCompSwap:
2988 if (i == 0)
2989 lvalue = true;
2990 break;
Rex Xu5eafa472016-02-19 22:24:03 +08002991 case glslang::EOpSparseImageLoad:
2992 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
2993 lvalue = true;
2994 break;
Rex Xu48edadf2015-12-31 16:11:41 +08002995 case glslang::EOpSparseTexture:
2996 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
2997 lvalue = true;
2998 break;
2999 case glslang::EOpSparseTextureClamp:
3000 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3001 lvalue = true;
3002 break;
3003 case glslang::EOpSparseTextureLod:
3004 case glslang::EOpSparseTextureOffset:
3005 if (i == 3)
3006 lvalue = true;
3007 break;
3008 case glslang::EOpSparseTextureFetch:
3009 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3010 lvalue = true;
3011 break;
3012 case glslang::EOpSparseTextureFetchOffset:
3013 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3014 lvalue = true;
3015 break;
3016 case glslang::EOpSparseTextureLodOffset:
3017 case glslang::EOpSparseTextureGrad:
3018 case glslang::EOpSparseTextureOffsetClamp:
3019 if (i == 4)
3020 lvalue = true;
3021 break;
3022 case glslang::EOpSparseTextureGradOffset:
3023 case glslang::EOpSparseTextureGradClamp:
3024 if (i == 5)
3025 lvalue = true;
3026 break;
3027 case glslang::EOpSparseTextureGradOffsetClamp:
3028 if (i == 6)
3029 lvalue = true;
3030 break;
3031 case glslang::EOpSparseTextureGather:
3032 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3033 lvalue = true;
3034 break;
3035 case glslang::EOpSparseTextureGatherOffset:
3036 case glslang::EOpSparseTextureGatherOffsets:
3037 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3038 lvalue = true;
3039 break;
Rex Xufc618912015-09-09 16:42:49 +08003040 default:
3041 break;
3042 }
3043
Rex Xu6b86d492015-09-16 17:48:22 +08003044 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003045 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003046 else
John Kessenich32cfd492016-02-02 12:37:46 -07003047 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003048 }
3049}
3050
John Kessenichfc51d282015-08-19 13:34:18 -06003051void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003052{
John Kessenichfc51d282015-08-19 13:34:18 -06003053 builder.clearAccessChain();
3054 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003055 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003056}
John Kessenich140f3df2015-06-26 16:58:36 -06003057
John Kessenichfc51d282015-08-19 13:34:18 -06003058spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3059{
Rex Xufc618912015-09-09 16:42:49 +08003060 if (! node->isImage() && ! node->isTexture()) {
John Kessenichfc51d282015-08-19 13:34:18 -06003061 return spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06003062 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003063 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003064
John Kessenichfc51d282015-08-19 13:34:18 -06003065 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003066 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3067 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3068 std::vector<spv::Id> arguments;
3069 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003070 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003071 else
3072 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003073 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003074
3075 spv::Builder::TextureParameters params = { };
3076 params.sampler = arguments[0];
3077
Rex Xu04db3f52015-09-16 11:44:02 +08003078 glslang::TCrackedTextureOp cracked;
3079 node->crackTexture(sampler, cracked);
3080
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003081 const bool isUnsignedResult =
3082 node->getType().getBasicType() == glslang::EbtUint64 ||
3083 node->getType().getBasicType() == glslang::EbtUint;
3084
John Kessenichfc51d282015-08-19 13:34:18 -06003085 // Check for queries
3086 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003087 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3088 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003089 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003090
John Kessenichfc51d282015-08-19 13:34:18 -06003091 switch (node->getOp()) {
3092 case glslang::EOpImageQuerySize:
3093 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003094 if (arguments.size() > 1) {
3095 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003096 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003097 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003098 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003099 case glslang::EOpImageQuerySamples:
3100 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003101 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003102 case glslang::EOpTextureQueryLod:
3103 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003104 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003105 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003106 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003107 case glslang::EOpSparseTexelsResident:
3108 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003109 default:
3110 assert(0);
3111 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003112 }
John Kessenich140f3df2015-06-26 16:58:36 -06003113 }
3114
Rex Xufc618912015-09-09 16:42:49 +08003115 // Check for image functions other than queries
3116 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003117 std::vector<spv::Id> operands;
3118 auto opIt = arguments.begin();
3119 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003120
3121 // Handle subpass operations
3122 // TODO: GLSL should change to have the "MS" only on the type rather than the
3123 // built-in function.
3124 if (cracked.subpass) {
3125 // add on the (0,0) coordinate
3126 spv::Id zero = builder.makeIntConstant(0);
3127 std::vector<spv::Id> comps;
3128 comps.push_back(zero);
3129 comps.push_back(zero);
3130 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3131 if (sampler.ms) {
3132 operands.push_back(spv::ImageOperandsSampleMask);
3133 operands.push_back(*(opIt++));
3134 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003135 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003136 }
3137
John Kessenich56bab042015-09-16 10:54:31 -06003138 operands.push_back(*(opIt++));
John Kessenich56bab042015-09-16 10:54:31 -06003139 if (node->getOp() == glslang::EOpImageLoad) {
John Kessenich55e7d112015-11-15 21:33:39 -07003140 if (sampler.ms) {
3141 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003142 operands.push_back(*opIt);
John Kessenich55e7d112015-11-15 21:33:39 -07003143 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003144 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3145 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003146 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich56bab042015-09-16 10:54:31 -06003147 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu7beb4412015-12-15 17:52:45 +08003148 if (sampler.ms) {
3149 operands.push_back(*(opIt + 1));
3150 operands.push_back(spv::ImageOperandsSampleMask);
3151 operands.push_back(*opIt);
3152 } else
3153 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003154 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003155 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3156 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003157 return spv::NoResult;
Rex Xu5eafa472016-02-19 22:24:03 +08003158 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
3159 builder.addCapability(spv::CapabilitySparseResidency);
3160 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3161 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3162
3163 if (sampler.ms) {
3164 operands.push_back(spv::ImageOperandsSampleMask);
3165 operands.push_back(*opIt++);
3166 }
3167
3168 // Create the return type that was a special structure
3169 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003170 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003171 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3172 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3173
3174 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3175
3176 // Decode the return type
3177 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3178 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003179 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003180 // Process image atomic operations
3181
3182 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3183 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003184 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003185
John Kessenich8c8505c2016-07-26 12:50:38 -06003186 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003187 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003188
3189 std::vector<spv::Id> operands;
3190 operands.push_back(pointer);
3191 for (; opIt != arguments.end(); ++opIt)
3192 operands.push_back(*opIt);
3193
John Kessenich8c8505c2016-07-26 12:50:38 -06003194 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003195 }
3196 }
3197
3198 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003199 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003200 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3201
John Kessenichfc51d282015-08-19 13:34:18 -06003202 // check for bias argument
3203 bool bias = false;
Rex Xu71519fe2015-11-11 15:35:47 +08003204 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003205 int nonBiasArgCount = 2;
3206 if (cracked.offset)
3207 ++nonBiasArgCount;
3208 if (cracked.grad)
3209 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003210 if (cracked.lodClamp)
3211 ++nonBiasArgCount;
3212 if (sparse)
3213 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003214
3215 if ((int)arguments.size() > nonBiasArgCount)
3216 bias = true;
3217 }
3218
John Kessenicha5c33d62016-06-02 23:45:21 -06003219 // See if the sampler param should really be just the SPV image part
3220 if (cracked.fetch) {
3221 // a fetch needs to have the image extracted first
3222 if (builder.isSampledImage(params.sampler))
3223 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3224 }
3225
John Kessenichfc51d282015-08-19 13:34:18 -06003226 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003227
John Kessenichfc51d282015-08-19 13:34:18 -06003228 params.coords = arguments[1];
3229 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003230 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003231
3232 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003233 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003234 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003235 ++extraArgs;
3236 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003237 params.Dref = arguments[2];
3238 ++extraArgs;
3239 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003240 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003241 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003242 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003243 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003244 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003245 dRefComp = builder.getNumComponents(params.coords) - 1;
3246 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003247 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3248 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003249
3250 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003251 if (cracked.lod) {
3252 params.lod = arguments[2];
3253 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003254 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3255 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3256 noImplicitLod = true;
3257 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003258
3259 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003260 if (sampler.ms) {
Rex Xu6b86d492015-09-16 17:48:22 +08003261 params.sample = arguments[2]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003262 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003263 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003264
3265 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003266 if (cracked.grad) {
3267 params.gradX = arguments[2 + extraArgs];
3268 params.gradY = arguments[3 + extraArgs];
3269 extraArgs += 2;
3270 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003271
3272 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003273 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003274 params.offset = arguments[2 + extraArgs];
3275 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003276 } else if (cracked.offsets) {
3277 params.offsets = arguments[2 + extraArgs];
3278 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003279 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003280
3281 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003282 if (cracked.lodClamp) {
3283 params.lodClamp = arguments[2 + extraArgs];
3284 ++extraArgs;
3285 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003286
3287 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003288 if (sparse) {
3289 params.texelOut = arguments[2 + extraArgs];
3290 ++extraArgs;
3291 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003292
3293 // bias
John Kessenichfc51d282015-08-19 13:34:18 -06003294 if (bias) {
3295 params.bias = arguments[2 + extraArgs];
3296 ++extraArgs;
3297 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003298
3299 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003300 if (cracked.gather && ! sampler.shadow) {
3301 // default component is 0, if missing, otherwise an argument
3302 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003303 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003304 ++extraArgs;
3305 } else {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003306 params.component = builder.makeIntConstant(0);
John Kessenich55e7d112015-11-15 21:33:39 -07003307 }
3308 }
John Kessenichfc51d282015-08-19 13:34:18 -06003309
John Kessenich65336482016-06-16 14:06:26 -06003310 // projective component (might not to move)
3311 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3312 // are divided by the last component of P."
3313 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3314 // unused components will appear after all used components."
3315 if (cracked.proj) {
3316 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3317 int projTargetComp;
3318 switch (sampler.dim) {
3319 case glslang::Esd1D: projTargetComp = 1; break;
3320 case glslang::Esd2D: projTargetComp = 2; break;
3321 case glslang::EsdRect: projTargetComp = 2; break;
3322 default: projTargetComp = projSourceComp; break;
3323 }
3324 // copy the projective coordinate if we have to
3325 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003326 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003327 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3328 projSourceComp);
3329 params.coords = builder.createCompositeInsert(projComp, params.coords,
3330 builder.getTypeId(params.coords), projTargetComp);
3331 }
3332 }
3333
John Kessenich8c8505c2016-07-26 12:50:38 -06003334 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003335}
3336
3337spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3338{
3339 // Grab the function's pointer from the previously created function
3340 spv::Function* function = functionMap[node->getName().c_str()];
3341 if (! function)
3342 return 0;
3343
3344 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3345 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3346
3347 // See comments in makeFunctions() for details about the semantics for parameter passing.
3348 //
3349 // These imply we need a four step process:
3350 // 1. Evaluate the arguments
3351 // 2. Allocate and make copies of in, out, and inout arguments
3352 // 3. Make the call
3353 // 4. Copy back the results
3354
3355 // 1. Evaluate the arguments
3356 std::vector<spv::Builder::AccessChain> lValues;
3357 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003358 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003359 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003360 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003361 // build l-value
3362 builder.clearAccessChain();
3363 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003364 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003365 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
John Kessenich4a57dce2017-02-24 19:15:46 -07003366 if (qualifiers[a] != glslang::EvqConstReadOnly || paramType.containsOpaque()) {
John Kessenich140f3df2015-06-26 16:58:36 -06003367 // save l-value
3368 lValues.push_back(builder.getAccessChain());
3369 } else {
3370 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003371 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003372 }
3373 }
3374
3375 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3376 // copy the original into that space.
3377 //
3378 // Also, build up the list of actual arguments to pass in for the call
3379 int lValueCount = 0;
3380 int rValueCount = 0;
3381 std::vector<spv::Id> spvArgs;
3382 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003383 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003384 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003385 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003386 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3387 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003388 builder.setAccessChain(lValues[lValueCount]);
3389 arg = builder.accessChainGetLValue();
3390 ++lValueCount;
3391 } else if (qualifiers[a] != glslang::EvqConstReadOnly) {
John Kessenich140f3df2015-06-26 16:58:36 -06003392 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003393 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3394 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3395 // need to copy the input into output space
3396 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003397 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003398 builder.clearAccessChain();
3399 builder.setAccessChainLValue(arg);
3400 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003401 }
3402 ++lValueCount;
3403 } else {
3404 arg = rValues[rValueCount];
3405 ++rValueCount;
3406 }
3407 spvArgs.push_back(arg);
3408 }
3409
3410 // 3. Make the call.
3411 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003412 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003413
3414 // 4. Copy back out an "out" arguments.
3415 lValueCount = 0;
3416 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003417 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003418 if (qualifiers[a] != glslang::EvqConstReadOnly) {
3419 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3420 spv::Id copy = builder.createLoad(spvArgs[a]);
3421 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003422 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003423 }
3424 ++lValueCount;
3425 }
3426 }
3427
3428 return result;
3429}
3430
3431// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003432spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3433 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003434 spv::Id typeId, spv::Id left, spv::Id right,
3435 glslang::TBasicType typeProxy, bool reduceComparison)
3436{
Rex Xu8ff43de2016-04-22 16:51:45 +08003437 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003438#ifdef AMD_EXTENSIONS
3439 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3440#else
John Kessenich140f3df2015-06-26 16:58:36 -06003441 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003442#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003443 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003444
3445 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003446 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003447 bool comparison = false;
3448
3449 switch (op) {
3450 case glslang::EOpAdd:
3451 case glslang::EOpAddAssign:
3452 if (isFloat)
3453 binOp = spv::OpFAdd;
3454 else
3455 binOp = spv::OpIAdd;
3456 break;
3457 case glslang::EOpSub:
3458 case glslang::EOpSubAssign:
3459 if (isFloat)
3460 binOp = spv::OpFSub;
3461 else
3462 binOp = spv::OpISub;
3463 break;
3464 case glslang::EOpMul:
3465 case glslang::EOpMulAssign:
3466 if (isFloat)
3467 binOp = spv::OpFMul;
3468 else
3469 binOp = spv::OpIMul;
3470 break;
3471 case glslang::EOpVectorTimesScalar:
3472 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003473 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003474 if (builder.isVector(right))
3475 std::swap(left, right);
3476 assert(builder.isScalar(right));
3477 needMatchingVectors = false;
3478 binOp = spv::OpVectorTimesScalar;
3479 } else
3480 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003481 break;
3482 case glslang::EOpVectorTimesMatrix:
3483 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003484 binOp = spv::OpVectorTimesMatrix;
3485 break;
3486 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003487 binOp = spv::OpMatrixTimesVector;
3488 break;
3489 case glslang::EOpMatrixTimesScalar:
3490 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003491 binOp = spv::OpMatrixTimesScalar;
3492 break;
3493 case glslang::EOpMatrixTimesMatrix:
3494 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003495 binOp = spv::OpMatrixTimesMatrix;
3496 break;
3497 case glslang::EOpOuterProduct:
3498 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003499 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003500 break;
3501
3502 case glslang::EOpDiv:
3503 case glslang::EOpDivAssign:
3504 if (isFloat)
3505 binOp = spv::OpFDiv;
3506 else if (isUnsigned)
3507 binOp = spv::OpUDiv;
3508 else
3509 binOp = spv::OpSDiv;
3510 break;
3511 case glslang::EOpMod:
3512 case glslang::EOpModAssign:
3513 if (isFloat)
3514 binOp = spv::OpFMod;
3515 else if (isUnsigned)
3516 binOp = spv::OpUMod;
3517 else
3518 binOp = spv::OpSMod;
3519 break;
3520 case glslang::EOpRightShift:
3521 case glslang::EOpRightShiftAssign:
3522 if (isUnsigned)
3523 binOp = spv::OpShiftRightLogical;
3524 else
3525 binOp = spv::OpShiftRightArithmetic;
3526 break;
3527 case glslang::EOpLeftShift:
3528 case glslang::EOpLeftShiftAssign:
3529 binOp = spv::OpShiftLeftLogical;
3530 break;
3531 case glslang::EOpAnd:
3532 case glslang::EOpAndAssign:
3533 binOp = spv::OpBitwiseAnd;
3534 break;
3535 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003536 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003537 binOp = spv::OpLogicalAnd;
3538 break;
3539 case glslang::EOpInclusiveOr:
3540 case glslang::EOpInclusiveOrAssign:
3541 binOp = spv::OpBitwiseOr;
3542 break;
3543 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003544 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003545 binOp = spv::OpLogicalOr;
3546 break;
3547 case glslang::EOpExclusiveOr:
3548 case glslang::EOpExclusiveOrAssign:
3549 binOp = spv::OpBitwiseXor;
3550 break;
3551 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003552 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003553 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003554 break;
3555
3556 case glslang::EOpLessThan:
3557 case glslang::EOpGreaterThan:
3558 case glslang::EOpLessThanEqual:
3559 case glslang::EOpGreaterThanEqual:
3560 case glslang::EOpEqual:
3561 case glslang::EOpNotEqual:
3562 case glslang::EOpVectorEqual:
3563 case glslang::EOpVectorNotEqual:
3564 comparison = true;
3565 break;
3566 default:
3567 break;
3568 }
3569
John Kessenich7c1aa102015-10-15 13:29:11 -06003570 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003571 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003572 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003573 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003574 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003575
3576 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003577 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003578 builder.promoteScalar(precision, left, right);
3579
qining25262b32016-05-06 17:25:16 -04003580 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3581 addDecoration(result, noContraction);
3582 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003583 }
3584
3585 if (! comparison)
3586 return 0;
3587
John Kessenich7c1aa102015-10-15 13:29:11 -06003588 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003589
John Kessenich4583b612016-08-07 19:14:22 -06003590 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3591 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003592 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003593
3594 switch (op) {
3595 case glslang::EOpLessThan:
3596 if (isFloat)
3597 binOp = spv::OpFOrdLessThan;
3598 else if (isUnsigned)
3599 binOp = spv::OpULessThan;
3600 else
3601 binOp = spv::OpSLessThan;
3602 break;
3603 case glslang::EOpGreaterThan:
3604 if (isFloat)
3605 binOp = spv::OpFOrdGreaterThan;
3606 else if (isUnsigned)
3607 binOp = spv::OpUGreaterThan;
3608 else
3609 binOp = spv::OpSGreaterThan;
3610 break;
3611 case glslang::EOpLessThanEqual:
3612 if (isFloat)
3613 binOp = spv::OpFOrdLessThanEqual;
3614 else if (isUnsigned)
3615 binOp = spv::OpULessThanEqual;
3616 else
3617 binOp = spv::OpSLessThanEqual;
3618 break;
3619 case glslang::EOpGreaterThanEqual:
3620 if (isFloat)
3621 binOp = spv::OpFOrdGreaterThanEqual;
3622 else if (isUnsigned)
3623 binOp = spv::OpUGreaterThanEqual;
3624 else
3625 binOp = spv::OpSGreaterThanEqual;
3626 break;
3627 case glslang::EOpEqual:
3628 case glslang::EOpVectorEqual:
3629 if (isFloat)
3630 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003631 else if (isBool)
3632 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003633 else
3634 binOp = spv::OpIEqual;
3635 break;
3636 case glslang::EOpNotEqual:
3637 case glslang::EOpVectorNotEqual:
3638 if (isFloat)
3639 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003640 else if (isBool)
3641 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003642 else
3643 binOp = spv::OpINotEqual;
3644 break;
3645 default:
3646 break;
3647 }
3648
qining25262b32016-05-06 17:25:16 -04003649 if (binOp != spv::OpNop) {
3650 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3651 addDecoration(result, noContraction);
3652 return builder.setPrecision(result, precision);
3653 }
John Kessenich140f3df2015-06-26 16:58:36 -06003654
3655 return 0;
3656}
3657
John Kessenich04bb8a02015-12-12 12:28:14 -07003658//
3659// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3660// These can be any of:
3661//
3662// matrix * scalar
3663// scalar * matrix
3664// matrix * matrix linear algebraic
3665// matrix * vector
3666// vector * matrix
3667// matrix * matrix componentwise
3668// matrix op matrix op in {+, -, /}
3669// matrix op scalar op in {+, -, /}
3670// scalar op matrix op in {+, -, /}
3671//
qining25262b32016-05-06 17:25:16 -04003672spv::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 -07003673{
3674 bool firstClass = true;
3675
3676 // First, handle first-class matrix operations (* and matrix/scalar)
3677 switch (op) {
3678 case spv::OpFDiv:
3679 if (builder.isMatrix(left) && builder.isScalar(right)) {
3680 // turn matrix / scalar into a multiply...
3681 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3682 op = spv::OpMatrixTimesScalar;
3683 } else
3684 firstClass = false;
3685 break;
3686 case spv::OpMatrixTimesScalar:
3687 if (builder.isMatrix(right))
3688 std::swap(left, right);
3689 assert(builder.isScalar(right));
3690 break;
3691 case spv::OpVectorTimesMatrix:
3692 assert(builder.isVector(left));
3693 assert(builder.isMatrix(right));
3694 break;
3695 case spv::OpMatrixTimesVector:
3696 assert(builder.isMatrix(left));
3697 assert(builder.isVector(right));
3698 break;
3699 case spv::OpMatrixTimesMatrix:
3700 assert(builder.isMatrix(left));
3701 assert(builder.isMatrix(right));
3702 break;
3703 default:
3704 firstClass = false;
3705 break;
3706 }
3707
qining25262b32016-05-06 17:25:16 -04003708 if (firstClass) {
3709 spv::Id result = builder.createBinOp(op, typeId, left, right);
3710 addDecoration(result, noContraction);
3711 return builder.setPrecision(result, precision);
3712 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003713
LoopDawg592860c2016-06-09 08:57:35 -06003714 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003715 // The result type of all of them is the same type as the (a) matrix operand.
3716 // The algorithm is to:
3717 // - break the matrix(es) into vectors
3718 // - smear any scalar to a vector
3719 // - do vector operations
3720 // - make a matrix out the vector results
3721 switch (op) {
3722 case spv::OpFAdd:
3723 case spv::OpFSub:
3724 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003725 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003726 case spv::OpFMul:
3727 {
3728 // one time set up...
3729 bool leftMat = builder.isMatrix(left);
3730 bool rightMat = builder.isMatrix(right);
3731 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3732 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3733 spv::Id scalarType = builder.getScalarTypeId(typeId);
3734 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3735 std::vector<spv::Id> results;
3736 spv::Id smearVec = spv::NoResult;
3737 if (builder.isScalar(left))
3738 smearVec = builder.smearScalar(precision, left, vecType);
3739 else if (builder.isScalar(right))
3740 smearVec = builder.smearScalar(precision, right, vecType);
3741
3742 // do each vector op
3743 for (unsigned int c = 0; c < numCols; ++c) {
3744 std::vector<unsigned int> indexes;
3745 indexes.push_back(c);
3746 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3747 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003748 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3749 addDecoration(result, noContraction);
3750 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003751 }
3752
3753 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003754 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003755 }
3756 default:
3757 assert(0);
3758 return spv::NoResult;
3759 }
3760}
3761
qining25262b32016-05-06 17:25:16 -04003762spv::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 -06003763{
3764 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003765 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003766 int libCall = -1;
Rex Xu8ff43de2016-04-22 16:51:45 +08003767 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003768#ifdef AMD_EXTENSIONS
3769 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3770#else
Rex Xu04db3f52015-09-16 11:44:02 +08003771 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003772#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003773
3774 switch (op) {
3775 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003776 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003777 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003778 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003779 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07003780 } else
John Kessenich140f3df2015-06-26 16:58:36 -06003781 unaryOp = spv::OpSNegate;
3782 break;
3783
3784 case glslang::EOpLogicalNot:
3785 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06003786 unaryOp = spv::OpLogicalNot;
3787 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003788 case glslang::EOpBitwiseNot:
3789 unaryOp = spv::OpNot;
3790 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06003791
John Kessenich140f3df2015-06-26 16:58:36 -06003792 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06003793 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06003794 break;
3795 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06003796 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06003797 break;
3798 case glslang::EOpTranspose:
3799 unaryOp = spv::OpTranspose;
3800 break;
3801
3802 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06003803 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06003804 break;
3805 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06003806 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06003807 break;
3808 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003809 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06003810 break;
3811 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003812 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06003813 break;
3814 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003815 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06003816 break;
3817 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06003818 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06003819 break;
3820 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06003821 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06003822 break;
3823 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06003824 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06003825 break;
3826
3827 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003828 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003829 break;
3830 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003831 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003832 break;
3833 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003834 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003835 break;
3836 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003837 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06003838 break;
3839 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003840 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06003841 break;
3842 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06003843 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06003844 break;
3845
3846 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06003847 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06003848 break;
3849 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06003850 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06003851 break;
3852
3853 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06003854 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06003855 break;
3856 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06003857 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06003858 break;
3859 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003860 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06003861 break;
3862 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06003863 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06003864 break;
3865 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003866 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003867 break;
3868 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06003869 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06003870 break;
3871
3872 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06003873 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06003874 break;
3875 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06003876 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06003877 break;
3878 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06003879 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06003880 break;
3881 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06003882 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06003883 break;
3884 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06003885 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06003886 break;
3887 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06003888 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06003889 break;
3890
3891 case glslang::EOpIsNan:
3892 unaryOp = spv::OpIsNan;
3893 break;
3894 case glslang::EOpIsInf:
3895 unaryOp = spv::OpIsInf;
3896 break;
LoopDawg592860c2016-06-09 08:57:35 -06003897 case glslang::EOpIsFinite:
3898 unaryOp = spv::OpIsFinite;
3899 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003900
Rex Xucbc426e2015-12-15 16:03:10 +08003901 case glslang::EOpFloatBitsToInt:
3902 case glslang::EOpFloatBitsToUint:
3903 case glslang::EOpIntBitsToFloat:
3904 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08003905 case glslang::EOpDoubleBitsToInt64:
3906 case glslang::EOpDoubleBitsToUint64:
3907 case glslang::EOpInt64BitsToDouble:
3908 case glslang::EOpUint64BitsToDouble:
Rex Xucbc426e2015-12-15 16:03:10 +08003909 unaryOp = spv::OpBitcast;
3910 break;
3911
John Kessenich140f3df2015-06-26 16:58:36 -06003912 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003913 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003914 break;
3915 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003916 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003917 break;
3918 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003919 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003920 break;
3921 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003922 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003923 break;
3924 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003925 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003926 break;
3927 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06003928 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06003929 break;
John Kessenichfc51d282015-08-19 13:34:18 -06003930 case glslang::EOpPackSnorm4x8:
3931 libCall = spv::GLSLstd450PackSnorm4x8;
3932 break;
3933 case glslang::EOpUnpackSnorm4x8:
3934 libCall = spv::GLSLstd450UnpackSnorm4x8;
3935 break;
3936 case glslang::EOpPackUnorm4x8:
3937 libCall = spv::GLSLstd450PackUnorm4x8;
3938 break;
3939 case glslang::EOpUnpackUnorm4x8:
3940 libCall = spv::GLSLstd450UnpackUnorm4x8;
3941 break;
3942 case glslang::EOpPackDouble2x32:
3943 libCall = spv::GLSLstd450PackDouble2x32;
3944 break;
3945 case glslang::EOpUnpackDouble2x32:
3946 libCall = spv::GLSLstd450UnpackDouble2x32;
3947 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003948
Rex Xu8ff43de2016-04-22 16:51:45 +08003949 case glslang::EOpPackInt2x32:
3950 case glslang::EOpUnpackInt2x32:
3951 case glslang::EOpPackUint2x32:
3952 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08003953 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08003954 break;
3955
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003956#ifdef AMD_EXTENSIONS
3957 case glslang::EOpPackFloat2x16:
3958 case glslang::EOpUnpackFloat2x16:
3959 unaryOp = spv::OpBitcast;
3960 break;
3961#endif
3962
John Kessenich140f3df2015-06-26 16:58:36 -06003963 case glslang::EOpDPdx:
3964 unaryOp = spv::OpDPdx;
3965 break;
3966 case glslang::EOpDPdy:
3967 unaryOp = spv::OpDPdy;
3968 break;
3969 case glslang::EOpFwidth:
3970 unaryOp = spv::OpFwidth;
3971 break;
3972 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07003973 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003974 unaryOp = spv::OpDPdxFine;
3975 break;
3976 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07003977 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003978 unaryOp = spv::OpDPdyFine;
3979 break;
3980 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07003981 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003982 unaryOp = spv::OpFwidthFine;
3983 break;
3984 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003985 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003986 unaryOp = spv::OpDPdxCoarse;
3987 break;
3988 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003989 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003990 unaryOp = spv::OpDPdyCoarse;
3991 break;
3992 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07003993 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06003994 unaryOp = spv::OpFwidthCoarse;
3995 break;
Rex Xu7a26c172015-12-08 17:12:09 +08003996 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07003997 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08003998 libCall = spv::GLSLstd450InterpolateAtCentroid;
3999 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004000 case glslang::EOpAny:
4001 unaryOp = spv::OpAny;
4002 break;
4003 case glslang::EOpAll:
4004 unaryOp = spv::OpAll;
4005 break;
4006
4007 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004008 if (isFloat)
4009 libCall = spv::GLSLstd450FAbs;
4010 else
4011 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004012 break;
4013 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004014 if (isFloat)
4015 libCall = spv::GLSLstd450FSign;
4016 else
4017 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004018 break;
4019
John Kessenichfc51d282015-08-19 13:34:18 -06004020 case glslang::EOpAtomicCounterIncrement:
4021 case glslang::EOpAtomicCounterDecrement:
4022 case glslang::EOpAtomicCounter:
4023 {
4024 // Handle all of the atomics in one place, in createAtomicOperation()
4025 std::vector<spv::Id> operands;
4026 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004027 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004028 }
4029
John Kessenichfc51d282015-08-19 13:34:18 -06004030 case glslang::EOpBitFieldReverse:
4031 unaryOp = spv::OpBitReverse;
4032 break;
4033 case glslang::EOpBitCount:
4034 unaryOp = spv::OpBitCount;
4035 break;
4036 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004037 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004038 break;
4039 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004040 if (isUnsigned)
4041 libCall = spv::GLSLstd450FindUMsb;
4042 else
4043 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004044 break;
4045
Rex Xu574ab042016-04-14 16:53:07 +08004046 case glslang::EOpBallot:
4047 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004048 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004049 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004050 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004051#ifdef AMD_EXTENSIONS
4052 case glslang::EOpMinInvocations:
4053 case glslang::EOpMaxInvocations:
4054 case glslang::EOpAddInvocations:
4055 case glslang::EOpMinInvocationsNonUniform:
4056 case glslang::EOpMaxInvocationsNonUniform:
4057 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004058 case glslang::EOpMinInvocationsInclusiveScan:
4059 case glslang::EOpMaxInvocationsInclusiveScan:
4060 case glslang::EOpAddInvocationsInclusiveScan:
4061 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4062 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4063 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4064 case glslang::EOpMinInvocationsExclusiveScan:
4065 case glslang::EOpMaxInvocationsExclusiveScan:
4066 case glslang::EOpAddInvocationsExclusiveScan:
4067 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4068 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4069 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004070#endif
Rex Xu51596642016-09-21 18:56:12 +08004071 {
4072 std::vector<spv::Id> operands;
4073 operands.push_back(operand);
4074 return createInvocationsOperation(op, typeId, operands, typeProxy);
4075 }
Rex Xu9d93a232016-05-05 12:30:44 +08004076
4077#ifdef AMD_EXTENSIONS
4078 case glslang::EOpMbcnt:
4079 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4080 libCall = spv::MbcntAMD;
4081 break;
4082
4083 case glslang::EOpCubeFaceIndex:
4084 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4085 libCall = spv::CubeFaceIndexAMD;
4086 break;
4087
4088 case glslang::EOpCubeFaceCoord:
4089 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4090 libCall = spv::CubeFaceCoordAMD;
4091 break;
4092#endif
Rex Xu338b1852016-05-05 20:38:33 +08004093
John Kessenich140f3df2015-06-26 16:58:36 -06004094 default:
4095 return 0;
4096 }
4097
4098 spv::Id id;
4099 if (libCall >= 0) {
4100 std::vector<spv::Id> args;
4101 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004102 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004103 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004104 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004105 }
John Kessenich140f3df2015-06-26 16:58:36 -06004106
qining25262b32016-05-06 17:25:16 -04004107 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004108 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004109}
4110
John Kessenich7a53f762016-01-20 11:19:27 -07004111// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004112spv::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 -07004113{
4114 // Handle unary operations vector by vector.
4115 // The result type is the same type as the original type.
4116 // The algorithm is to:
4117 // - break the matrix into vectors
4118 // - apply the operation to each vector
4119 // - make a matrix out the vector results
4120
4121 // get the types sorted out
4122 int numCols = builder.getNumColumns(operand);
4123 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004124 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4125 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004126 std::vector<spv::Id> results;
4127
4128 // do each vector op
4129 for (int c = 0; c < numCols; ++c) {
4130 std::vector<unsigned int> indexes;
4131 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004132 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4133 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4134 addDecoration(destVec, noContraction);
4135 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004136 }
4137
4138 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004139 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004140}
4141
Rex Xu73e3ce72016-04-27 18:48:17 +08004142spv::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 -06004143{
4144 spv::Op convOp = spv::OpNop;
4145 spv::Id zero = 0;
4146 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004147 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004148
4149 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4150
4151 switch (op) {
4152 case glslang::EOpConvIntToBool:
4153 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004154 case glslang::EOpConvInt64ToBool:
4155 case glslang::EOpConvUint64ToBool:
4156 zero = (op == glslang::EOpConvInt64ToBool ||
4157 op == glslang::EOpConvUint64ToBool) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004158 zero = makeSmearedConstant(zero, vectorSize);
4159 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4160
4161 case glslang::EOpConvFloatToBool:
4162 zero = builder.makeFloatConstant(0.0F);
4163 zero = makeSmearedConstant(zero, vectorSize);
4164 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4165
4166 case glslang::EOpConvDoubleToBool:
4167 zero = builder.makeDoubleConstant(0.0);
4168 zero = makeSmearedConstant(zero, vectorSize);
4169 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4170
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004171#ifdef AMD_EXTENSIONS
4172 case glslang::EOpConvFloat16ToBool:
4173 zero = builder.makeFloat16Constant(0.0F);
4174 zero = makeSmearedConstant(zero, vectorSize);
4175 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4176#endif
4177
John Kessenich140f3df2015-06-26 16:58:36 -06004178 case glslang::EOpConvBoolToFloat:
4179 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004180 zero = builder.makeFloatConstant(0.0F);
4181 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004182 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004183
John Kessenich140f3df2015-06-26 16:58:36 -06004184 case glslang::EOpConvBoolToDouble:
4185 convOp = spv::OpSelect;
4186 zero = builder.makeDoubleConstant(0.0);
4187 one = builder.makeDoubleConstant(1.0);
4188 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004189
4190#ifdef AMD_EXTENSIONS
4191 case glslang::EOpConvBoolToFloat16:
4192 convOp = spv::OpSelect;
4193 zero = builder.makeFloat16Constant(0.0F);
4194 one = builder.makeFloat16Constant(1.0F);
4195 break;
4196#endif
4197
John Kessenich140f3df2015-06-26 16:58:36 -06004198 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004199 case glslang::EOpConvBoolToInt64:
4200 zero = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(0) : builder.makeIntConstant(0);
4201 one = (op == glslang::EOpConvBoolToInt64) ? builder.makeInt64Constant(1) : builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004202 convOp = spv::OpSelect;
4203 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004204
John Kessenich140f3df2015-06-26 16:58:36 -06004205 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004206 case glslang::EOpConvBoolToUint64:
4207 zero = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4208 one = (op == glslang::EOpConvBoolToUint64) ? builder.makeUint64Constant(1) : builder.makeUintConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06004209 convOp = spv::OpSelect;
4210 break;
4211
4212 case glslang::EOpConvIntToFloat:
4213 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004214 case glslang::EOpConvInt64ToFloat:
4215 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004216#ifdef AMD_EXTENSIONS
4217 case glslang::EOpConvIntToFloat16:
4218 case glslang::EOpConvInt64ToFloat16:
4219#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004220 convOp = spv::OpConvertSToF;
4221 break;
4222
4223 case glslang::EOpConvUintToFloat:
4224 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004225 case glslang::EOpConvUint64ToFloat:
4226 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004227#ifdef AMD_EXTENSIONS
4228 case glslang::EOpConvUintToFloat16:
4229 case glslang::EOpConvUint64ToFloat16:
4230#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004231 convOp = spv::OpConvertUToF;
4232 break;
4233
4234 case glslang::EOpConvDoubleToFloat:
4235 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004236#ifdef AMD_EXTENSIONS
4237 case glslang::EOpConvDoubleToFloat16:
4238 case glslang::EOpConvFloat16ToDouble:
4239 case glslang::EOpConvFloatToFloat16:
4240 case glslang::EOpConvFloat16ToFloat:
4241#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004242 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004243 if (builder.isMatrixType(destType))
4244 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004245 break;
4246
4247 case glslang::EOpConvFloatToInt:
4248 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004249 case glslang::EOpConvFloatToInt64:
4250 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004251#ifdef AMD_EXTENSIONS
4252 case glslang::EOpConvFloat16ToInt:
4253 case glslang::EOpConvFloat16ToInt64:
4254#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004255 convOp = spv::OpConvertFToS;
4256 break;
4257
4258 case glslang::EOpConvUintToInt:
4259 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004260 case glslang::EOpConvUint64ToInt64:
4261 case glslang::EOpConvInt64ToUint64:
qininge24aa5e2016-04-07 15:40:27 -04004262 if (builder.isInSpecConstCodeGenMode()) {
4263 // Build zero scalar or vector for OpIAdd.
Rex Xu64bcfdb2016-09-05 16:10:14 +08004264 zero = (op == glslang::EOpConvUint64ToInt64 ||
4265 op == glslang::EOpConvInt64ToUint64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
qining189b2032016-04-12 23:16:20 -04004266 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004267 // Use OpIAdd, instead of OpBitcast to do the conversion when
4268 // generating for OpSpecConstantOp instruction.
4269 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4270 }
4271 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004272 convOp = spv::OpBitcast;
4273 break;
4274
4275 case glslang::EOpConvFloatToUint:
4276 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004277 case glslang::EOpConvFloatToUint64:
4278 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004279#ifdef AMD_EXTENSIONS
4280 case glslang::EOpConvFloat16ToUint:
4281 case glslang::EOpConvFloat16ToUint64:
4282#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004283 convOp = spv::OpConvertFToU;
4284 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004285
4286 case glslang::EOpConvIntToInt64:
4287 case glslang::EOpConvInt64ToInt:
4288 convOp = spv::OpSConvert;
4289 break;
4290
4291 case glslang::EOpConvUintToUint64:
4292 case glslang::EOpConvUint64ToUint:
4293 convOp = spv::OpUConvert;
4294 break;
4295
4296 case glslang::EOpConvIntToUint64:
4297 case glslang::EOpConvInt64ToUint:
4298 case glslang::EOpConvUint64ToInt:
4299 case glslang::EOpConvUintToInt64:
4300 // OpSConvert/OpUConvert + OpBitCast
4301 switch (op) {
4302 case glslang::EOpConvIntToUint64:
4303 convOp = spv::OpSConvert;
4304 type = builder.makeIntType(64);
4305 break;
4306 case glslang::EOpConvInt64ToUint:
4307 convOp = spv::OpSConvert;
4308 type = builder.makeIntType(32);
4309 break;
4310 case glslang::EOpConvUint64ToInt:
4311 convOp = spv::OpUConvert;
4312 type = builder.makeUintType(32);
4313 break;
4314 case glslang::EOpConvUintToInt64:
4315 convOp = spv::OpUConvert;
4316 type = builder.makeUintType(64);
4317 break;
4318 default:
4319 assert(0);
4320 break;
4321 }
4322
4323 if (vectorSize > 0)
4324 type = builder.makeVectorType(type, vectorSize);
4325
4326 operand = builder.createUnaryOp(convOp, type, operand);
4327
4328 if (builder.isInSpecConstCodeGenMode()) {
4329 // Build zero scalar or vector for OpIAdd.
4330 zero = (op == glslang::EOpConvIntToUint64 ||
4331 op == glslang::EOpConvUintToInt64) ? builder.makeUint64Constant(0) : builder.makeUintConstant(0);
4332 zero = makeSmearedConstant(zero, vectorSize);
4333 // Use OpIAdd, instead of OpBitcast to do the conversion when
4334 // generating for OpSpecConstantOp instruction.
4335 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4336 }
4337 // For normal run-time conversion instruction, use OpBitcast.
4338 convOp = spv::OpBitcast;
4339 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004340 default:
4341 break;
4342 }
4343
4344 spv::Id result = 0;
4345 if (convOp == spv::OpNop)
4346 return result;
4347
4348 if (convOp == spv::OpSelect) {
4349 zero = makeSmearedConstant(zero, vectorSize);
4350 one = makeSmearedConstant(one, vectorSize);
4351 result = builder.createTriOp(convOp, destType, operand, one, zero);
4352 } else
4353 result = builder.createUnaryOp(convOp, destType, operand);
4354
John Kessenich32cfd492016-02-02 12:37:46 -07004355 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004356}
4357
4358spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4359{
4360 if (vectorSize == 0)
4361 return constant;
4362
4363 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4364 std::vector<spv::Id> components;
4365 for (int c = 0; c < vectorSize; ++c)
4366 components.push_back(constant);
4367 return builder.makeCompositeConstant(vectorTypeId, components);
4368}
4369
John Kessenich426394d2015-07-23 10:22:48 -06004370// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004371spv::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 -06004372{
4373 spv::Op opCode = spv::OpNop;
4374
4375 switch (op) {
4376 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004377 case glslang::EOpImageAtomicAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004378 opCode = spv::OpAtomicIAdd;
4379 break;
4380 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004381 case glslang::EOpImageAtomicMin:
Rex Xu04db3f52015-09-16 11:44:02 +08004382 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004383 break;
4384 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004385 case glslang::EOpImageAtomicMax:
Rex Xu04db3f52015-09-16 11:44:02 +08004386 opCode = typeProxy == glslang::EbtUint ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004387 break;
4388 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004389 case glslang::EOpImageAtomicAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004390 opCode = spv::OpAtomicAnd;
4391 break;
4392 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004393 case glslang::EOpImageAtomicOr:
John Kessenich426394d2015-07-23 10:22:48 -06004394 opCode = spv::OpAtomicOr;
4395 break;
4396 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004397 case glslang::EOpImageAtomicXor:
John Kessenich426394d2015-07-23 10:22:48 -06004398 opCode = spv::OpAtomicXor;
4399 break;
4400 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004401 case glslang::EOpImageAtomicExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004402 opCode = spv::OpAtomicExchange;
4403 break;
4404 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004405 case glslang::EOpImageAtomicCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004406 opCode = spv::OpAtomicCompareExchange;
4407 break;
4408 case glslang::EOpAtomicCounterIncrement:
4409 opCode = spv::OpAtomicIIncrement;
4410 break;
4411 case glslang::EOpAtomicCounterDecrement:
4412 opCode = spv::OpAtomicIDecrement;
4413 break;
4414 case glslang::EOpAtomicCounter:
4415 opCode = spv::OpAtomicLoad;
4416 break;
4417 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004418 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004419 break;
4420 }
4421
4422 // Sort out the operands
4423 // - mapping from glslang -> SPV
4424 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004425 // - compare-exchange swaps the value and comparator
4426 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004427 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4428 auto opIt = operands.begin(); // walk the glslang operands
4429 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004430 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4431 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4432 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004433 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4434 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004435 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004436 spvAtomicOperands.push_back(*(opIt + 1));
4437 spvAtomicOperands.push_back(*opIt);
4438 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004439 }
John Kessenich426394d2015-07-23 10:22:48 -06004440
John Kessenich3e60a6f2015-09-14 22:45:16 -06004441 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004442 for (; opIt != operands.end(); ++opIt)
4443 spvAtomicOperands.push_back(*opIt);
4444
4445 return builder.createOp(opCode, typeId, spvAtomicOperands);
4446}
4447
John Kessenich91cef522016-05-05 16:45:40 -06004448// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004449spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004450{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004451#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004452 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004453 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004454#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004455
Rex Xu51596642016-09-21 18:56:12 +08004456 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004457 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004458 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4459
chaocf200da82016-12-20 12:44:35 -08004460 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4461 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004462 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4463 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004464 } else if (op == glslang::EOpAnyInvocation ||
4465 op == glslang::EOpAllInvocations ||
4466 op == glslang::EOpAllInvocationsEqual) {
4467 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4468 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004469 } else {
4470 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004471#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004472 if (op == glslang::EOpMinInvocationsNonUniform ||
4473 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004474 op == glslang::EOpAddInvocationsNonUniform ||
4475 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4476 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4477 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4478 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4479 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4480 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004481 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004482#endif
Rex Xu51596642016-09-21 18:56:12 +08004483
4484 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004485#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004486 switch (op) {
4487 case glslang::EOpMinInvocations:
4488 case glslang::EOpMaxInvocations:
4489 case glslang::EOpAddInvocations:
4490 case glslang::EOpMinInvocationsNonUniform:
4491 case glslang::EOpMaxInvocationsNonUniform:
4492 case glslang::EOpAddInvocationsNonUniform:
4493 groupOperation = spv::GroupOperationReduce;
4494 spvGroupOperands.push_back(groupOperation);
4495 break;
4496 case glslang::EOpMinInvocationsInclusiveScan:
4497 case glslang::EOpMaxInvocationsInclusiveScan:
4498 case glslang::EOpAddInvocationsInclusiveScan:
4499 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4500 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4501 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4502 groupOperation = spv::GroupOperationInclusiveScan;
4503 spvGroupOperands.push_back(groupOperation);
4504 break;
4505 case glslang::EOpMinInvocationsExclusiveScan:
4506 case glslang::EOpMaxInvocationsExclusiveScan:
4507 case glslang::EOpAddInvocationsExclusiveScan:
4508 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4509 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4510 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4511 groupOperation = spv::GroupOperationExclusiveScan;
4512 spvGroupOperands.push_back(groupOperation);
4513 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004514 default:
4515 break;
Rex Xu430ef402016-10-14 17:22:23 +08004516 }
Rex Xu9d93a232016-05-05 12:30:44 +08004517#endif
Rex Xu51596642016-09-21 18:56:12 +08004518 }
4519
4520 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4521 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004522
4523 switch (op) {
4524 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004525 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004526 break;
John Kessenich91cef522016-05-05 16:45:40 -06004527 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004528 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004529 break;
John Kessenich91cef522016-05-05 16:45:40 -06004530 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004531 opCode = spv::OpSubgroupAllEqualKHR;
4532 break;
Rex Xu51596642016-09-21 18:56:12 +08004533 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004534 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004535 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004536 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004537 break;
4538 case glslang::EOpReadFirstInvocation:
4539 opCode = spv::OpSubgroupFirstInvocationKHR;
4540 break;
4541 case glslang::EOpBallot:
4542 {
4543 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4544 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4545 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4546 //
4547 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4548 //
4549 spv::Id uintType = builder.makeUintType(32);
4550 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4551 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4552
4553 std::vector<spv::Id> components;
4554 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4555 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4556
4557 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4558 return builder.createUnaryOp(spv::OpBitcast, typeId,
4559 builder.createCompositeConstruct(uvec2Type, components));
4560 }
4561
Rex Xu9d93a232016-05-05 12:30:44 +08004562#ifdef AMD_EXTENSIONS
4563 case glslang::EOpMinInvocations:
4564 case glslang::EOpMaxInvocations:
4565 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004566 case glslang::EOpMinInvocationsInclusiveScan:
4567 case glslang::EOpMaxInvocationsInclusiveScan:
4568 case glslang::EOpAddInvocationsInclusiveScan:
4569 case glslang::EOpMinInvocationsExclusiveScan:
4570 case glslang::EOpMaxInvocationsExclusiveScan:
4571 case glslang::EOpAddInvocationsExclusiveScan:
4572 if (op == glslang::EOpMinInvocations ||
4573 op == glslang::EOpMinInvocationsInclusiveScan ||
4574 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004575 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004576 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004577 else {
4578 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004579 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004580 else
Rex Xu51596642016-09-21 18:56:12 +08004581 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004582 }
Rex Xu430ef402016-10-14 17:22:23 +08004583 } else if (op == glslang::EOpMaxInvocations ||
4584 op == glslang::EOpMaxInvocationsInclusiveScan ||
4585 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004586 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004587 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004588 else {
4589 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004590 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004591 else
Rex Xu51596642016-09-21 18:56:12 +08004592 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004593 }
4594 } else {
4595 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004596 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004597 else
Rex Xu51596642016-09-21 18:56:12 +08004598 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004599 }
4600
Rex Xu2bbbe062016-08-23 15:41:05 +08004601 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004602 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004603
4604 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004605 case glslang::EOpMinInvocationsNonUniform:
4606 case glslang::EOpMaxInvocationsNonUniform:
4607 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004608 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4609 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4610 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4611 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4612 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4613 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4614 if (op == glslang::EOpMinInvocationsNonUniform ||
4615 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4616 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004617 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004618 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004619 else {
4620 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004621 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004622 else
Rex Xu51596642016-09-21 18:56:12 +08004623 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004624 }
4625 }
Rex Xu430ef402016-10-14 17:22:23 +08004626 else if (op == glslang::EOpMaxInvocationsNonUniform ||
4627 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4628 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004629 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004630 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004631 else {
4632 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004633 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004634 else
Rex Xu51596642016-09-21 18:56:12 +08004635 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004636 }
4637 }
4638 else {
4639 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004640 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004641 else
Rex Xu51596642016-09-21 18:56:12 +08004642 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004643 }
4644
Rex Xu2bbbe062016-08-23 15:41:05 +08004645 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004646 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004647
4648 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004649#endif
John Kessenich91cef522016-05-05 16:45:40 -06004650 default:
4651 logger->missingFunctionality("invocation operation");
4652 return spv::NoResult;
4653 }
Rex Xu51596642016-09-21 18:56:12 +08004654
4655 assert(opCode != spv::OpNop);
4656 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06004657}
4658
Rex Xu2bbbe062016-08-23 15:41:05 +08004659// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08004660spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08004661{
Rex Xub7072052016-09-26 15:53:40 +08004662#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08004663 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4664 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08004665 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08004666 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08004667 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
4668 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
4669 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08004670#else
4671 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
4672 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08004673 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
4674 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08004675#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08004676
4677 // Handle group invocation operations scalar by scalar.
4678 // The result type is the same type as the original type.
4679 // The algorithm is to:
4680 // - break the vector into scalars
4681 // - apply the operation to each scalar
4682 // - make a vector out the scalar results
4683
4684 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08004685 int numComponents = builder.getNumComponents(operands[0]);
4686 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08004687 std::vector<spv::Id> results;
4688
4689 // do each scalar op
4690 for (int comp = 0; comp < numComponents; ++comp) {
4691 std::vector<unsigned int> indexes;
4692 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08004693 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08004694 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08004695 if (op == spv::OpSubgroupReadInvocationKHR) {
4696 spvGroupOperands.push_back(scalar);
4697 spvGroupOperands.push_back(operands[1]);
4698 } else if (op == spv::OpGroupBroadcast) {
4699 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08004700 spvGroupOperands.push_back(scalar);
4701 spvGroupOperands.push_back(operands[1]);
4702 } else {
chaocf200da82016-12-20 12:44:35 -08004703 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08004704 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08004705 spvGroupOperands.push_back(scalar);
4706 }
Rex Xu2bbbe062016-08-23 15:41:05 +08004707
Rex Xub7072052016-09-26 15:53:40 +08004708 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08004709 }
4710
4711 // put the pieces together
4712 return builder.createCompositeConstruct(typeId, results);
4713}
Rex Xu2bbbe062016-08-23 15:41:05 +08004714
John Kessenich5e4b1242015-08-06 22:53:06 -06004715spv::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 -06004716{
Rex Xu8ff43de2016-04-22 16:51:45 +08004717 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004718#ifdef AMD_EXTENSIONS
4719 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
4720#else
John Kessenich5e4b1242015-08-06 22:53:06 -06004721 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004722#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06004723
John Kessenich140f3df2015-06-26 16:58:36 -06004724 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08004725 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06004726 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05004727 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07004728 spv::Id typeId0 = 0;
4729 if (consumedOperands > 0)
4730 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08004731 spv::Id typeId1 = 0;
4732 if (consumedOperands > 1)
4733 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07004734 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004735
4736 switch (op) {
4737 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004738 if (isFloat)
4739 libCall = spv::GLSLstd450FMin;
4740 else if (isUnsigned)
4741 libCall = spv::GLSLstd450UMin;
4742 else
4743 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004744 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004745 break;
4746 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06004747 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06004748 break;
4749 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06004750 if (isFloat)
4751 libCall = spv::GLSLstd450FMax;
4752 else if (isUnsigned)
4753 libCall = spv::GLSLstd450UMax;
4754 else
4755 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004756 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004757 break;
4758 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06004759 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06004760 break;
4761 case glslang::EOpDot:
4762 opCode = spv::OpDot;
4763 break;
4764 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004765 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06004766 break;
4767
4768 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004769 if (isFloat)
4770 libCall = spv::GLSLstd450FClamp;
4771 else if (isUnsigned)
4772 libCall = spv::GLSLstd450UClamp;
4773 else
4774 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004775 builder.promoteScalar(precision, operands.front(), operands[1]);
4776 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004777 break;
4778 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08004779 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
4780 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07004781 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08004782 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07004783 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08004784 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07004785 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07004786 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004787 break;
4788 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004789 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004790 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06004791 break;
4792 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06004793 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07004794 builder.promoteScalar(precision, operands[0], operands[2]);
4795 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06004796 break;
4797
4798 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06004799 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06004800 break;
4801 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06004802 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06004803 break;
4804 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06004805 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06004806 break;
4807 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06004808 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06004809 break;
4810 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004811 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06004812 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004813 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07004814 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004815 libCall = spv::GLSLstd450InterpolateAtSample;
4816 break;
4817 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07004818 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004819 libCall = spv::GLSLstd450InterpolateAtOffset;
4820 break;
John Kessenich55e7d112015-11-15 21:33:39 -07004821 case glslang::EOpAddCarry:
4822 opCode = spv::OpIAddCarry;
4823 typeId = builder.makeStructResultType(typeId0, typeId0);
4824 consumedOperands = 2;
4825 break;
4826 case glslang::EOpSubBorrow:
4827 opCode = spv::OpISubBorrow;
4828 typeId = builder.makeStructResultType(typeId0, typeId0);
4829 consumedOperands = 2;
4830 break;
4831 case glslang::EOpUMulExtended:
4832 opCode = spv::OpUMulExtended;
4833 typeId = builder.makeStructResultType(typeId0, typeId0);
4834 consumedOperands = 2;
4835 break;
4836 case glslang::EOpIMulExtended:
4837 opCode = spv::OpSMulExtended;
4838 typeId = builder.makeStructResultType(typeId0, typeId0);
4839 consumedOperands = 2;
4840 break;
4841 case glslang::EOpBitfieldExtract:
4842 if (isUnsigned)
4843 opCode = spv::OpBitFieldUExtract;
4844 else
4845 opCode = spv::OpBitFieldSExtract;
4846 break;
4847 case glslang::EOpBitfieldInsert:
4848 opCode = spv::OpBitFieldInsert;
4849 break;
4850
4851 case glslang::EOpFma:
4852 libCall = spv::GLSLstd450Fma;
4853 break;
4854 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004855 {
4856 libCall = spv::GLSLstd450FrexpStruct;
4857 assert(builder.isPointerType(typeId1));
4858 typeId1 = builder.getContainedTypeId(typeId1);
4859#ifdef AMD_EXTENSIONS
4860 int width = builder.getScalarTypeWidth(typeId1);
4861#else
4862 int width = 32;
4863#endif
4864 if (builder.getNumComponents(operands[0]) == 1)
4865 frexpIntType = builder.makeIntegerType(width, true);
4866 else
4867 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
4868 typeId = builder.makeStructResultType(typeId0, frexpIntType);
4869 consumedOperands = 1;
4870 }
John Kessenich55e7d112015-11-15 21:33:39 -07004871 break;
4872 case glslang::EOpLdexp:
4873 libCall = spv::GLSLstd450Ldexp;
4874 break;
4875
Rex Xu574ab042016-04-14 16:53:07 +08004876 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08004877 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08004878
Rex Xu9d93a232016-05-05 12:30:44 +08004879#ifdef AMD_EXTENSIONS
4880 case glslang::EOpSwizzleInvocations:
4881 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4882 libCall = spv::SwizzleInvocationsAMD;
4883 break;
4884 case glslang::EOpSwizzleInvocationsMasked:
4885 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4886 libCall = spv::SwizzleInvocationsMaskedAMD;
4887 break;
4888 case glslang::EOpWriteInvocation:
4889 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4890 libCall = spv::WriteInvocationAMD;
4891 break;
4892
4893 case glslang::EOpMin3:
4894 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4895 if (isFloat)
4896 libCall = spv::FMin3AMD;
4897 else {
4898 if (isUnsigned)
4899 libCall = spv::UMin3AMD;
4900 else
4901 libCall = spv::SMin3AMD;
4902 }
4903 break;
4904 case glslang::EOpMax3:
4905 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4906 if (isFloat)
4907 libCall = spv::FMax3AMD;
4908 else {
4909 if (isUnsigned)
4910 libCall = spv::UMax3AMD;
4911 else
4912 libCall = spv::SMax3AMD;
4913 }
4914 break;
4915 case glslang::EOpMid3:
4916 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
4917 if (isFloat)
4918 libCall = spv::FMid3AMD;
4919 else {
4920 if (isUnsigned)
4921 libCall = spv::UMid3AMD;
4922 else
4923 libCall = spv::SMid3AMD;
4924 }
4925 break;
4926
4927 case glslang::EOpInterpolateAtVertex:
4928 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
4929 libCall = spv::InterpolateAtVertexAMD;
4930 break;
4931#endif
4932
John Kessenich140f3df2015-06-26 16:58:36 -06004933 default:
4934 return 0;
4935 }
4936
4937 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07004938 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05004939 // Use an extended instruction from the standard library.
4940 // Construct the call arguments, without modifying the original operands vector.
4941 // We might need the remaining arguments, e.g. in the EOpFrexp case.
4942 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08004943 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07004944 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07004945 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06004946 case 0:
4947 // should all be handled by visitAggregate and createNoArgOperation
4948 assert(0);
4949 return 0;
4950 case 1:
4951 // should all be handled by createUnaryOperation
4952 assert(0);
4953 return 0;
4954 case 2:
4955 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
4956 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004957 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004958 // anything 3 or over doesn't have l-value operands, so all should be consumed
4959 assert(consumedOperands == operands.size());
4960 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06004961 break;
4962 }
4963 }
4964
John Kessenich55e7d112015-11-15 21:33:39 -07004965 // Decode the return types that were structures
4966 switch (op) {
4967 case glslang::EOpAddCarry:
4968 case glslang::EOpSubBorrow:
4969 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4970 id = builder.createCompositeExtract(id, typeId0, 0);
4971 break;
4972 case glslang::EOpUMulExtended:
4973 case glslang::EOpIMulExtended:
4974 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
4975 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
4976 break;
4977 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08004978 {
4979 assert(operands.size() == 2);
4980 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
4981 // "exp" is floating-point type (from HLSL intrinsic)
4982 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
4983 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
4984 builder.createStore(member1, operands[1]);
4985 } else
4986 // "exp" is integer type (from GLSL built-in function)
4987 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
4988 id = builder.createCompositeExtract(id, typeId0, 0);
4989 }
John Kessenich55e7d112015-11-15 21:33:39 -07004990 break;
4991 default:
4992 break;
4993 }
4994
John Kessenich32cfd492016-02-02 12:37:46 -07004995 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004996}
4997
Rex Xu9d93a232016-05-05 12:30:44 +08004998// Intrinsics with no arguments (or no return value, and no precision).
4999spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005000{
5001 // TODO: get the barrier operands correct
5002
5003 switch (op) {
5004 case glslang::EOpEmitVertex:
5005 builder.createNoResultOp(spv::OpEmitVertex);
5006 return 0;
5007 case glslang::EOpEndPrimitive:
5008 builder.createNoResultOp(spv::OpEndPrimitive);
5009 return 0;
5010 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005011 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005012 return 0;
5013 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005014 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005015 return 0;
5016 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005017 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005018 return 0;
5019 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005020 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005021 return 0;
5022 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005023 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005024 return 0;
5025 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005026 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005027 return 0;
5028 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005029 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005030 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005031 case glslang::EOpAllMemoryBarrierWithGroupSync:
5032 // Control barrier with non-"None" semantic is also a memory barrier.
5033 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5034 return 0;
5035 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5036 // Control barrier with non-"None" semantic is also a memory barrier.
5037 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5038 return 0;
5039 case glslang::EOpWorkgroupMemoryBarrier:
5040 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5041 return 0;
5042 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5043 // Control barrier with non-"None" semantic is also a memory barrier.
5044 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5045 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005046#ifdef AMD_EXTENSIONS
5047 case glslang::EOpTime:
5048 {
5049 std::vector<spv::Id> args; // Dummy arguments
5050 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5051 return builder.setPrecision(id, precision);
5052 }
5053#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005054 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005055 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005056 return 0;
5057 }
5058}
5059
5060spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5061{
John Kessenich2f273362015-07-18 22:34:27 -06005062 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005063 spv::Id id;
5064 if (symbolValues.end() != iter) {
5065 id = iter->second;
5066 return id;
5067 }
5068
5069 // it was not found, create it
5070 id = createSpvVariable(symbol);
5071 symbolValues[symbol->getId()] = id;
5072
Rex Xuc884b4a2016-06-29 15:03:44 +08005073 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005074 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005075 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005076 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005077 if (symbol->getType().getQualifier().hasSpecConstantId())
5078 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005079 if (symbol->getQualifier().hasIndex())
5080 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5081 if (symbol->getQualifier().hasComponent())
5082 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5083 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005084 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005085 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005086 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005087 if (symbol->getQualifier().hasXfbBuffer())
5088 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5089 if (symbol->getQualifier().hasXfbOffset())
5090 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5091 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005092 // atomic counters use this:
5093 if (symbol->getQualifier().hasOffset())
5094 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005095 }
5096
scygan2c864272016-05-18 18:09:17 +02005097 if (symbol->getQualifier().hasLocation())
5098 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005099 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005100 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005101 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005102 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005103 }
John Kessenich140f3df2015-06-26 16:58:36 -06005104 if (symbol->getQualifier().hasSet())
5105 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005106 else if (IsDescriptorResource(symbol->getType())) {
5107 // default to 0
5108 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5109 }
John Kessenich140f3df2015-06-26 16:58:36 -06005110 if (symbol->getQualifier().hasBinding())
5111 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005112 if (symbol->getQualifier().hasAttachment())
5113 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005114 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005115 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005116 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005117 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005118 if (symbol->getQualifier().hasXfbBuffer())
5119 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5120 }
5121
Rex Xu1da878f2016-02-21 20:59:01 +08005122 if (symbol->getType().isImage()) {
5123 std::vector<spv::Decoration> memory;
5124 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5125 for (unsigned int i = 0; i < memory.size(); ++i)
5126 addDecoration(id, memory[i]);
5127 }
5128
John Kessenich140f3df2015-06-26 16:58:36 -06005129 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005130 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005131 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005132 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005133
John Kessenichecba76f2017-01-06 00:34:48 -07005134#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005135 if (builtIn == spv::BuiltInSampleMask) {
5136 spv::Decoration decoration;
5137 // GL_NV_sample_mask_override_coverage extension
5138 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005139 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005140 else
5141 decoration = (spv::Decoration)spv::DecorationMax;
5142 addDecoration(id, decoration);
5143 if (decoration != spv::DecorationMax) {
5144 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5145 }
5146 }
chaoc771d89f2017-01-13 01:10:53 -08005147 else if (builtIn == spv::BuiltInLayer) {
5148 // SPV_NV_viewport_array2 extension
5149 if (symbol->getQualifier().layoutViewportRelative)
5150 {
5151 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5152 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5153 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5154 }
5155 if(symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048)
5156 {
5157 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5158 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5159 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5160 }
5161 }
5162
chaoc6e5acae2016-12-20 13:28:52 -08005163 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005164 addDecoration(id, spv::DecorationPassthroughNV);
5165 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005166 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5167 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005168#endif
5169
John Kessenich140f3df2015-06-26 16:58:36 -06005170 return id;
5171}
5172
John Kessenich55e7d112015-11-15 21:33:39 -07005173// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005174void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5175{
John Kessenich4016e382016-07-15 11:53:56 -06005176 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005177 builder.addDecoration(id, dec);
5178}
5179
John Kessenich55e7d112015-11-15 21:33:39 -07005180// If 'dec' is valid, add a one-operand decoration to an object
5181void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5182{
John Kessenich4016e382016-07-15 11:53:56 -06005183 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005184 builder.addDecoration(id, dec, value);
5185}
5186
5187// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005188void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5189{
John Kessenich4016e382016-07-15 11:53:56 -06005190 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005191 builder.addMemberDecoration(id, (unsigned)member, dec);
5192}
5193
John Kessenich92187592016-02-01 13:45:25 -07005194// If 'dec' is valid, add a one-operand decoration to a struct member
5195void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5196{
John Kessenich4016e382016-07-15 11:53:56 -06005197 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005198 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5199}
5200
John Kessenich55e7d112015-11-15 21:33:39 -07005201// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005202// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005203//
5204// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5205//
5206// Recursively walk the nodes. The nodes form a tree whose leaves are
5207// regular constants, which themselves are trees that createSpvConstant()
5208// recursively walks. So, this function walks the "top" of the tree:
5209// - emit specialization constant-building instructions for specConstant
5210// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005211spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005212{
John Kessenich7cc0e282016-03-20 00:46:02 -06005213 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005214
qining4f4bb812016-04-03 23:55:17 -04005215 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005216 if (! node.getQualifier().specConstant) {
5217 // hand off to the non-spec-constant path
5218 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5219 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005220 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005221 nextConst, false);
5222 }
5223
5224 // We now know we have a specialization constant to build
5225
John Kessenichd94c0032016-05-30 19:29:40 -06005226 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005227 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5228 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5229 std::vector<spv::Id> dimConstId;
5230 for (int dim = 0; dim < 3; ++dim) {
5231 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5232 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5233 if (specConst)
5234 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5235 }
5236 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5237 }
5238
5239 // An AST node labelled as specialization constant should be a symbol node.
5240 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5241 if (auto* sn = node.getAsSymbolNode()) {
5242 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005243 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5244 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5245 // will set the builder into spec constant op instruction generating mode.
5246 sub_tree->traverse(this);
5247 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005248 } else if (auto* const_union_array = &sn->getConstArray()){
5249 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005250 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5251 builder.addName(id, sn->getName().c_str());
5252 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005253 }
5254 }
qining4f4bb812016-04-03 23:55:17 -04005255
5256 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5257 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005258 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005259 exit(1);
5260 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005261}
5262
John Kessenich140f3df2015-06-26 16:58:36 -06005263// Use 'consts' as the flattened glslang source of scalar constants to recursively
5264// build the aggregate SPIR-V constant.
5265//
5266// If there are not enough elements present in 'consts', 0 will be substituted;
5267// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5268//
qining08408382016-03-21 09:51:37 -04005269spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005270{
5271 // vector of constants for SPIR-V
5272 std::vector<spv::Id> spvConsts;
5273
5274 // Type is used for struct and array constants
5275 spv::Id typeId = convertGlslangToSpvType(glslangType);
5276
5277 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005278 glslang::TType elementType(glslangType, 0);
5279 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005280 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005281 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005282 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005283 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005284 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005285 } else if (glslangType.getStruct()) {
5286 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5287 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005288 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005289 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005290 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5291 bool zero = nextConst >= consts.size();
5292 switch (glslangType.getBasicType()) {
5293 case glslang::EbtInt:
5294 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5295 break;
5296 case glslang::EbtUint:
5297 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5298 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005299 case glslang::EbtInt64:
5300 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5301 break;
5302 case glslang::EbtUint64:
5303 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5304 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005305 case glslang::EbtFloat:
5306 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5307 break;
5308 case glslang::EbtDouble:
5309 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5310 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005311#ifdef AMD_EXTENSIONS
5312 case glslang::EbtFloat16:
5313 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5314 break;
5315#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005316 case glslang::EbtBool:
5317 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5318 break;
5319 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005320 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005321 break;
5322 }
5323 ++nextConst;
5324 }
5325 } else {
5326 // we have a non-aggregate (scalar) constant
5327 bool zero = nextConst >= consts.size();
5328 spv::Id scalar = 0;
5329 switch (glslangType.getBasicType()) {
5330 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005331 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005332 break;
5333 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005334 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005335 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005336 case glslang::EbtInt64:
5337 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5338 break;
5339 case glslang::EbtUint64:
5340 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5341 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005342 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005343 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005344 break;
5345 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005346 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005347 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005348#ifdef AMD_EXTENSIONS
5349 case glslang::EbtFloat16:
5350 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5351 break;
5352#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005353 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005354 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005355 break;
5356 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005357 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005358 break;
5359 }
5360 ++nextConst;
5361 return scalar;
5362 }
5363
5364 return builder.makeCompositeConstant(typeId, spvConsts);
5365}
5366
John Kessenich7c1aa102015-10-15 13:29:11 -06005367// Return true if the node is a constant or symbol whose reading has no
5368// non-trivial observable cost or effect.
5369bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5370{
5371 // don't know what this is
5372 if (node == nullptr)
5373 return false;
5374
5375 // a constant is safe
5376 if (node->getAsConstantUnion() != nullptr)
5377 return true;
5378
5379 // not a symbol means non-trivial
5380 if (node->getAsSymbolNode() == nullptr)
5381 return false;
5382
5383 // a symbol, depends on what's being read
5384 switch (node->getType().getQualifier().storage) {
5385 case glslang::EvqTemporary:
5386 case glslang::EvqGlobal:
5387 case glslang::EvqIn:
5388 case glslang::EvqInOut:
5389 case glslang::EvqConst:
5390 case glslang::EvqConstReadOnly:
5391 case glslang::EvqUniform:
5392 return true;
5393 default:
5394 return false;
5395 }
qining25262b32016-05-06 17:25:16 -04005396}
John Kessenich7c1aa102015-10-15 13:29:11 -06005397
5398// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005399// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005400// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005401// Return true if trivial.
5402bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5403{
5404 if (node == nullptr)
5405 return false;
5406
John Kessenich84cc15f2017-05-24 16:44:47 -06005407 // count non scalars as trivial, as well as anything coming from HLSL
5408 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005409 return true;
5410
John Kessenich7c1aa102015-10-15 13:29:11 -06005411 // symbols and constants are trivial
5412 if (isTrivialLeaf(node))
5413 return true;
5414
5415 // otherwise, it needs to be a simple operation or one or two leaf nodes
5416
5417 // not a simple operation
5418 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5419 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5420 if (binaryNode == nullptr && unaryNode == nullptr)
5421 return false;
5422
5423 // not on leaf nodes
5424 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5425 return false;
5426
5427 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5428 return false;
5429 }
5430
5431 switch (node->getAsOperator()->getOp()) {
5432 case glslang::EOpLogicalNot:
5433 case glslang::EOpConvIntToBool:
5434 case glslang::EOpConvUintToBool:
5435 case glslang::EOpConvFloatToBool:
5436 case glslang::EOpConvDoubleToBool:
5437 case glslang::EOpEqual:
5438 case glslang::EOpNotEqual:
5439 case glslang::EOpLessThan:
5440 case glslang::EOpGreaterThan:
5441 case glslang::EOpLessThanEqual:
5442 case glslang::EOpGreaterThanEqual:
5443 case glslang::EOpIndexDirect:
5444 case glslang::EOpIndexDirectStruct:
5445 case glslang::EOpLogicalXor:
5446 case glslang::EOpAny:
5447 case glslang::EOpAll:
5448 return true;
5449 default:
5450 return false;
5451 }
5452}
5453
5454// Emit short-circuiting code, where 'right' is never evaluated unless
5455// the left side is true (for &&) or false (for ||).
5456spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5457{
5458 spv::Id boolTypeId = builder.makeBoolType();
5459
5460 // emit left operand
5461 builder.clearAccessChain();
5462 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005463 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005464
5465 // Operands to accumulate OpPhi operands
5466 std::vector<spv::Id> phiOperands;
5467 // accumulate left operand's phi information
5468 phiOperands.push_back(leftId);
5469 phiOperands.push_back(builder.getBuildPoint()->getId());
5470
5471 // Make the two kinds of operation symmetric with a "!"
5472 // || => emit "if (! left) result = right"
5473 // && => emit "if ( left) result = right"
5474 //
5475 // TODO: this runtime "not" for || could be avoided by adding functionality
5476 // to 'builder' to have an "else" without an "then"
5477 if (op == glslang::EOpLogicalOr)
5478 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5479
5480 // make an "if" based on the left value
5481 spv::Builder::If ifBuilder(leftId, builder);
5482
5483 // emit right operand as the "then" part of the "if"
5484 builder.clearAccessChain();
5485 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005486 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005487
5488 // accumulate left operand's phi information
5489 phiOperands.push_back(rightId);
5490 phiOperands.push_back(builder.getBuildPoint()->getId());
5491
5492 // finish the "if"
5493 ifBuilder.makeEndIf();
5494
5495 // phi together the two results
5496 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5497}
5498
Rex Xu9d93a232016-05-05 12:30:44 +08005499// Return type Id of the imported set of extended instructions corresponds to the name.
5500// Import this set if it has not been imported yet.
5501spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5502{
5503 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5504 return extBuiltinMap[name];
5505 else {
Rex Xu51596642016-09-21 18:56:12 +08005506 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005507 spv::Id extBuiltins = builder.import(name);
5508 extBuiltinMap[name] = extBuiltins;
5509 return extBuiltins;
5510 }
5511}
5512
John Kessenich140f3df2015-06-26 16:58:36 -06005513}; // end anonymous namespace
5514
5515namespace glslang {
5516
John Kessenich68d78fd2015-07-12 19:28:10 -06005517void GetSpirvVersion(std::string& version)
5518{
John Kessenich9e55f632015-07-15 10:03:39 -06005519 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005520 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005521 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005522 version = buf;
5523}
5524
John Kessenich140f3df2015-06-26 16:58:36 -06005525// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005526void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005527{
5528 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005529 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005530 if (out.fail())
5531 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005532 for (int i = 0; i < (int)spirv.size(); ++i) {
5533 unsigned int word = spirv[i];
5534 out.write((const char*)&word, 4);
5535 }
5536 out.close();
5537}
5538
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005539// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005540void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005541{
5542 std::ofstream out;
5543 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005544 if (out.fail())
5545 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005546 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005547 if (varName != nullptr) {
5548 out << "\t #pragma once" << std::endl;
5549 out << "const uint32_t " << varName << "[] = {" << std::endl;
5550 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005551 const int WORDS_PER_LINE = 8;
5552 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5553 out << "\t";
5554 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5555 const unsigned int word = spirv[i + j];
5556 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5557 if (i + j + 1 < (int)spirv.size()) {
5558 out << ",";
5559 }
5560 }
5561 out << std::endl;
5562 }
Flavio15017db2017-02-15 14:29:33 -08005563 if (varName != nullptr) {
5564 out << "};";
5565 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005566 out.close();
5567}
5568
John Kessenich140f3df2015-06-26 16:58:36 -06005569//
5570// Set up the glslang traversal
5571//
John Kessenich121853f2017-05-31 17:11:16 -06005572void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005573{
Lei Zhang17535f72016-05-04 15:55:59 -04005574 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005575 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005576}
5577
John Kessenich121853f2017-05-31 17:11:16 -06005578void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5579 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005580{
John Kessenich140f3df2015-06-26 16:58:36 -06005581 TIntermNode* root = intermediate.getTreeRoot();
5582
5583 if (root == 0)
5584 return;
5585
John Kessenich121853f2017-05-31 17:11:16 -06005586 glslang::SpvOptions defaultOptions;
5587 if (options == nullptr)
5588 options = &defaultOptions;
5589
John Kessenich140f3df2015-06-26 16:58:36 -06005590 glslang::GetThreadPoolAllocator().push();
5591
John Kessenich121853f2017-05-31 17:11:16 -06005592 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005593 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005594 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005595 it.dumpSpv(spirv);
5596
5597 glslang::GetThreadPoolAllocator().pop();
5598}
5599
5600}; // end namespace glslang