blob: 54dc61f35629f67ae12a906ab5c41a6224bf0d42 [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);
Rex Xu57e65922017-07-04 23:23:40 +0800125 spv::SelectionControlMask TranslateSelectionControl(glslang::TSelectionControl) const;
steve-lunargf1709e72017-05-02 20:14:50 -0600126 spv::LoopControlMask TranslateLoopControl(glslang::TLoopControl) const;
John Kessenicha5c5fb62017-05-05 05:09:58 -0600127 spv::StorageClass TranslateStorageClass(const glslang::TType&);
John Kessenich140f3df2015-06-26 16:58:36 -0600128 spv::Id createSpvVariable(const glslang::TIntermSymbol*);
129 spv::Id getSampledType(const glslang::TSampler&);
John Kessenich8c8505c2016-07-26 12:50:38 -0600130 spv::Id getInvertedSwizzleType(const glslang::TIntermTyped&);
131 spv::Id createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped&, spv::Id parentResult);
132 void convertSwizzle(const glslang::TIntermAggregate&, std::vector<unsigned>& swizzle);
John Kessenich140f3df2015-06-26 16:58:36 -0600133 spv::Id convertGlslangToSpvType(const glslang::TType& type);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700134 spv::Id convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking, const glslang::TQualifier&);
John Kessenich0e737842017-03-24 18:38:16 -0600135 bool filterMember(const glslang::TType& member);
John Kessenich6090df02016-06-30 21:18:02 -0600136 spv::Id convertGlslangStructToSpvType(const glslang::TType&, const glslang::TTypeList* glslangStruct,
137 glslang::TLayoutPacking, const glslang::TQualifier&);
138 void decorateStructType(const glslang::TType&, const glslang::TTypeList* glslangStruct, glslang::TLayoutPacking,
139 const glslang::TQualifier&, spv::Id);
John Kessenich6c292d32016-02-15 20:58:50 -0700140 spv::Id makeArraySizeId(const glslang::TArraySizes&, int dim);
John Kessenich32cfd492016-02-02 12:37:46 -0700141 spv::Id accessChainLoad(const glslang::TType& type);
Rex Xu27253232016-02-23 17:51:09 +0800142 void accessChainStore(const glslang::TType& type, spv::Id rvalue);
John Kessenich4bf71552016-09-02 11:20:21 -0600143 void multiTypeStore(const glslang::TType&, spv::Id rValue);
John Kessenichf85e8062015-12-19 13:57:10 -0700144 glslang::TLayoutPacking getExplicitLayout(const glslang::TType& type) const;
John Kessenich3ac051e2015-12-20 11:29:16 -0700145 int getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
146 int getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking, glslang::TLayoutMatrix);
147 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 +0100148 void declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember);
John Kessenich140f3df2015-06-26 16:58:36 -0600149
John Kessenich6fccb3c2016-09-19 16:01:41 -0600150 bool isShaderEntryPoint(const glslang::TIntermAggregate* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600151 void makeFunctions(const glslang::TIntermSequence&);
152 void makeGlobalInitializers(const glslang::TIntermSequence&);
153 void visitFunctions(const glslang::TIntermSequence&);
154 void handleFunctionEntry(const glslang::TIntermAggregate* node);
Rex Xu04db3f52015-09-16 11:44:02 +0800155 void translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments);
John Kessenichfc51d282015-08-19 13:34:18 -0600156 void translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments);
157 spv::Id createImageTextureFunctionCall(glslang::TIntermOperator* node);
John Kessenich140f3df2015-06-26 16:58:36 -0600158 spv::Id handleUserFunctionCall(const glslang::TIntermAggregate*);
159
qining25262b32016-05-06 17:25:16 -0400160 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);
161 spv::Id createBinaryMatrixOperation(spv::Op, spv::Decoration precision, spv::Decoration noContraction, spv::Id typeId, spv::Id left, spv::Id right);
162 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 +0800163 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 +0800164 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 -0600165 spv::Id makeSmearedConstant(spv::Id constant, int vectorSize);
Rex Xu04db3f52015-09-16 11:44:02 +0800166 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 +0800167 spv::Id createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy);
Rex Xu430ef402016-10-14 17:22:23 +0800168 spv::Id CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands);
John Kessenich5e4b1242015-08-06 22:53:06 -0600169 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 +0800170 spv::Id createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId);
John Kessenich140f3df2015-06-26 16:58:36 -0600171 spv::Id getSymbolId(const glslang::TIntermSymbol* node);
172 void addDecoration(spv::Id id, spv::Decoration dec);
John Kessenich55e7d112015-11-15 21:33:39 -0700173 void addDecoration(spv::Id id, spv::Decoration dec, unsigned value);
John Kessenich140f3df2015-06-26 16:58:36 -0600174 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec);
John Kessenich92187592016-02-01 13:45:25 -0700175 void addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value);
qining08408382016-03-21 09:51:37 -0400176 spv::Id createSpvConstant(const glslang::TIntermTyped&);
177 spv::Id createSpvConstantFromConstUnionArray(const glslang::TType& type, const glslang::TConstUnionArray&, int& nextConst, bool specConstant);
John Kessenich7c1aa102015-10-15 13:29:11 -0600178 bool isTrivialLeaf(const glslang::TIntermTyped* node);
179 bool isTrivial(const glslang::TIntermTyped* node);
180 spv::Id createShortCircuit(glslang::TOperator, glslang::TIntermTyped& left, glslang::TIntermTyped& right);
Rex Xu9d93a232016-05-05 12:30:44 +0800181 spv::Id getExtBuiltins(const char* name);
John Kessenich140f3df2015-06-26 16:58:36 -0600182
John Kessenich121853f2017-05-31 17:11:16 -0600183 glslang::SpvOptions& options;
John Kessenich140f3df2015-06-26 16:58:36 -0600184 spv::Function* shaderEntry;
John Kesseniched33e052016-10-06 12:59:51 -0600185 spv::Function* currentFunction;
John Kessenich55e7d112015-11-15 21:33:39 -0700186 spv::Instruction* entryPoint;
John Kessenich140f3df2015-06-26 16:58:36 -0600187 int sequenceDepth;
188
Lei Zhang17535f72016-05-04 15:55:59 -0400189 spv::SpvBuildLogger* logger;
Lei Zhang09caf122016-05-02 18:11:54 -0400190
John Kessenich140f3df2015-06-26 16:58:36 -0600191 // There is a 1:1 mapping between a spv builder and a module; this is thread safe
192 spv::Builder builder;
John Kessenich517fe7a2016-11-26 13:31:47 -0700193 bool inEntryPoint;
194 bool entryPointTerminated;
John Kessenich7ba63412015-12-20 17:37:07 -0700195 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 -0700196 std::set<spv::Id> iOSet; // all input/output variables from either static use or declaration of interface
John Kessenich140f3df2015-06-26 16:58:36 -0600197 const glslang::TIntermediate* glslangIntermediate;
198 spv::Id stdBuiltins;
Rex Xu9d93a232016-05-05 12:30:44 +0800199 std::unordered_map<const char*, spv::Id> extBuiltinMap;
John Kessenich140f3df2015-06-26 16:58:36 -0600200
John Kessenich2f273362015-07-18 22:34:27 -0600201 std::unordered_map<int, spv::Id> symbolValues;
John Kessenich4bf71552016-09-02 11:20:21 -0600202 std::unordered_set<int> rValueParameters; // set of formal function parameters passed as rValues, rather than a pointer
John Kessenich2f273362015-07-18 22:34:27 -0600203 std::unordered_map<std::string, spv::Function*> functionMap;
John Kessenich3ac051e2015-12-20 11:29:16 -0700204 std::unordered_map<const glslang::TTypeList*, spv::Id> structMap[glslang::ElpCount][glslang::ElmCount];
John Kessenich2f273362015-07-18 22:34:27 -0600205 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 -0600206 std::stack<bool> breakForLoop; // false means break for switch
John Kessenich140f3df2015-06-26 16:58:36 -0600207};
208
209//
210// Helper functions for translating glslang representations to SPIR-V enumerants.
211//
212
213// Translate glslang profile to SPIR-V source language.
John Kessenich66e2faf2016-03-12 18:34:36 -0700214spv::SourceLanguage TranslateSourceLanguage(glslang::EShSource source, EProfile profile)
John Kessenich140f3df2015-06-26 16:58:36 -0600215{
John Kessenich66e2faf2016-03-12 18:34:36 -0700216 switch (source) {
217 case glslang::EShSourceGlsl:
218 switch (profile) {
219 case ENoProfile:
220 case ECoreProfile:
221 case ECompatibilityProfile:
222 return spv::SourceLanguageGLSL;
223 case EEsProfile:
224 return spv::SourceLanguageESSL;
225 default:
226 return spv::SourceLanguageUnknown;
227 }
228 case glslang::EShSourceHlsl:
John Kessenich6fa17642017-04-07 15:33:08 -0600229 return spv::SourceLanguageHLSL;
John Kessenich140f3df2015-06-26 16:58:36 -0600230 default:
231 return spv::SourceLanguageUnknown;
232 }
233}
234
235// Translate glslang language (stage) to SPIR-V execution model.
236spv::ExecutionModel TranslateExecutionModel(EShLanguage stage)
237{
238 switch (stage) {
239 case EShLangVertex: return spv::ExecutionModelVertex;
240 case EShLangTessControl: return spv::ExecutionModelTessellationControl;
241 case EShLangTessEvaluation: return spv::ExecutionModelTessellationEvaluation;
242 case EShLangGeometry: return spv::ExecutionModelGeometry;
243 case EShLangFragment: return spv::ExecutionModelFragment;
244 case EShLangCompute: return spv::ExecutionModelGLCompute;
245 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700246 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600247 return spv::ExecutionModelFragment;
248 }
249}
250
John Kessenich140f3df2015-06-26 16:58:36 -0600251// Translate glslang sampler type to SPIR-V dimensionality.
252spv::Dim TranslateDimensionality(const glslang::TSampler& sampler)
253{
254 switch (sampler.dim) {
John Kessenich55e7d112015-11-15 21:33:39 -0700255 case glslang::Esd1D: return spv::Dim1D;
256 case glslang::Esd2D: return spv::Dim2D;
257 case glslang::Esd3D: return spv::Dim3D;
258 case glslang::EsdCube: return spv::DimCube;
259 case glslang::EsdRect: return spv::DimRect;
260 case glslang::EsdBuffer: return spv::DimBuffer;
John Kessenich6c292d32016-02-15 20:58:50 -0700261 case glslang::EsdSubpass: return spv::DimSubpassData;
John Kessenich140f3df2015-06-26 16:58:36 -0600262 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700263 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600264 return spv::Dim2D;
265 }
266}
267
John Kessenichf6640762016-08-01 19:44:00 -0600268// Translate glslang precision to SPIR-V precision decorations.
269spv::Decoration TranslatePrecisionDecoration(glslang::TPrecisionQualifier glslangPrecision)
John Kessenich140f3df2015-06-26 16:58:36 -0600270{
John Kessenichf6640762016-08-01 19:44:00 -0600271 switch (glslangPrecision) {
John Kessenich61c47a92015-12-14 18:21:19 -0700272 case glslang::EpqLow: return spv::DecorationRelaxedPrecision;
John Kessenich5e4b1242015-08-06 22:53:06 -0600273 case glslang::EpqMedium: return spv::DecorationRelaxedPrecision;
John Kessenich140f3df2015-06-26 16:58:36 -0600274 default:
275 return spv::NoPrecision;
276 }
277}
278
John Kessenichf6640762016-08-01 19:44:00 -0600279// Translate glslang type to SPIR-V precision decorations.
280spv::Decoration TranslatePrecisionDecoration(const glslang::TType& type)
281{
282 return TranslatePrecisionDecoration(type.getQualifier().precision);
283}
284
John Kessenich140f3df2015-06-26 16:58:36 -0600285// Translate glslang type to SPIR-V block decorations.
John Kessenich67027182017-04-19 18:34:49 -0600286spv::Decoration TranslateBlockDecoration(const glslang::TType& type, bool useStorageBuffer)
John Kessenich140f3df2015-06-26 16:58:36 -0600287{
288 if (type.getBasicType() == glslang::EbtBlock) {
289 switch (type.getQualifier().storage) {
290 case glslang::EvqUniform: return spv::DecorationBlock;
John Kessenich67027182017-04-19 18:34:49 -0600291 case glslang::EvqBuffer: return useStorageBuffer ? spv::DecorationBlock : spv::DecorationBufferBlock;
John Kessenich140f3df2015-06-26 16:58:36 -0600292 case glslang::EvqVaryingIn: return spv::DecorationBlock;
293 case glslang::EvqVaryingOut: return spv::DecorationBlock;
294 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700295 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -0600296 break;
297 }
298 }
299
John Kessenich4016e382016-07-15 11:53:56 -0600300 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600301}
302
Rex Xu1da878f2016-02-21 20:59:01 +0800303// Translate glslang type to SPIR-V memory decorations.
304void TranslateMemoryDecoration(const glslang::TQualifier& qualifier, std::vector<spv::Decoration>& memory)
305{
306 if (qualifier.coherent)
307 memory.push_back(spv::DecorationCoherent);
308 if (qualifier.volatil)
309 memory.push_back(spv::DecorationVolatile);
310 if (qualifier.restrict)
311 memory.push_back(spv::DecorationRestrict);
312 if (qualifier.readonly)
313 memory.push_back(spv::DecorationNonWritable);
314 if (qualifier.writeonly)
315 memory.push_back(spv::DecorationNonReadable);
316}
317
John Kessenich140f3df2015-06-26 16:58:36 -0600318// Translate glslang type to SPIR-V layout decorations.
John Kessenich3ac051e2015-12-20 11:29:16 -0700319spv::Decoration TranslateLayoutDecoration(const glslang::TType& type, glslang::TLayoutMatrix matrixLayout)
John Kessenich140f3df2015-06-26 16:58:36 -0600320{
321 if (type.isMatrix()) {
John Kessenich3ac051e2015-12-20 11:29:16 -0700322 switch (matrixLayout) {
John Kessenich140f3df2015-06-26 16:58:36 -0600323 case glslang::ElmRowMajor:
324 return spv::DecorationRowMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700325 case glslang::ElmColumnMajor:
John Kessenich140f3df2015-06-26 16:58:36 -0600326 return spv::DecorationColMajor;
John Kessenich3ac051e2015-12-20 11:29:16 -0700327 default:
328 // opaque layouts don't need a majorness
John Kessenich4016e382016-07-15 11:53:56 -0600329 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600330 }
331 } else {
332 switch (type.getBasicType()) {
333 default:
John Kessenich4016e382016-07-15 11:53:56 -0600334 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600335 break;
336 case glslang::EbtBlock:
337 switch (type.getQualifier().storage) {
338 case glslang::EvqUniform:
339 case glslang::EvqBuffer:
340 switch (type.getQualifier().layoutPacking) {
341 case glslang::ElpShared: return spv::DecorationGLSLShared;
John Kessenich140f3df2015-06-26 16:58:36 -0600342 case glslang::ElpPacked: return spv::DecorationGLSLPacked;
343 default:
John Kessenich4016e382016-07-15 11:53:56 -0600344 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600345 }
346 case glslang::EvqVaryingIn:
347 case glslang::EvqVaryingOut:
John Kessenich55e7d112015-11-15 21:33:39 -0700348 assert(type.getQualifier().layoutPacking == glslang::ElpNone);
John Kessenich4016e382016-07-15 11:53:56 -0600349 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600350 default:
John Kessenich55e7d112015-11-15 21:33:39 -0700351 assert(0);
John Kessenich4016e382016-07-15 11:53:56 -0600352 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600353 }
354 }
355 }
356}
357
358// Translate glslang type to SPIR-V interpolation decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600359// Returns spv::DecorationMax when no decoration
John Kessenich55e7d112015-11-15 21:33:39 -0700360// should be applied.
Rex Xu17ff3432016-10-14 17:41:45 +0800361spv::Decoration TGlslangToSpvTraverser::TranslateInterpolationDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600362{
Rex Xubbceed72016-05-21 09:40:44 +0800363 if (qualifier.smooth)
John Kessenich55e7d112015-11-15 21:33:39 -0700364 // Smooth decoration doesn't exist in SPIR-V 1.0
John Kessenich4016e382016-07-15 11:53:56 -0600365 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800366 else if (qualifier.nopersp)
John Kessenich55e7d112015-11-15 21:33:39 -0700367 return spv::DecorationNoPerspective;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700368 else if (qualifier.flat)
John Kessenich140f3df2015-06-26 16:58:36 -0600369 return spv::DecorationFlat;
Rex Xu9d93a232016-05-05 12:30:44 +0800370#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800371 else if (qualifier.explicitInterp) {
372 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
Rex Xu9d93a232016-05-05 12:30:44 +0800373 return spv::DecorationExplicitInterpAMD;
Rex Xu17ff3432016-10-14 17:41:45 +0800374 }
Rex Xu9d93a232016-05-05 12:30:44 +0800375#endif
Rex Xubbceed72016-05-21 09:40:44 +0800376 else
John Kessenich4016e382016-07-15 11:53:56 -0600377 return spv::DecorationMax;
Rex Xubbceed72016-05-21 09:40:44 +0800378}
379
380// Translate glslang type to SPIR-V auxiliary storage decorations.
John Kessenich4016e382016-07-15 11:53:56 -0600381// Returns spv::DecorationMax when no decoration
Rex Xubbceed72016-05-21 09:40:44 +0800382// should be applied.
383spv::Decoration TGlslangToSpvTraverser::TranslateAuxiliaryStorageDecoration(const glslang::TQualifier& qualifier)
384{
385 if (qualifier.patch)
386 return spv::DecorationPatch;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700387 else if (qualifier.centroid)
John Kessenich140f3df2015-06-26 16:58:36 -0600388 return spv::DecorationCentroid;
John Kessenich5e801132016-02-15 11:09:46 -0700389 else if (qualifier.sample) {
390 builder.addCapability(spv::CapabilitySampleRateShading);
John Kessenich140f3df2015-06-26 16:58:36 -0600391 return spv::DecorationSample;
John Kessenich5e801132016-02-15 11:09:46 -0700392 } else
John Kessenich4016e382016-07-15 11:53:56 -0600393 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600394}
395
John Kessenich92187592016-02-01 13:45:25 -0700396// If glslang type is invariant, return SPIR-V invariant decoration.
John Kesseniche0b6cad2015-12-24 10:30:13 -0700397spv::Decoration TranslateInvariantDecoration(const glslang::TQualifier& qualifier)
John Kessenich140f3df2015-06-26 16:58:36 -0600398{
John Kesseniche0b6cad2015-12-24 10:30:13 -0700399 if (qualifier.invariant)
John Kessenich140f3df2015-06-26 16:58:36 -0600400 return spv::DecorationInvariant;
401 else
John Kessenich4016e382016-07-15 11:53:56 -0600402 return spv::DecorationMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600403}
404
qining9220dbb2016-05-04 17:34:38 -0400405// If glslang type is noContraction, return SPIR-V NoContraction decoration.
406spv::Decoration TranslateNoContractionDecoration(const glslang::TQualifier& qualifier)
407{
408 if (qualifier.noContraction)
409 return spv::DecorationNoContraction;
410 else
John Kessenich4016e382016-07-15 11:53:56 -0600411 return spv::DecorationMax;
qining9220dbb2016-05-04 17:34:38 -0400412}
413
David Netoa901ffe2016-06-08 14:11:40 +0100414// Translate a glslang built-in variable to a SPIR-V built in decoration. Also generate
415// associated capabilities when required. For some built-in variables, a capability
416// is generated only when using the variable in an executable instruction, but not when
417// just declaring a struct member variable with it. This is true for PointSize,
418// ClipDistance, and CullDistance.
419spv::BuiltIn TGlslangToSpvTraverser::TranslateBuiltInDecoration(glslang::TBuiltInVariable builtIn, bool memberDeclaration)
John Kessenich140f3df2015-06-26 16:58:36 -0600420{
421 switch (builtIn) {
John Kessenich92187592016-02-01 13:45:25 -0700422 case glslang::EbvPointSize:
John Kessenich78a45572016-07-08 14:05:15 -0600423 // Defer adding the capability until the built-in is actually used.
424 if (! memberDeclaration) {
425 switch (glslangIntermediate->getStage()) {
426 case EShLangGeometry:
427 builder.addCapability(spv::CapabilityGeometryPointSize);
428 break;
429 case EShLangTessControl:
430 case EShLangTessEvaluation:
431 builder.addCapability(spv::CapabilityTessellationPointSize);
432 break;
433 default:
434 break;
435 }
John Kessenich92187592016-02-01 13:45:25 -0700436 }
437 return spv::BuiltInPointSize;
438
John Kessenichebb50532016-05-16 19:22:05 -0600439 // These *Distance capabilities logically belong here, but if the member is declared and
440 // then never used, consumers of SPIR-V prefer the capability not be declared.
441 // They are now generated when used, rather than here when declared.
442 // Potentially, the specification should be more clear what the minimum
443 // use needed is to trigger the capability.
444 //
John Kessenich92187592016-02-01 13:45:25 -0700445 case glslang::EbvClipDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100446 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800447 builder.addCapability(spv::CapabilityClipDistance);
John Kessenich92187592016-02-01 13:45:25 -0700448 return spv::BuiltInClipDistance;
449
450 case glslang::EbvCullDistance:
David Netoa901ffe2016-06-08 14:11:40 +0100451 if (!memberDeclaration)
Rex Xu3e783f92017-02-22 16:44:48 +0800452 builder.addCapability(spv::CapabilityCullDistance);
John Kessenich92187592016-02-01 13:45:25 -0700453 return spv::BuiltInCullDistance;
454
455 case glslang::EbvViewportIndex:
John Kessenichba6a3c22017-09-13 13:22:50 -0600456 builder.addCapability(spv::CapabilityMultiViewport);
457 if (glslangIntermediate->getStage() == EShLangVertex ||
458 glslangIntermediate->getStage() == EShLangTessControl ||
459 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800460
John Kessenichba6a3c22017-09-13 13:22:50 -0600461 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
462 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800463 }
John Kessenich92187592016-02-01 13:45:25 -0700464 return spv::BuiltInViewportIndex;
465
John Kessenich5e801132016-02-15 11:09:46 -0700466 case glslang::EbvSampleId:
467 builder.addCapability(spv::CapabilitySampleRateShading);
468 return spv::BuiltInSampleId;
469
470 case glslang::EbvSamplePosition:
471 builder.addCapability(spv::CapabilitySampleRateShading);
472 return spv::BuiltInSamplePosition;
473
474 case glslang::EbvSampleMask:
475 builder.addCapability(spv::CapabilitySampleRateShading);
476 return spv::BuiltInSampleMask;
477
John Kessenich78a45572016-07-08 14:05:15 -0600478 case glslang::EbvLayer:
John Kessenichba6a3c22017-09-13 13:22:50 -0600479 builder.addCapability(spv::CapabilityGeometry);
480 if (glslangIntermediate->getStage() == EShLangVertex ||
481 glslangIntermediate->getStage() == EShLangTessControl ||
482 glslangIntermediate->getStage() == EShLangTessEvaluation) {
Rex Xu5e317ff2017-03-16 23:02:39 +0800483
John Kessenichba6a3c22017-09-13 13:22:50 -0600484 builder.addExtension(spv::E_SPV_EXT_shader_viewport_index_layer);
485 builder.addCapability(spv::CapabilityShaderViewportIndexLayerEXT);
Rex Xu5e317ff2017-03-16 23:02:39 +0800486 }
John Kessenich78a45572016-07-08 14:05:15 -0600487 return spv::BuiltInLayer;
488
John Kessenich140f3df2015-06-26 16:58:36 -0600489 case glslang::EbvPosition: return spv::BuiltInPosition;
John Kessenich140f3df2015-06-26 16:58:36 -0600490 case glslang::EbvVertexId: return spv::BuiltInVertexId;
491 case glslang::EbvInstanceId: return spv::BuiltInInstanceId;
John Kessenich6c292d32016-02-15 20:58:50 -0700492 case glslang::EbvVertexIndex: return spv::BuiltInVertexIndex;
493 case glslang::EbvInstanceIndex: return spv::BuiltInInstanceIndex;
Rex Xuf3b27472016-07-22 18:15:31 +0800494
John Kessenichda581a22015-10-14 14:10:30 -0600495 case glslang::EbvBaseVertex:
Rex Xuf3b27472016-07-22 18:15:31 +0800496 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
497 builder.addCapability(spv::CapabilityDrawParameters);
498 return spv::BuiltInBaseVertex;
499
John Kessenichda581a22015-10-14 14:10:30 -0600500 case glslang::EbvBaseInstance:
Rex Xuf3b27472016-07-22 18:15:31 +0800501 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
502 builder.addCapability(spv::CapabilityDrawParameters);
503 return spv::BuiltInBaseInstance;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200504
John Kessenichda581a22015-10-14 14:10:30 -0600505 case glslang::EbvDrawId:
Rex Xuf3b27472016-07-22 18:15:31 +0800506 builder.addExtension(spv::E_SPV_KHR_shader_draw_parameters);
507 builder.addCapability(spv::CapabilityDrawParameters);
508 return spv::BuiltInDrawIndex;
Maciej Jesionowski04b3e872016-09-26 16:49:09 +0200509
510 case glslang::EbvPrimitiveId:
511 if (glslangIntermediate->getStage() == EShLangFragment)
512 builder.addCapability(spv::CapabilityGeometry);
513 return spv::BuiltInPrimitiveId;
514
Rex Xu37cdcee2017-06-29 17:46:34 +0800515 case glslang::EbvFragStencilRef:
Rex Xue8fdd792017-08-23 23:24:42 +0800516 builder.addExtension(spv::E_SPV_EXT_shader_stencil_export);
517 builder.addCapability(spv::CapabilityStencilExportEXT);
518 return spv::BuiltInFragStencilRefEXT;
Rex Xu37cdcee2017-06-29 17:46:34 +0800519
John Kessenich140f3df2015-06-26 16:58:36 -0600520 case glslang::EbvInvocationId: return spv::BuiltInInvocationId;
John Kessenich140f3df2015-06-26 16:58:36 -0600521 case glslang::EbvTessLevelInner: return spv::BuiltInTessLevelInner;
522 case glslang::EbvTessLevelOuter: return spv::BuiltInTessLevelOuter;
523 case glslang::EbvTessCoord: return spv::BuiltInTessCoord;
524 case glslang::EbvPatchVertices: return spv::BuiltInPatchVertices;
525 case glslang::EbvFragCoord: return spv::BuiltInFragCoord;
526 case glslang::EbvPointCoord: return spv::BuiltInPointCoord;
527 case glslang::EbvFace: return spv::BuiltInFrontFacing;
John Kessenich140f3df2015-06-26 16:58:36 -0600528 case glslang::EbvFragDepth: return spv::BuiltInFragDepth;
529 case glslang::EbvHelperInvocation: return spv::BuiltInHelperInvocation;
530 case glslang::EbvNumWorkGroups: return spv::BuiltInNumWorkgroups;
531 case glslang::EbvWorkGroupSize: return spv::BuiltInWorkgroupSize;
532 case glslang::EbvWorkGroupId: return spv::BuiltInWorkgroupId;
533 case glslang::EbvLocalInvocationId: return spv::BuiltInLocalInvocationId;
534 case glslang::EbvLocalInvocationIndex: return spv::BuiltInLocalInvocationIndex;
535 case glslang::EbvGlobalInvocationId: return spv::BuiltInGlobalInvocationId;
Rex Xu51596642016-09-21 18:56:12 +0800536
Rex Xu574ab042016-04-14 16:53:07 +0800537 case glslang::EbvSubGroupSize:
Rex Xu36876e62016-09-23 22:13:43 +0800538 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800539 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
540 return spv::BuiltInSubgroupSize;
541
Rex Xu574ab042016-04-14 16:53:07 +0800542 case glslang::EbvSubGroupInvocation:
Rex Xu36876e62016-09-23 22:13:43 +0800543 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
Rex Xu51596642016-09-21 18:56:12 +0800544 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
545 return spv::BuiltInSubgroupLocalInvocationId;
546
Rex Xu574ab042016-04-14 16:53:07 +0800547 case glslang::EbvSubGroupEqMask:
Rex Xu51596642016-09-21 18:56:12 +0800548 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
549 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
550 return spv::BuiltInSubgroupEqMaskKHR;
551
Rex Xu574ab042016-04-14 16:53:07 +0800552 case glslang::EbvSubGroupGeMask:
Rex Xu51596642016-09-21 18:56:12 +0800553 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
554 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
555 return spv::BuiltInSubgroupGeMaskKHR;
556
Rex Xu574ab042016-04-14 16:53:07 +0800557 case glslang::EbvSubGroupGtMask:
Rex Xu51596642016-09-21 18:56:12 +0800558 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
559 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
560 return spv::BuiltInSubgroupGtMaskKHR;
561
Rex Xu574ab042016-04-14 16:53:07 +0800562 case glslang::EbvSubGroupLeMask:
Rex Xu51596642016-09-21 18:56:12 +0800563 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
564 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
565 return spv::BuiltInSubgroupLeMaskKHR;
566
Rex Xu574ab042016-04-14 16:53:07 +0800567 case glslang::EbvSubGroupLtMask:
Rex Xu51596642016-09-21 18:56:12 +0800568 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
569 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
570 return spv::BuiltInSubgroupLtMaskKHR;
571
Rex Xu9d93a232016-05-05 12:30:44 +0800572#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +0800573 case glslang::EbvBaryCoordNoPersp:
574 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
575 return spv::BuiltInBaryCoordNoPerspAMD;
576
577 case glslang::EbvBaryCoordNoPerspCentroid:
578 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
579 return spv::BuiltInBaryCoordNoPerspCentroidAMD;
580
581 case glslang::EbvBaryCoordNoPerspSample:
582 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
583 return spv::BuiltInBaryCoordNoPerspSampleAMD;
584
585 case glslang::EbvBaryCoordSmooth:
586 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
587 return spv::BuiltInBaryCoordSmoothAMD;
588
589 case glslang::EbvBaryCoordSmoothCentroid:
590 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
591 return spv::BuiltInBaryCoordSmoothCentroidAMD;
592
593 case glslang::EbvBaryCoordSmoothSample:
594 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
595 return spv::BuiltInBaryCoordSmoothSampleAMD;
596
597 case glslang::EbvBaryCoordPullModel:
598 builder.addExtension(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
599 return spv::BuiltInBaryCoordPullModelAMD;
Rex Xu9d93a232016-05-05 12:30:44 +0800600#endif
chaoc771d89f2017-01-13 01:10:53 -0800601
John Kessenich6c8aaac2017-02-27 01:20:51 -0700602 case glslang::EbvDeviceIndex:
603 builder.addExtension(spv::E_SPV_KHR_device_group);
604 builder.addCapability(spv::CapabilityDeviceGroup);
John Kessenich42e33c92017-02-27 01:50:28 -0700605 return spv::BuiltInDeviceIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700606
607 case glslang::EbvViewIndex:
608 builder.addExtension(spv::E_SPV_KHR_multiview);
609 builder.addCapability(spv::CapabilityMultiView);
John Kessenich42e33c92017-02-27 01:50:28 -0700610 return spv::BuiltInViewIndex;
John Kessenich6c8aaac2017-02-27 01:20:51 -0700611
chaoc771d89f2017-01-13 01:10:53 -0800612#ifdef NV_EXTENSIONS
613 case glslang::EbvViewportMaskNV:
Rex Xu5e317ff2017-03-16 23:02:39 +0800614 if (!memberDeclaration) {
615 builder.addExtension(spv::E_SPV_NV_viewport_array2);
616 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
617 }
chaoc771d89f2017-01-13 01:10:53 -0800618 return spv::BuiltInViewportMaskNV;
619 case glslang::EbvSecondaryPositionNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800620 if (!memberDeclaration) {
621 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
622 builder.addCapability(spv::CapabilityShaderStereoViewNV);
623 }
chaoc771d89f2017-01-13 01:10:53 -0800624 return spv::BuiltInSecondaryPositionNV;
625 case glslang::EbvSecondaryViewportMaskNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800626 if (!memberDeclaration) {
627 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
628 builder.addCapability(spv::CapabilityShaderStereoViewNV);
629 }
chaoc771d89f2017-01-13 01:10:53 -0800630 return spv::BuiltInSecondaryViewportMaskNV;
chaocdf3956c2017-02-14 14:52:34 -0800631 case glslang::EbvPositionPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800632 if (!memberDeclaration) {
633 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
634 builder.addCapability(spv::CapabilityPerViewAttributesNV);
635 }
chaocdf3956c2017-02-14 14:52:34 -0800636 return spv::BuiltInPositionPerViewNV;
637 case glslang::EbvViewportMaskPerViewNV:
Rex Xu3e783f92017-02-22 16:44:48 +0800638 if (!memberDeclaration) {
639 builder.addExtension(spv::E_SPV_NVX_multiview_per_view_attributes);
640 builder.addCapability(spv::CapabilityPerViewAttributesNV);
641 }
chaocdf3956c2017-02-14 14:52:34 -0800642 return spv::BuiltInViewportMaskPerViewNV;
chaoc771d89f2017-01-13 01:10:53 -0800643#endif
Rex Xu3e783f92017-02-22 16:44:48 +0800644 default:
645 return spv::BuiltInMax;
John Kessenich140f3df2015-06-26 16:58:36 -0600646 }
647}
648
Rex Xufc618912015-09-09 16:42:49 +0800649// Translate glslang image layout format to SPIR-V image format.
John Kessenich5d0fa972016-02-15 11:57:00 -0700650spv::ImageFormat TGlslangToSpvTraverser::TranslateImageFormat(const glslang::TType& type)
Rex Xufc618912015-09-09 16:42:49 +0800651{
652 assert(type.getBasicType() == glslang::EbtSampler);
653
John Kessenich5d0fa972016-02-15 11:57:00 -0700654 // Check for capabilities
655 switch (type.getQualifier().layoutFormat) {
656 case glslang::ElfRg32f:
657 case glslang::ElfRg16f:
658 case glslang::ElfR11fG11fB10f:
659 case glslang::ElfR16f:
660 case glslang::ElfRgba16:
661 case glslang::ElfRgb10A2:
662 case glslang::ElfRg16:
663 case glslang::ElfRg8:
664 case glslang::ElfR16:
665 case glslang::ElfR8:
666 case glslang::ElfRgba16Snorm:
667 case glslang::ElfRg16Snorm:
668 case glslang::ElfRg8Snorm:
669 case glslang::ElfR16Snorm:
670 case glslang::ElfR8Snorm:
671
672 case glslang::ElfRg32i:
673 case glslang::ElfRg16i:
674 case glslang::ElfRg8i:
675 case glslang::ElfR16i:
676 case glslang::ElfR8i:
677
678 case glslang::ElfRgb10a2ui:
679 case glslang::ElfRg32ui:
680 case glslang::ElfRg16ui:
681 case glslang::ElfRg8ui:
682 case glslang::ElfR16ui:
683 case glslang::ElfR8ui:
684 builder.addCapability(spv::CapabilityStorageImageExtendedFormats);
685 break;
686
687 default:
688 break;
689 }
690
691 // do the translation
Rex Xufc618912015-09-09 16:42:49 +0800692 switch (type.getQualifier().layoutFormat) {
693 case glslang::ElfNone: return spv::ImageFormatUnknown;
694 case glslang::ElfRgba32f: return spv::ImageFormatRgba32f;
695 case glslang::ElfRgba16f: return spv::ImageFormatRgba16f;
696 case glslang::ElfR32f: return spv::ImageFormatR32f;
697 case glslang::ElfRgba8: return spv::ImageFormatRgba8;
698 case glslang::ElfRgba8Snorm: return spv::ImageFormatRgba8Snorm;
699 case glslang::ElfRg32f: return spv::ImageFormatRg32f;
700 case glslang::ElfRg16f: return spv::ImageFormatRg16f;
701 case glslang::ElfR11fG11fB10f: return spv::ImageFormatR11fG11fB10f;
702 case glslang::ElfR16f: return spv::ImageFormatR16f;
703 case glslang::ElfRgba16: return spv::ImageFormatRgba16;
704 case glslang::ElfRgb10A2: return spv::ImageFormatRgb10A2;
705 case glslang::ElfRg16: return spv::ImageFormatRg16;
706 case glslang::ElfRg8: return spv::ImageFormatRg8;
707 case glslang::ElfR16: return spv::ImageFormatR16;
708 case glslang::ElfR8: return spv::ImageFormatR8;
709 case glslang::ElfRgba16Snorm: return spv::ImageFormatRgba16Snorm;
710 case glslang::ElfRg16Snorm: return spv::ImageFormatRg16Snorm;
711 case glslang::ElfRg8Snorm: return spv::ImageFormatRg8Snorm;
712 case glslang::ElfR16Snorm: return spv::ImageFormatR16Snorm;
713 case glslang::ElfR8Snorm: return spv::ImageFormatR8Snorm;
714 case glslang::ElfRgba32i: return spv::ImageFormatRgba32i;
715 case glslang::ElfRgba16i: return spv::ImageFormatRgba16i;
716 case glslang::ElfRgba8i: return spv::ImageFormatRgba8i;
717 case glslang::ElfR32i: return spv::ImageFormatR32i;
718 case glslang::ElfRg32i: return spv::ImageFormatRg32i;
719 case glslang::ElfRg16i: return spv::ImageFormatRg16i;
720 case glslang::ElfRg8i: return spv::ImageFormatRg8i;
721 case glslang::ElfR16i: return spv::ImageFormatR16i;
722 case glslang::ElfR8i: return spv::ImageFormatR8i;
723 case glslang::ElfRgba32ui: return spv::ImageFormatRgba32ui;
724 case glslang::ElfRgba16ui: return spv::ImageFormatRgba16ui;
725 case glslang::ElfRgba8ui: return spv::ImageFormatRgba8ui;
726 case glslang::ElfR32ui: return spv::ImageFormatR32ui;
727 case glslang::ElfRg32ui: return spv::ImageFormatRg32ui;
728 case glslang::ElfRg16ui: return spv::ImageFormatRg16ui;
729 case glslang::ElfRgb10a2ui: return spv::ImageFormatRgb10a2ui;
730 case glslang::ElfRg8ui: return spv::ImageFormatRg8ui;
731 case glslang::ElfR16ui: return spv::ImageFormatR16ui;
732 case glslang::ElfR8ui: return spv::ImageFormatR8ui;
John Kessenich4016e382016-07-15 11:53:56 -0600733 default: return spv::ImageFormatMax;
Rex Xufc618912015-09-09 16:42:49 +0800734 }
735}
736
Rex Xu57e65922017-07-04 23:23:40 +0800737spv::SelectionControlMask TGlslangToSpvTraverser::TranslateSelectionControl(glslang::TSelectionControl selectionControl) const
738{
739 switch (selectionControl) {
740 case glslang::ESelectionControlNone: return spv::SelectionControlMaskNone;
741 case glslang::ESelectionControlFlatten: return spv::SelectionControlFlattenMask;
742 case glslang::ESelectionControlDontFlatten: return spv::SelectionControlDontFlattenMask;
743 default: return spv::SelectionControlMaskNone;
744 }
745}
746
steve-lunargf1709e72017-05-02 20:14:50 -0600747spv::LoopControlMask TGlslangToSpvTraverser::TranslateLoopControl(glslang::TLoopControl loopControl) const
748{
749 switch (loopControl) {
750 case glslang::ELoopControlNone: return spv::LoopControlMaskNone;
751 case glslang::ELoopControlUnroll: return spv::LoopControlUnrollMask;
752 case glslang::ELoopControlDontUnroll: return spv::LoopControlDontUnrollMask;
753 // TODO: DependencyInfinite
754 // TODO: DependencyLength
755 default: return spv::LoopControlMaskNone;
756 }
757}
758
John Kessenicha5c5fb62017-05-05 05:09:58 -0600759// Translate glslang type to SPIR-V storage class.
760spv::StorageClass TGlslangToSpvTraverser::TranslateStorageClass(const glslang::TType& type)
761{
762 if (type.getQualifier().isPipeInput())
763 return spv::StorageClassInput;
764 else if (type.getQualifier().isPipeOutput())
765 return spv::StorageClassOutput;
766 else if (type.getBasicType() == glslang::EbtAtomicUint)
767 return spv::StorageClassAtomicCounter;
768 else if (type.containsOpaque())
769 return spv::StorageClassUniformConstant;
770 else if (glslangIntermediate->usingStorageBuffer() && type.getQualifier().storage == glslang::EvqBuffer) {
771 builder.addExtension(spv::E_SPV_KHR_storage_buffer_storage_class);
772 return spv::StorageClassStorageBuffer;
773 } else if (type.getQualifier().isUniformOrBuffer()) {
774 if (type.getQualifier().layoutPushConstant)
775 return spv::StorageClassPushConstant;
776 if (type.getBasicType() == glslang::EbtBlock)
777 return spv::StorageClassUniform;
778 else
779 return spv::StorageClassUniformConstant;
780 } else {
781 switch (type.getQualifier().storage) {
782 case glslang::EvqShared: return spv::StorageClassWorkgroup; break;
783 case glslang::EvqGlobal: return spv::StorageClassPrivate;
784 case glslang::EvqConstReadOnly: return spv::StorageClassFunction;
785 case glslang::EvqTemporary: return spv::StorageClassFunction;
786 default:
787 assert(0);
788 return spv::StorageClassFunction;
789 }
790 }
791}
792
qining25262b32016-05-06 17:25:16 -0400793// Return whether or not the given type is something that should be tied to a
John Kessenich6c292d32016-02-15 20:58:50 -0700794// descriptor set.
795bool IsDescriptorResource(const glslang::TType& type)
796{
John Kessenichf7497e22016-03-08 21:36:22 -0700797 // uniform and buffer blocks are included, unless it is a push_constant
John Kessenich6c292d32016-02-15 20:58:50 -0700798 if (type.getBasicType() == glslang::EbtBlock)
John Kessenichf7497e22016-03-08 21:36:22 -0700799 return type.getQualifier().isUniformOrBuffer() && ! type.getQualifier().layoutPushConstant;
John Kessenich6c292d32016-02-15 20:58:50 -0700800
801 // non block...
802 // basically samplerXXX/subpass/sampler/texture are all included
803 // if they are the global-scope-class, not the function parameter
804 // (or local, if they ever exist) class.
805 if (type.getBasicType() == glslang::EbtSampler)
806 return type.getQualifier().isUniformOrBuffer();
807
808 // None of the above.
809 return false;
810}
811
John Kesseniche0b6cad2015-12-24 10:30:13 -0700812void InheritQualifiers(glslang::TQualifier& child, const glslang::TQualifier& parent)
813{
814 if (child.layoutMatrix == glslang::ElmNone)
815 child.layoutMatrix = parent.layoutMatrix;
816
817 if (parent.invariant)
818 child.invariant = true;
819 if (parent.nopersp)
820 child.nopersp = true;
Rex Xu9d93a232016-05-05 12:30:44 +0800821#ifdef AMD_EXTENSIONS
822 if (parent.explicitInterp)
823 child.explicitInterp = true;
824#endif
John Kesseniche0b6cad2015-12-24 10:30:13 -0700825 if (parent.flat)
826 child.flat = true;
827 if (parent.centroid)
828 child.centroid = true;
829 if (parent.patch)
830 child.patch = true;
831 if (parent.sample)
832 child.sample = true;
Rex Xu1da878f2016-02-21 20:59:01 +0800833 if (parent.coherent)
834 child.coherent = true;
835 if (parent.volatil)
836 child.volatil = true;
837 if (parent.restrict)
838 child.restrict = true;
839 if (parent.readonly)
840 child.readonly = true;
841 if (parent.writeonly)
842 child.writeonly = true;
John Kesseniche0b6cad2015-12-24 10:30:13 -0700843}
844
John Kessenichf2b7f332016-09-01 17:05:23 -0600845bool HasNonLayoutQualifiers(const glslang::TType& type, const glslang::TQualifier& qualifier)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700846{
John Kessenich7b9fa252016-01-21 18:56:57 -0700847 // This should list qualifiers that simultaneous satisfy:
John Kessenichf2b7f332016-09-01 17:05:23 -0600848 // - struct members might inherit from a struct declaration
849 // (note that non-block structs don't explicitly inherit,
850 // only implicitly, meaning no decoration involved)
851 // - affect decorations on the struct members
852 // (note smooth does not, and expecting something like volatile
853 // to effect the whole object)
John Kesseniche0b6cad2015-12-24 10:30:13 -0700854 // - are not part of the offset/st430/etc or row/column-major layout
John Kessenichf2b7f332016-09-01 17:05:23 -0600855 return qualifier.invariant || (qualifier.hasLocation() && type.getBasicType() == glslang::EbtBlock);
John Kesseniche0b6cad2015-12-24 10:30:13 -0700856}
857
John Kessenich140f3df2015-06-26 16:58:36 -0600858//
859// Implement the TGlslangToSpvTraverser class.
860//
861
John Kessenich121853f2017-05-31 17:11:16 -0600862TGlslangToSpvTraverser::TGlslangToSpvTraverser(const glslang::TIntermediate* glslangIntermediate,
863 spv::SpvBuildLogger* buildLogger, glslang::SpvOptions& options)
864 : TIntermTraverser(true, false, true),
865 options(options),
866 shaderEntry(nullptr), currentFunction(nullptr),
John Kesseniched33e052016-10-06 12:59:51 -0600867 sequenceDepth(0), logger(buildLogger),
Lei Zhang17535f72016-05-04 15:55:59 -0400868 builder((glslang::GetKhronosToolId() << 16) | GeneratorVersion, logger),
John Kessenich517fe7a2016-11-26 13:31:47 -0700869 inEntryPoint(false), entryPointTerminated(false), linkageOnly(false),
John Kessenich140f3df2015-06-26 16:58:36 -0600870 glslangIntermediate(glslangIntermediate)
871{
872 spv::ExecutionModel executionModel = TranslateExecutionModel(glslangIntermediate->getStage());
873
874 builder.clearAccessChain();
John Kessenich2a271162017-07-20 20:00:36 -0600875 builder.setSource(TranslateSourceLanguage(glslangIntermediate->getSource(), glslangIntermediate->getProfile()),
876 glslangIntermediate->getVersion());
877
John Kessenich121853f2017-05-31 17:11:16 -0600878 if (options.generateDebugInfo) {
John Kesseniche485c7a2017-05-31 18:50:53 -0600879 builder.setEmitOpLines();
John Kessenich2a271162017-07-20 20:00:36 -0600880 builder.setSourceFile(glslangIntermediate->getSourceFile());
881
882 // Set the source shader's text. If for SPV version 1.0, include
883 // a preamble in comments stating the OpModuleProcessed instructions.
884 // Otherwise, emit those as actual instructions.
885 std::string text;
886 const std::vector<std::string>& processes = glslangIntermediate->getProcesses();
887 for (int p = 0; p < (int)processes.size(); ++p) {
888 if (glslangIntermediate->getSpv().spv < 0x00010100) {
889 text.append("// OpModuleProcessed ");
890 text.append(processes[p]);
891 text.append("\n");
892 } else
893 builder.addModuleProcessed(processes[p]);
894 }
895 if (glslangIntermediate->getSpv().spv < 0x00010100 && (int)processes.size() > 0)
896 text.append("#line 1\n");
897 text.append(glslangIntermediate->getSourceText());
898 builder.setSourceText(text);
John Kessenich121853f2017-05-31 17:11:16 -0600899 }
John Kessenich140f3df2015-06-26 16:58:36 -0600900 stdBuiltins = builder.import("GLSL.std.450");
901 builder.setMemoryModel(spv::AddressingModelLogical, spv::MemoryModelGLSL450);
John Kessenicheee9d532016-09-19 18:09:30 -0600902 shaderEntry = builder.makeEntryPoint(glslangIntermediate->getEntryPointName().c_str());
903 entryPoint = builder.addEntryPoint(executionModel, shaderEntry, glslangIntermediate->getEntryPointName().c_str());
John Kessenich140f3df2015-06-26 16:58:36 -0600904
905 // Add the source extensions
John Kessenich2f273362015-07-18 22:34:27 -0600906 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
907 for (auto it = sourceExtensions.begin(); it != sourceExtensions.end(); ++it)
John Kessenich140f3df2015-06-26 16:58:36 -0600908 builder.addSourceExtension(it->c_str());
909
910 // Add the top-level modes for this shader.
911
John Kessenich92187592016-02-01 13:45:25 -0700912 if (glslangIntermediate->getXfbMode()) {
913 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -0600914 builder.addExecutionMode(shaderEntry, spv::ExecutionModeXfb);
John Kessenich92187592016-02-01 13:45:25 -0700915 }
John Kessenich140f3df2015-06-26 16:58:36 -0600916
917 unsigned int mode;
918 switch (glslangIntermediate->getStage()) {
919 case EShLangVertex:
John Kessenich5e4b1242015-08-06 22:53:06 -0600920 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600921 break;
922
steve-lunarge7412492017-03-23 11:56:07 -0600923 case EShLangTessEvaluation:
John Kessenich140f3df2015-06-26 16:58:36 -0600924 case EShLangTessControl:
John Kessenich5e4b1242015-08-06 22:53:06 -0600925 builder.addCapability(spv::CapabilityTessellation);
John Kessenich140f3df2015-06-26 16:58:36 -0600926
steve-lunarge7412492017-03-23 11:56:07 -0600927 glslang::TLayoutGeometry primitive;
928
929 if (glslangIntermediate->getStage() == EShLangTessControl) {
930 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
931 primitive = glslangIntermediate->getOutputPrimitive();
932 } else {
933 primitive = glslangIntermediate->getInputPrimitive();
934 }
935
936 switch (primitive) {
John Kessenich55e7d112015-11-15 21:33:39 -0700937 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
938 case glslang::ElgQuads: mode = spv::ExecutionModeQuads; break;
939 case glslang::ElgIsolines: mode = spv::ExecutionModeIsolines; break;
John Kessenich4016e382016-07-15 11:53:56 -0600940 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600941 }
John Kessenich4016e382016-07-15 11:53:56 -0600942 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600943 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
944
John Kesseniche6903322015-10-13 16:29:02 -0600945 switch (glslangIntermediate->getVertexSpacing()) {
946 case glslang::EvsEqual: mode = spv::ExecutionModeSpacingEqual; break;
947 case glslang::EvsFractionalEven: mode = spv::ExecutionModeSpacingFractionalEven; break;
948 case glslang::EvsFractionalOdd: mode = spv::ExecutionModeSpacingFractionalOdd; break;
John Kessenich4016e382016-07-15 11:53:56 -0600949 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600950 }
John Kessenich4016e382016-07-15 11:53:56 -0600951 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600952 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
953
954 switch (glslangIntermediate->getVertexOrder()) {
955 case glslang::EvoCw: mode = spv::ExecutionModeVertexOrderCw; break;
956 case glslang::EvoCcw: mode = spv::ExecutionModeVertexOrderCcw; break;
John Kessenich4016e382016-07-15 11:53:56 -0600957 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -0600958 }
John Kessenich4016e382016-07-15 11:53:56 -0600959 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -0600960 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
961
962 if (glslangIntermediate->getPointMode())
963 builder.addExecutionMode(shaderEntry, spv::ExecutionModePointMode);
John Kessenich140f3df2015-06-26 16:58:36 -0600964 break;
965
966 case EShLangGeometry:
John Kessenich5e4b1242015-08-06 22:53:06 -0600967 builder.addCapability(spv::CapabilityGeometry);
John Kessenich140f3df2015-06-26 16:58:36 -0600968 switch (glslangIntermediate->getInputPrimitive()) {
969 case glslang::ElgPoints: mode = spv::ExecutionModeInputPoints; break;
970 case glslang::ElgLines: mode = spv::ExecutionModeInputLines; break;
971 case glslang::ElgLinesAdjacency: mode = spv::ExecutionModeInputLinesAdjacency; break;
John Kessenich55e7d112015-11-15 21:33:39 -0700972 case glslang::ElgTriangles: mode = spv::ExecutionModeTriangles; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600973 case glslang::ElgTrianglesAdjacency: mode = spv::ExecutionModeInputTrianglesAdjacency; break;
John Kessenich4016e382016-07-15 11:53:56 -0600974 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600975 }
John Kessenich4016e382016-07-15 11:53:56 -0600976 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600977 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
John Kesseniche6903322015-10-13 16:29:02 -0600978
John Kessenich140f3df2015-06-26 16:58:36 -0600979 builder.addExecutionMode(shaderEntry, spv::ExecutionModeInvocations, glslangIntermediate->getInvocations());
980
981 switch (glslangIntermediate->getOutputPrimitive()) {
982 case glslang::ElgPoints: mode = spv::ExecutionModeOutputPoints; break;
983 case glslang::ElgLineStrip: mode = spv::ExecutionModeOutputLineStrip; break;
984 case glslang::ElgTriangleStrip: mode = spv::ExecutionModeOutputTriangleStrip; break;
John Kessenich4016e382016-07-15 11:53:56 -0600985 default: mode = spv::ExecutionModeMax; break;
John Kessenich140f3df2015-06-26 16:58:36 -0600986 }
John Kessenich4016e382016-07-15 11:53:56 -0600987 if (mode != spv::ExecutionModeMax)
John Kessenich140f3df2015-06-26 16:58:36 -0600988 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
989 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOutputVertices, glslangIntermediate->getVertices());
990 break;
991
992 case EShLangFragment:
John Kessenich5e4b1242015-08-06 22:53:06 -0600993 builder.addCapability(spv::CapabilityShader);
John Kessenich140f3df2015-06-26 16:58:36 -0600994 if (glslangIntermediate->getPixelCenterInteger())
995 builder.addExecutionMode(shaderEntry, spv::ExecutionModePixelCenterInteger);
John Kesseniche6903322015-10-13 16:29:02 -0600996
John Kessenich140f3df2015-06-26 16:58:36 -0600997 if (glslangIntermediate->getOriginUpperLeft())
998 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginUpperLeft);
John Kessenich5e4b1242015-08-06 22:53:06 -0600999 else
1000 builder.addExecutionMode(shaderEntry, spv::ExecutionModeOriginLowerLeft);
John Kesseniche6903322015-10-13 16:29:02 -06001001
1002 if (glslangIntermediate->getEarlyFragmentTests())
1003 builder.addExecutionMode(shaderEntry, spv::ExecutionModeEarlyFragmentTests);
1004
chaocc1204522017-06-30 17:14:30 -07001005 if (glslangIntermediate->getPostDepthCoverage()) {
1006 builder.addCapability(spv::CapabilitySampleMaskPostDepthCoverage);
1007 builder.addExecutionMode(shaderEntry, spv::ExecutionModePostDepthCoverage);
1008 builder.addExtension(spv::E_SPV_KHR_post_depth_coverage);
1009 }
1010
John Kesseniche6903322015-10-13 16:29:02 -06001011 switch(glslangIntermediate->getDepth()) {
John Kesseniche6903322015-10-13 16:29:02 -06001012 case glslang::EldGreater: mode = spv::ExecutionModeDepthGreater; break;
1013 case glslang::EldLess: mode = spv::ExecutionModeDepthLess; break;
John Kessenich4016e382016-07-15 11:53:56 -06001014 default: mode = spv::ExecutionModeMax; break;
John Kesseniche6903322015-10-13 16:29:02 -06001015 }
John Kessenich4016e382016-07-15 11:53:56 -06001016 if (mode != spv::ExecutionModeMax)
John Kesseniche6903322015-10-13 16:29:02 -06001017 builder.addExecutionMode(shaderEntry, (spv::ExecutionMode)mode);
1018
1019 if (glslangIntermediate->getDepth() != glslang::EldUnchanged && glslangIntermediate->isDepthReplacing())
1020 builder.addExecutionMode(shaderEntry, spv::ExecutionModeDepthReplacing);
John Kessenich140f3df2015-06-26 16:58:36 -06001021 break;
1022
1023 case EShLangCompute:
John Kessenich5e4b1242015-08-06 22:53:06 -06001024 builder.addCapability(spv::CapabilityShader);
John Kessenichb56a26a2015-09-16 16:04:05 -06001025 builder.addExecutionMode(shaderEntry, spv::ExecutionModeLocalSize, glslangIntermediate->getLocalSize(0),
1026 glslangIntermediate->getLocalSize(1),
1027 glslangIntermediate->getLocalSize(2));
John Kessenich140f3df2015-06-26 16:58:36 -06001028 break;
1029
1030 default:
1031 break;
1032 }
John Kessenich140f3df2015-06-26 16:58:36 -06001033}
1034
John Kessenichfca82622016-11-26 13:23:20 -07001035// Finish creating SPV, after the traversal is complete.
1036void TGlslangToSpvTraverser::finishSpv()
John Kessenich7ba63412015-12-20 17:37:07 -07001037{
John Kessenich517fe7a2016-11-26 13:31:47 -07001038 if (! entryPointTerminated) {
John Kessenichfca82622016-11-26 13:23:20 -07001039 builder.setBuildPoint(shaderEntry->getLastBlock());
1040 builder.leaveFunction();
1041 }
1042
John Kessenich7ba63412015-12-20 17:37:07 -07001043 // finish off the entry-point SPV instruction by adding the Input/Output <id>
rdb32084e82016-02-23 22:17:38 +01001044 for (auto it = iOSet.cbegin(); it != iOSet.cend(); ++it)
1045 entryPoint->addIdOperand(*it);
John Kessenich7ba63412015-12-20 17:37:07 -07001046
qiningda397332016-03-09 19:54:03 -05001047 builder.eliminateDeadDecorations();
John Kessenich7ba63412015-12-20 17:37:07 -07001048}
1049
John Kessenichfca82622016-11-26 13:23:20 -07001050// Write the SPV into 'out'.
1051void TGlslangToSpvTraverser::dumpSpv(std::vector<unsigned int>& out)
John Kessenich140f3df2015-06-26 16:58:36 -06001052{
John Kessenichfca82622016-11-26 13:23:20 -07001053 builder.dump(out);
John Kessenich140f3df2015-06-26 16:58:36 -06001054}
1055
1056//
1057// Implement the traversal functions.
1058//
1059// Return true from interior nodes to have the external traversal
1060// continue on to children. Return false if children were
1061// already processed.
1062//
1063
1064//
qining25262b32016-05-06 17:25:16 -04001065// Symbols can turn into
John Kessenich140f3df2015-06-26 16:58:36 -06001066// - uniform/input reads
1067// - output writes
1068// - complex lvalue base setups: foo.bar[3].... , where we see foo and start up an access chain
1069// - something simple that degenerates into the last bullet
1070//
1071void TGlslangToSpvTraverser::visitSymbol(glslang::TIntermSymbol* symbol)
1072{
qining75d1d802016-04-06 14:42:01 -04001073 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1074 if (symbol->getType().getQualifier().isSpecConstant())
1075 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1076
John Kessenich140f3df2015-06-26 16:58:36 -06001077 // getSymbolId() will set up all the IO decorations on the first call.
1078 // Formal function parameters were mapped during makeFunctions().
1079 spv::Id id = getSymbolId(symbol);
John Kessenich7ba63412015-12-20 17:37:07 -07001080
1081 // Include all "static use" and "linkage only" interface variables on the OpEntryPoint instruction
1082 if (builder.isPointer(id)) {
1083 spv::StorageClass sc = builder.getStorageClass(id);
John Kessenich5f77d862017-09-19 11:09:59 -06001084 if (sc == spv::StorageClassInput || sc == spv::StorageClassOutput) {
1085 if (!symbol->getType().isStruct() || symbol->getType().getStruct()->size() > 0)
1086 iOSet.insert(id);
1087 }
John Kessenich7ba63412015-12-20 17:37:07 -07001088 }
1089
1090 // Only process non-linkage-only nodes for generating actual static uses
John Kessenich6c292d32016-02-15 20:58:50 -07001091 if (! linkageOnly || symbol->getQualifier().isSpecConstant()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001092 // Prepare to generate code for the access
1093
1094 // L-value chains will be computed left to right. We're on the symbol now,
1095 // which is the left-most part of the access chain, so now is "clear" time,
1096 // followed by setting the base.
1097 builder.clearAccessChain();
1098
1099 // For now, we consider all user variables as being in memory, so they are pointers,
John Kessenich6c292d32016-02-15 20:58:50 -07001100 // except for
John Kessenich4bf71552016-09-02 11:20:21 -06001101 // A) R-Value arguments to a function, which are an intermediate object.
John Kessenich6c292d32016-02-15 20:58:50 -07001102 // See comments in handleUserFunctionCall().
John Kessenich4bf71552016-09-02 11:20:21 -06001103 // B) Specialization constants (normal constants don't even come in as a variable),
John Kessenich6c292d32016-02-15 20:58:50 -07001104 // These are also pure R-values.
1105 glslang::TQualifier qualifier = symbol->getQualifier();
John Kessenich4bf71552016-09-02 11:20:21 -06001106 if (qualifier.isSpecConstant() || rValueParameters.find(symbol->getId()) != rValueParameters.end())
John Kessenich140f3df2015-06-26 16:58:36 -06001107 builder.setAccessChainRValue(id);
1108 else
1109 builder.setAccessChainLValue(id);
1110 }
1111}
1112
1113bool TGlslangToSpvTraverser::visitBinary(glslang::TVisit /* visit */, glslang::TIntermBinary* node)
1114{
John Kesseniche485c7a2017-05-31 18:50:53 -06001115 builder.setLine(node->getLoc().line);
1116
qining40887662016-04-03 22:20:42 -04001117 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1118 if (node->getType().getQualifier().isSpecConstant())
1119 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1120
John Kessenich140f3df2015-06-26 16:58:36 -06001121 // First, handle special cases
1122 switch (node->getOp()) {
1123 case glslang::EOpAssign:
1124 case glslang::EOpAddAssign:
1125 case glslang::EOpSubAssign:
1126 case glslang::EOpMulAssign:
1127 case glslang::EOpVectorTimesMatrixAssign:
1128 case glslang::EOpVectorTimesScalarAssign:
1129 case glslang::EOpMatrixTimesScalarAssign:
1130 case glslang::EOpMatrixTimesMatrixAssign:
1131 case glslang::EOpDivAssign:
1132 case glslang::EOpModAssign:
1133 case glslang::EOpAndAssign:
1134 case glslang::EOpInclusiveOrAssign:
1135 case glslang::EOpExclusiveOrAssign:
1136 case glslang::EOpLeftShiftAssign:
1137 case glslang::EOpRightShiftAssign:
1138 // A bin-op assign "a += b" means the same thing as "a = a + b"
1139 // where a is evaluated before b. For a simple assignment, GLSL
1140 // says to evaluate the left before the right. So, always, left
1141 // node then right node.
1142 {
1143 // get the left l-value, save it away
1144 builder.clearAccessChain();
1145 node->getLeft()->traverse(this);
1146 spv::Builder::AccessChain lValue = builder.getAccessChain();
1147
1148 // evaluate the right
1149 builder.clearAccessChain();
1150 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001151 spv::Id rValue = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001152
1153 if (node->getOp() != glslang::EOpAssign) {
1154 // the left is also an r-value
1155 builder.setAccessChain(lValue);
John Kessenich32cfd492016-02-02 12:37:46 -07001156 spv::Id leftRValue = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001157
1158 // do the operation
John Kessenichf6640762016-08-01 19:44:00 -06001159 rValue = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001160 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich140f3df2015-06-26 16:58:36 -06001161 convertGlslangToSpvType(node->getType()), leftRValue, rValue,
1162 node->getType().getBasicType());
1163
1164 // these all need their counterparts in createBinaryOperation()
John Kessenich55e7d112015-11-15 21:33:39 -07001165 assert(rValue != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001166 }
1167
1168 // store the result
1169 builder.setAccessChain(lValue);
John Kessenich4bf71552016-09-02 11:20:21 -06001170 multiTypeStore(node->getType(), rValue);
John Kessenich140f3df2015-06-26 16:58:36 -06001171
1172 // assignments are expressions having an rValue after they are evaluated...
1173 builder.clearAccessChain();
1174 builder.setAccessChainRValue(rValue);
1175 }
1176 return false;
1177 case glslang::EOpIndexDirect:
1178 case glslang::EOpIndexDirectStruct:
1179 {
1180 // Get the left part of the access chain.
1181 node->getLeft()->traverse(this);
1182
1183 // Add the next element in the chain
1184
David Netoa901ffe2016-06-08 14:11:40 +01001185 const int glslangIndex = node->getRight()->getAsConstantUnion()->getConstArray()[0].getIConst();
John Kessenich140f3df2015-06-26 16:58:36 -06001186 if (! node->getLeft()->getType().isArray() &&
1187 node->getLeft()->getType().isVector() &&
1188 node->getOp() == glslang::EOpIndexDirect) {
1189 // This is essentially a hard-coded vector swizzle of size 1,
1190 // so short circuit the access-chain stuff with a swizzle.
1191 std::vector<unsigned> swizzle;
David Netoa901ffe2016-06-08 14:11:40 +01001192 swizzle.push_back(glslangIndex);
John Kessenichfa668da2015-09-13 14:46:30 -06001193 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001194 } else {
David Netoa901ffe2016-06-08 14:11:40 +01001195 int spvIndex = glslangIndex;
1196 if (node->getLeft()->getBasicType() == glslang::EbtBlock &&
1197 node->getOp() == glslang::EOpIndexDirectStruct)
1198 {
1199 // This may be, e.g., an anonymous block-member selection, which generally need
1200 // index remapping due to hidden members in anonymous blocks.
1201 std::vector<int>& remapper = memberRemapper[node->getLeft()->getType().getStruct()];
1202 assert(remapper.size() > 0);
1203 spvIndex = remapper[glslangIndex];
1204 }
John Kessenichebb50532016-05-16 19:22:05 -06001205
David Netoa901ffe2016-06-08 14:11:40 +01001206 // normal case for indexing array or structure or block
1207 builder.accessChainPush(builder.makeIntConstant(spvIndex));
1208
1209 // Add capabilities here for accessing PointSize and clip/cull distance.
1210 // We have deferred generation of associated capabilities until now.
John Kessenichebb50532016-05-16 19:22:05 -06001211 if (node->getLeft()->getType().isStruct() && ! node->getLeft()->getType().isArray())
David Netoa901ffe2016-06-08 14:11:40 +01001212 declareUseOfStructMember(*(node->getLeft()->getType().getStruct()), glslangIndex);
John Kessenich140f3df2015-06-26 16:58:36 -06001213 }
1214 }
1215 return false;
1216 case glslang::EOpIndexIndirect:
1217 {
1218 // Structure or array or vector indirection.
1219 // Will use native SPIR-V access-chain for struct and array indirection;
1220 // matrices are arrays of vectors, so will also work for a matrix.
1221 // Will use the access chain's 'component' for variable index into a vector.
1222
1223 // This adapter is building access chains left to right.
1224 // Set up the access chain to the left.
1225 node->getLeft()->traverse(this);
1226
1227 // save it so that computing the right side doesn't trash it
1228 spv::Builder::AccessChain partial = builder.getAccessChain();
1229
1230 // compute the next index in the chain
1231 builder.clearAccessChain();
1232 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001233 spv::Id index = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001234
1235 // restore the saved access chain
1236 builder.setAccessChain(partial);
1237
1238 if (! node->getLeft()->getType().isArray() && node->getLeft()->getType().isVector())
John Kessenichfa668da2015-09-13 14:46:30 -06001239 builder.accessChainPushComponent(index, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001240 else
John Kessenichfa668da2015-09-13 14:46:30 -06001241 builder.accessChainPush(index);
John Kessenich140f3df2015-06-26 16:58:36 -06001242 }
1243 return false;
1244 case glslang::EOpVectorSwizzle:
1245 {
1246 node->getLeft()->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001247 std::vector<unsigned> swizzle;
John Kessenich8c8505c2016-07-26 12:50:38 -06001248 convertSwizzle(*node->getRight()->getAsAggregate(), swizzle);
John Kessenichfa668da2015-09-13 14:46:30 -06001249 builder.accessChainPushSwizzle(swizzle, convertGlslangToSpvType(node->getLeft()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06001250 }
1251 return false;
John Kessenichfdf63472017-01-13 12:27:52 -07001252 case glslang::EOpMatrixSwizzle:
1253 logger->missingFunctionality("matrix swizzle");
1254 return true;
John Kessenich7c1aa102015-10-15 13:29:11 -06001255 case glslang::EOpLogicalOr:
1256 case glslang::EOpLogicalAnd:
1257 {
1258
1259 // These may require short circuiting, but can sometimes be done as straight
1260 // binary operations. The right operand must be short circuited if it has
1261 // side effects, and should probably be if it is complex.
1262 if (isTrivial(node->getRight()->getAsTyped()))
1263 break; // handle below as a normal binary operation
1264 // otherwise, we need to do dynamic short circuiting on the right operand
1265 spv::Id result = createShortCircuit(node->getOp(), *node->getLeft()->getAsTyped(), *node->getRight()->getAsTyped());
1266 builder.clearAccessChain();
1267 builder.setAccessChainRValue(result);
1268 }
1269 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001270 default:
1271 break;
1272 }
1273
1274 // Assume generic binary op...
1275
John Kessenich32cfd492016-02-02 12:37:46 -07001276 // get right operand
John Kessenich140f3df2015-06-26 16:58:36 -06001277 builder.clearAccessChain();
1278 node->getLeft()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001279 spv::Id left = accessChainLoad(node->getLeft()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001280
John Kessenich32cfd492016-02-02 12:37:46 -07001281 // get left operand
John Kessenich140f3df2015-06-26 16:58:36 -06001282 builder.clearAccessChain();
1283 node->getRight()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001284 spv::Id right = accessChainLoad(node->getRight()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001285
John Kessenich32cfd492016-02-02 12:37:46 -07001286 // get result
John Kessenichf6640762016-08-01 19:44:00 -06001287 spv::Id result = createBinaryOperation(node->getOp(), TranslatePrecisionDecoration(node->getOperationPrecision()),
qining25262b32016-05-06 17:25:16 -04001288 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich32cfd492016-02-02 12:37:46 -07001289 convertGlslangToSpvType(node->getType()), left, right,
1290 node->getLeft()->getType().getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001291
John Kessenich50e57562015-12-21 21:21:11 -07001292 builder.clearAccessChain();
John Kessenich140f3df2015-06-26 16:58:36 -06001293 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001294 logger->missingFunctionality("unknown glslang binary operation");
John Kessenich50e57562015-12-21 21:21:11 -07001295 return true; // pick up a child as the place-holder result
John Kessenich140f3df2015-06-26 16:58:36 -06001296 } else {
John Kessenich140f3df2015-06-26 16:58:36 -06001297 builder.setAccessChainRValue(result);
John Kessenich140f3df2015-06-26 16:58:36 -06001298 return false;
1299 }
John Kessenich140f3df2015-06-26 16:58:36 -06001300}
1301
1302bool TGlslangToSpvTraverser::visitUnary(glslang::TVisit /* visit */, glslang::TIntermUnary* node)
1303{
John Kesseniche485c7a2017-05-31 18:50:53 -06001304 builder.setLine(node->getLoc().line);
1305
qining40887662016-04-03 22:20:42 -04001306 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1307 if (node->getType().getQualifier().isSpecConstant())
1308 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1309
John Kessenichfc51d282015-08-19 13:34:18 -06001310 spv::Id result = spv::NoResult;
1311
1312 // try texturing first
1313 result = createImageTextureFunctionCall(node);
1314 if (result != spv::NoResult) {
1315 builder.clearAccessChain();
1316 builder.setAccessChainRValue(result);
1317
1318 return false; // done with this node
1319 }
1320
1321 // Non-texturing.
John Kessenichc9a80832015-09-12 12:17:44 -06001322
1323 if (node->getOp() == glslang::EOpArrayLength) {
1324 // Quite special; won't want to evaluate the operand.
1325
1326 // Normal .length() would have been constant folded by the front-end.
1327 // So, this has to be block.lastMember.length().
John Kessenichee21fc92015-09-21 21:50:29 -06001328 // SPV wants "block" and member number as the operands, go get them.
John Kessenichc9a80832015-09-12 12:17:44 -06001329 assert(node->getOperand()->getType().isRuntimeSizedArray());
1330 glslang::TIntermTyped* block = node->getOperand()->getAsBinaryNode()->getLeft();
1331 block->traverse(this);
John Kessenichee21fc92015-09-21 21:50:29 -06001332 unsigned int member = node->getOperand()->getAsBinaryNode()->getRight()->getAsConstantUnion()->getConstArray()[0].getUConst();
1333 spv::Id length = builder.createArrayLength(builder.accessChainGetLValue(), member);
John Kessenichc9a80832015-09-12 12:17:44 -06001334
1335 builder.clearAccessChain();
1336 builder.setAccessChainRValue(length);
1337
1338 return false;
1339 }
1340
John Kessenichfc51d282015-08-19 13:34:18 -06001341 // Start by evaluating the operand
1342
John Kessenich8c8505c2016-07-26 12:50:38 -06001343 // Does it need a swizzle inversion? If so, evaluation is inverted;
1344 // operate first on the swizzle base, then apply the swizzle.
1345 spv::Id invertedType = spv::NoType;
1346 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
1347 if (node->getOp() == glslang::EOpInterpolateAtCentroid)
1348 invertedType = getInvertedSwizzleType(*node->getOperand());
1349
John Kessenich140f3df2015-06-26 16:58:36 -06001350 builder.clearAccessChain();
John Kessenich8c8505c2016-07-26 12:50:38 -06001351 if (invertedType != spv::NoType)
1352 node->getOperand()->getAsBinaryNode()->getLeft()->traverse(this);
1353 else
1354 node->getOperand()->traverse(this);
Rex Xu30f92582015-09-14 10:38:56 +08001355
Rex Xufc618912015-09-09 16:42:49 +08001356 spv::Id operand = spv::NoResult;
1357
1358 if (node->getOp() == glslang::EOpAtomicCounterIncrement ||
1359 node->getOp() == glslang::EOpAtomicCounterDecrement ||
Rex Xu7a26c172015-12-08 17:12:09 +08001360 node->getOp() == glslang::EOpAtomicCounter ||
1361 node->getOp() == glslang::EOpInterpolateAtCentroid)
Rex Xufc618912015-09-09 16:42:49 +08001362 operand = builder.accessChainGetLValue(); // Special case l-value operands
1363 else
John Kessenich32cfd492016-02-02 12:37:46 -07001364 operand = accessChainLoad(node->getOperand()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001365
John Kessenichf6640762016-08-01 19:44:00 -06001366 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
qining25262b32016-05-06 17:25:16 -04001367 spv::Decoration noContraction = TranslateNoContractionDecoration(node->getType().getQualifier());
John Kessenich140f3df2015-06-26 16:58:36 -06001368
1369 // it could be a conversion
John Kessenichfc51d282015-08-19 13:34:18 -06001370 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001371 result = createConversion(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001372
1373 // if not, then possibly an operation
1374 if (! result)
John Kessenich8c8505c2016-07-26 12:50:38 -06001375 result = createUnaryOperation(node->getOp(), precision, noContraction, resultType(), operand, node->getOperand()->getBasicType());
John Kessenich140f3df2015-06-26 16:58:36 -06001376
1377 if (result) {
John Kessenich8c8505c2016-07-26 12:50:38 -06001378 if (invertedType)
1379 result = createInvertedSwizzle(precision, *node->getOperand(), result);
1380
John Kessenich140f3df2015-06-26 16:58:36 -06001381 builder.clearAccessChain();
1382 builder.setAccessChainRValue(result);
1383
1384 return false; // done with this node
1385 }
1386
1387 // it must be a special case, check...
1388 switch (node->getOp()) {
1389 case glslang::EOpPostIncrement:
1390 case glslang::EOpPostDecrement:
1391 case glslang::EOpPreIncrement:
1392 case glslang::EOpPreDecrement:
1393 {
1394 // we need the integer value "1" or the floating point "1.0" to add/subtract
Rex Xu8ff43de2016-04-22 16:51:45 +08001395 spv::Id one = 0;
1396 if (node->getBasicType() == glslang::EbtFloat)
1397 one = builder.makeFloatConstant(1.0F);
Rex Xuce31aea2016-07-29 16:13:04 +08001398 else if (node->getBasicType() == glslang::EbtDouble)
1399 one = builder.makeDoubleConstant(1.0);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001400#ifdef AMD_EXTENSIONS
1401 else if (node->getBasicType() == glslang::EbtFloat16)
1402 one = builder.makeFloat16Constant(1.0F);
1403#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001404 else if (node->getBasicType() == glslang::EbtInt64 || node->getBasicType() == glslang::EbtUint64)
1405 one = builder.makeInt64Constant(1);
Rex Xucabbb782017-03-24 13:41:14 +08001406#ifdef AMD_EXTENSIONS
1407 else if (node->getBasicType() == glslang::EbtInt16 || node->getBasicType() == glslang::EbtUint16)
1408 one = builder.makeInt16Constant(1);
1409#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08001410 else
1411 one = builder.makeIntConstant(1);
John Kessenich140f3df2015-06-26 16:58:36 -06001412 glslang::TOperator op;
1413 if (node->getOp() == glslang::EOpPreIncrement ||
1414 node->getOp() == glslang::EOpPostIncrement)
1415 op = glslang::EOpAdd;
1416 else
1417 op = glslang::EOpSub;
1418
John Kessenichf6640762016-08-01 19:44:00 -06001419 spv::Id result = createBinaryOperation(op, precision,
qining25262b32016-05-06 17:25:16 -04001420 TranslateNoContractionDecoration(node->getType().getQualifier()),
Rex Xu8ff43de2016-04-22 16:51:45 +08001421 convertGlslangToSpvType(node->getType()), operand, one,
1422 node->getType().getBasicType());
John Kessenich55e7d112015-11-15 21:33:39 -07001423 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001424
1425 // The result of operation is always stored, but conditionally the
1426 // consumed result. The consumed result is always an r-value.
1427 builder.accessChainStore(result);
1428 builder.clearAccessChain();
1429 if (node->getOp() == glslang::EOpPreIncrement ||
1430 node->getOp() == glslang::EOpPreDecrement)
1431 builder.setAccessChainRValue(result);
1432 else
1433 builder.setAccessChainRValue(operand);
1434 }
1435
1436 return false;
1437
1438 case glslang::EOpEmitStreamVertex:
1439 builder.createNoResultOp(spv::OpEmitStreamVertex, operand);
1440 return false;
1441 case glslang::EOpEndStreamPrimitive:
1442 builder.createNoResultOp(spv::OpEndStreamPrimitive, operand);
1443 return false;
1444
1445 default:
Lei Zhang17535f72016-05-04 15:55:59 -04001446 logger->missingFunctionality("unknown glslang unary");
John Kessenich50e57562015-12-21 21:21:11 -07001447 return true; // pick up operand as placeholder result
John Kessenich140f3df2015-06-26 16:58:36 -06001448 }
John Kessenich140f3df2015-06-26 16:58:36 -06001449}
1450
1451bool TGlslangToSpvTraverser::visitAggregate(glslang::TVisit visit, glslang::TIntermAggregate* node)
1452{
qining27e04a02016-04-14 16:40:20 -04001453 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1454 if (node->getType().getQualifier().isSpecConstant())
1455 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1456
John Kessenichfc51d282015-08-19 13:34:18 -06001457 spv::Id result = spv::NoResult;
John Kessenich8c8505c2016-07-26 12:50:38 -06001458 spv::Id invertedType = spv::NoType; // to use to override the natural type of the node
1459 auto resultType = [&invertedType, &node, this](){ return invertedType != spv::NoType ? invertedType : convertGlslangToSpvType(node->getType()); };
John Kessenichfc51d282015-08-19 13:34:18 -06001460
1461 // try texturing
1462 result = createImageTextureFunctionCall(node);
1463 if (result != spv::NoResult) {
1464 builder.clearAccessChain();
1465 builder.setAccessChainRValue(result);
1466
1467 return false;
Rex Xu129799a2017-07-05 17:23:28 +08001468#ifdef AMD_EXTENSIONS
1469 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
1470#else
John Kessenich56bab042015-09-16 10:54:31 -06001471 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08001472#endif
Rex Xufc618912015-09-09 16:42:49 +08001473 // "imageStore" is a special case, which has no result
1474 return false;
1475 }
John Kessenichfc51d282015-08-19 13:34:18 -06001476
John Kessenich140f3df2015-06-26 16:58:36 -06001477 glslang::TOperator binOp = glslang::EOpNull;
1478 bool reduceComparison = true;
1479 bool isMatrix = false;
1480 bool noReturnValue = false;
John Kessenich426394d2015-07-23 10:22:48 -06001481 bool atomic = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001482
1483 assert(node->getOp());
1484
John Kessenichf6640762016-08-01 19:44:00 -06001485 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenich140f3df2015-06-26 16:58:36 -06001486
1487 switch (node->getOp()) {
1488 case glslang::EOpSequence:
1489 {
1490 if (preVisit)
1491 ++sequenceDepth;
1492 else
1493 --sequenceDepth;
1494
1495 if (sequenceDepth == 1) {
1496 // If this is the parent node of all the functions, we want to see them
1497 // early, so all call points have actual SPIR-V functions to reference.
1498 // In all cases, still let the traverser visit the children for us.
1499 makeFunctions(node->getAsAggregate()->getSequence());
1500
John Kessenich6fccb3c2016-09-19 16:01:41 -06001501 // Also, we want all globals initializers to go into the beginning of the entry point, before
John Kessenich140f3df2015-06-26 16:58:36 -06001502 // anything else gets there, so visit out of order, doing them all now.
1503 makeGlobalInitializers(node->getAsAggregate()->getSequence());
1504
John Kessenich6a60c2f2016-12-08 21:01:59 -07001505 // 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 -06001506 // so do them manually.
1507 visitFunctions(node->getAsAggregate()->getSequence());
1508
1509 return false;
1510 }
1511
1512 return true;
1513 }
1514 case glslang::EOpLinkerObjects:
1515 {
1516 if (visit == glslang::EvPreVisit)
1517 linkageOnly = true;
1518 else
1519 linkageOnly = false;
1520
1521 return true;
1522 }
1523 case glslang::EOpComma:
1524 {
1525 // processing from left to right naturally leaves the right-most
1526 // lying around in the access chain
1527 glslang::TIntermSequence& glslangOperands = node->getSequence();
1528 for (int i = 0; i < (int)glslangOperands.size(); ++i)
1529 glslangOperands[i]->traverse(this);
1530
1531 return false;
1532 }
1533 case glslang::EOpFunction:
1534 if (visit == glslang::EvPreVisit) {
John Kessenich6fccb3c2016-09-19 16:01:41 -06001535 if (isShaderEntryPoint(node)) {
John Kessenich517fe7a2016-11-26 13:31:47 -07001536 inEntryPoint = true;
John Kessenich140f3df2015-06-26 16:58:36 -06001537 builder.setBuildPoint(shaderEntry->getLastBlock());
John Kesseniched33e052016-10-06 12:59:51 -06001538 currentFunction = shaderEntry;
John Kessenich140f3df2015-06-26 16:58:36 -06001539 } else {
1540 handleFunctionEntry(node);
1541 }
1542 } else {
John Kessenich517fe7a2016-11-26 13:31:47 -07001543 if (inEntryPoint)
1544 entryPointTerminated = true;
John Kesseniche770b3e2015-09-14 20:58:02 -06001545 builder.leaveFunction();
John Kessenich517fe7a2016-11-26 13:31:47 -07001546 inEntryPoint = false;
John Kessenich140f3df2015-06-26 16:58:36 -06001547 }
1548
1549 return true;
1550 case glslang::EOpParameters:
1551 // Parameters will have been consumed by EOpFunction processing, but not
1552 // the body, so we still visited the function node's children, making this
1553 // child redundant.
1554 return false;
1555 case glslang::EOpFunctionCall:
1556 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001557 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001558 if (node->isUserDefined())
1559 result = handleUserFunctionCall(node);
John Kessenich927608b2017-01-06 12:34:14 -07001560 // 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 -07001561 if (result) {
1562 builder.clearAccessChain();
1563 builder.setAccessChainRValue(result);
1564 } else
Lei Zhang17535f72016-05-04 15:55:59 -04001565 logger->missingFunctionality("missing user function; linker needs to catch that");
John Kessenich140f3df2015-06-26 16:58:36 -06001566
1567 return false;
1568 }
1569 case glslang::EOpConstructMat2x2:
1570 case glslang::EOpConstructMat2x3:
1571 case glslang::EOpConstructMat2x4:
1572 case glslang::EOpConstructMat3x2:
1573 case glslang::EOpConstructMat3x3:
1574 case glslang::EOpConstructMat3x4:
1575 case glslang::EOpConstructMat4x2:
1576 case glslang::EOpConstructMat4x3:
1577 case glslang::EOpConstructMat4x4:
1578 case glslang::EOpConstructDMat2x2:
1579 case glslang::EOpConstructDMat2x3:
1580 case glslang::EOpConstructDMat2x4:
1581 case glslang::EOpConstructDMat3x2:
1582 case glslang::EOpConstructDMat3x3:
1583 case glslang::EOpConstructDMat3x4:
1584 case glslang::EOpConstructDMat4x2:
1585 case glslang::EOpConstructDMat4x3:
1586 case glslang::EOpConstructDMat4x4:
LoopDawg174ccb82017-05-20 21:40:27 -06001587 case glslang::EOpConstructIMat2x2:
1588 case glslang::EOpConstructIMat2x3:
1589 case glslang::EOpConstructIMat2x4:
1590 case glslang::EOpConstructIMat3x2:
1591 case glslang::EOpConstructIMat3x3:
1592 case glslang::EOpConstructIMat3x4:
1593 case glslang::EOpConstructIMat4x2:
1594 case glslang::EOpConstructIMat4x3:
1595 case glslang::EOpConstructIMat4x4:
1596 case glslang::EOpConstructUMat2x2:
1597 case glslang::EOpConstructUMat2x3:
1598 case glslang::EOpConstructUMat2x4:
1599 case glslang::EOpConstructUMat3x2:
1600 case glslang::EOpConstructUMat3x3:
1601 case glslang::EOpConstructUMat3x4:
1602 case glslang::EOpConstructUMat4x2:
1603 case glslang::EOpConstructUMat4x3:
1604 case glslang::EOpConstructUMat4x4:
1605 case glslang::EOpConstructBMat2x2:
1606 case glslang::EOpConstructBMat2x3:
1607 case glslang::EOpConstructBMat2x4:
1608 case glslang::EOpConstructBMat3x2:
1609 case glslang::EOpConstructBMat3x3:
1610 case glslang::EOpConstructBMat3x4:
1611 case glslang::EOpConstructBMat4x2:
1612 case glslang::EOpConstructBMat4x3:
1613 case glslang::EOpConstructBMat4x4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001614#ifdef AMD_EXTENSIONS
1615 case glslang::EOpConstructF16Mat2x2:
1616 case glslang::EOpConstructF16Mat2x3:
1617 case glslang::EOpConstructF16Mat2x4:
1618 case glslang::EOpConstructF16Mat3x2:
1619 case glslang::EOpConstructF16Mat3x3:
1620 case glslang::EOpConstructF16Mat3x4:
1621 case glslang::EOpConstructF16Mat4x2:
1622 case glslang::EOpConstructF16Mat4x3:
1623 case glslang::EOpConstructF16Mat4x4:
1624#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001625 isMatrix = true;
1626 // fall through
1627 case glslang::EOpConstructFloat:
1628 case glslang::EOpConstructVec2:
1629 case glslang::EOpConstructVec3:
1630 case glslang::EOpConstructVec4:
1631 case glslang::EOpConstructDouble:
1632 case glslang::EOpConstructDVec2:
1633 case glslang::EOpConstructDVec3:
1634 case glslang::EOpConstructDVec4:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08001635#ifdef AMD_EXTENSIONS
1636 case glslang::EOpConstructFloat16:
1637 case glslang::EOpConstructF16Vec2:
1638 case glslang::EOpConstructF16Vec3:
1639 case glslang::EOpConstructF16Vec4:
1640#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001641 case glslang::EOpConstructBool:
1642 case glslang::EOpConstructBVec2:
1643 case glslang::EOpConstructBVec3:
1644 case glslang::EOpConstructBVec4:
1645 case glslang::EOpConstructInt:
1646 case glslang::EOpConstructIVec2:
1647 case glslang::EOpConstructIVec3:
1648 case glslang::EOpConstructIVec4:
1649 case glslang::EOpConstructUint:
1650 case glslang::EOpConstructUVec2:
1651 case glslang::EOpConstructUVec3:
1652 case glslang::EOpConstructUVec4:
Rex Xu8ff43de2016-04-22 16:51:45 +08001653 case glslang::EOpConstructInt64:
1654 case glslang::EOpConstructI64Vec2:
1655 case glslang::EOpConstructI64Vec3:
1656 case glslang::EOpConstructI64Vec4:
1657 case glslang::EOpConstructUint64:
1658 case glslang::EOpConstructU64Vec2:
1659 case glslang::EOpConstructU64Vec3:
1660 case glslang::EOpConstructU64Vec4:
Rex Xucabbb782017-03-24 13:41:14 +08001661#ifdef AMD_EXTENSIONS
1662 case glslang::EOpConstructInt16:
1663 case glslang::EOpConstructI16Vec2:
1664 case glslang::EOpConstructI16Vec3:
1665 case glslang::EOpConstructI16Vec4:
1666 case glslang::EOpConstructUint16:
1667 case glslang::EOpConstructU16Vec2:
1668 case glslang::EOpConstructU16Vec3:
1669 case glslang::EOpConstructU16Vec4:
1670#endif
John Kessenich140f3df2015-06-26 16:58:36 -06001671 case glslang::EOpConstructStruct:
John Kessenich6c292d32016-02-15 20:58:50 -07001672 case glslang::EOpConstructTextureSampler:
John Kessenich140f3df2015-06-26 16:58:36 -06001673 {
John Kesseniche485c7a2017-05-31 18:50:53 -06001674 builder.setLine(node->getLoc().line);
John Kessenich140f3df2015-06-26 16:58:36 -06001675 std::vector<spv::Id> arguments;
Rex Xufc618912015-09-09 16:42:49 +08001676 translateArguments(*node, arguments);
John Kessenich140f3df2015-06-26 16:58:36 -06001677 spv::Id constructed;
John Kessenich6c292d32016-02-15 20:58:50 -07001678 if (node->getOp() == glslang::EOpConstructTextureSampler)
John Kessenich8c8505c2016-07-26 12:50:38 -06001679 constructed = builder.createOp(spv::OpSampledImage, resultType(), arguments);
John Kessenich6c292d32016-02-15 20:58:50 -07001680 else if (node->getOp() == glslang::EOpConstructStruct || node->getType().isArray()) {
John Kessenich140f3df2015-06-26 16:58:36 -06001681 std::vector<spv::Id> constituents;
1682 for (int c = 0; c < (int)arguments.size(); ++c)
1683 constituents.push_back(arguments[c]);
John Kessenich8c8505c2016-07-26 12:50:38 -06001684 constructed = builder.createCompositeConstruct(resultType(), constituents);
John Kessenich55e7d112015-11-15 21:33:39 -07001685 } else if (isMatrix)
John Kessenich8c8505c2016-07-26 12:50:38 -06001686 constructed = builder.createMatrixConstructor(precision, arguments, resultType());
John Kessenich55e7d112015-11-15 21:33:39 -07001687 else
John Kessenich8c8505c2016-07-26 12:50:38 -06001688 constructed = builder.createConstructor(precision, arguments, resultType());
John Kessenich140f3df2015-06-26 16:58:36 -06001689
1690 builder.clearAccessChain();
1691 builder.setAccessChainRValue(constructed);
1692
1693 return false;
1694 }
1695
1696 // These six are component-wise compares with component-wise results.
1697 // Forward on to createBinaryOperation(), requesting a vector result.
1698 case glslang::EOpLessThan:
1699 case glslang::EOpGreaterThan:
1700 case glslang::EOpLessThanEqual:
1701 case glslang::EOpGreaterThanEqual:
1702 case glslang::EOpVectorEqual:
1703 case glslang::EOpVectorNotEqual:
1704 {
1705 // Map the operation to a binary
1706 binOp = node->getOp();
1707 reduceComparison = false;
1708 switch (node->getOp()) {
1709 case glslang::EOpVectorEqual: binOp = glslang::EOpVectorEqual; break;
1710 case glslang::EOpVectorNotEqual: binOp = glslang::EOpVectorNotEqual; break;
1711 default: binOp = node->getOp(); break;
1712 }
1713
1714 break;
1715 }
1716 case glslang::EOpMul:
John Kessenich8c8505c2016-07-26 12:50:38 -06001717 // component-wise matrix multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001718 binOp = glslang::EOpMul;
1719 break;
1720 case glslang::EOpOuterProduct:
1721 // two vectors multiplied to make a matrix
1722 binOp = glslang::EOpOuterProduct;
1723 break;
1724 case glslang::EOpDot:
1725 {
qining25262b32016-05-06 17:25:16 -04001726 // for scalar dot product, use multiply
John Kessenich140f3df2015-06-26 16:58:36 -06001727 glslang::TIntermSequence& glslangOperands = node->getSequence();
John Kessenich8d72f1a2016-05-20 12:06:03 -06001728 if (glslangOperands[0]->getAsTyped()->getVectorSize() == 1)
John Kessenich140f3df2015-06-26 16:58:36 -06001729 binOp = glslang::EOpMul;
1730 break;
1731 }
1732 case glslang::EOpMod:
1733 // when an aggregate, this is the floating-point mod built-in function,
1734 // which can be emitted by the one in createBinaryOperation()
1735 binOp = glslang::EOpMod;
1736 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001737 case glslang::EOpEmitVertex:
1738 case glslang::EOpEndPrimitive:
1739 case glslang::EOpBarrier:
1740 case glslang::EOpMemoryBarrier:
1741 case glslang::EOpMemoryBarrierAtomicCounter:
1742 case glslang::EOpMemoryBarrierBuffer:
1743 case glslang::EOpMemoryBarrierImage:
1744 case glslang::EOpMemoryBarrierShared:
1745 case glslang::EOpGroupMemoryBarrier:
LoopDawg6e72fdd2016-06-15 09:50:24 -06001746 case glslang::EOpAllMemoryBarrierWithGroupSync:
1747 case glslang::EOpGroupMemoryBarrierWithGroupSync:
1748 case glslang::EOpWorkgroupMemoryBarrier:
1749 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
John Kessenich140f3df2015-06-26 16:58:36 -06001750 noReturnValue = true;
1751 // These all have 0 operands and will naturally finish up in the code below for 0 operands
1752 break;
1753
John Kessenich426394d2015-07-23 10:22:48 -06001754 case glslang::EOpAtomicAdd:
1755 case glslang::EOpAtomicMin:
1756 case glslang::EOpAtomicMax:
1757 case glslang::EOpAtomicAnd:
1758 case glslang::EOpAtomicOr:
1759 case glslang::EOpAtomicXor:
1760 case glslang::EOpAtomicExchange:
1761 case glslang::EOpAtomicCompSwap:
1762 atomic = true;
1763 break;
1764
John Kessenich0d0c6d32017-07-23 16:08:26 -06001765 case glslang::EOpAtomicCounterAdd:
1766 case glslang::EOpAtomicCounterSubtract:
1767 case glslang::EOpAtomicCounterMin:
1768 case glslang::EOpAtomicCounterMax:
1769 case glslang::EOpAtomicCounterAnd:
1770 case glslang::EOpAtomicCounterOr:
1771 case glslang::EOpAtomicCounterXor:
1772 case glslang::EOpAtomicCounterExchange:
1773 case glslang::EOpAtomicCounterCompSwap:
1774 builder.addExtension("SPV_KHR_shader_atomic_counter_ops");
1775 builder.addCapability(spv::CapabilityAtomicStorageOps);
1776 atomic = true;
1777 break;
1778
John Kessenich140f3df2015-06-26 16:58:36 -06001779 default:
1780 break;
1781 }
1782
1783 //
1784 // See if it maps to a regular operation.
1785 //
John Kessenich140f3df2015-06-26 16:58:36 -06001786 if (binOp != glslang::EOpNull) {
1787 glslang::TIntermTyped* left = node->getSequence()[0]->getAsTyped();
1788 glslang::TIntermTyped* right = node->getSequence()[1]->getAsTyped();
1789 assert(left && right);
1790
1791 builder.clearAccessChain();
1792 left->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001793 spv::Id leftId = accessChainLoad(left->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001794
1795 builder.clearAccessChain();
1796 right->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07001797 spv::Id rightId = accessChainLoad(right->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06001798
John Kesseniche485c7a2017-05-31 18:50:53 -06001799 builder.setLine(node->getLoc().line);
qining25262b32016-05-06 17:25:16 -04001800 result = createBinaryOperation(binOp, precision, TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001801 resultType(), leftId, rightId,
John Kessenich140f3df2015-06-26 16:58:36 -06001802 left->getType().getBasicType(), reduceComparison);
1803
1804 // code above should only make binOp that exists in createBinaryOperation
John Kessenich55e7d112015-11-15 21:33:39 -07001805 assert(result != spv::NoResult);
John Kessenich140f3df2015-06-26 16:58:36 -06001806 builder.clearAccessChain();
1807 builder.setAccessChainRValue(result);
1808
1809 return false;
1810 }
1811
John Kessenich426394d2015-07-23 10:22:48 -06001812 //
1813 // Create the list of operands.
1814 //
John Kessenich140f3df2015-06-26 16:58:36 -06001815 glslang::TIntermSequence& glslangOperands = node->getSequence();
1816 std::vector<spv::Id> operands;
1817 for (int arg = 0; arg < (int)glslangOperands.size(); ++arg) {
John Kessenich140f3df2015-06-26 16:58:36 -06001818 // special case l-value operands; there are just a few
1819 bool lvalue = false;
1820 switch (node->getOp()) {
John Kessenich55e7d112015-11-15 21:33:39 -07001821 case glslang::EOpFrexp:
John Kessenich140f3df2015-06-26 16:58:36 -06001822 case glslang::EOpModf:
1823 if (arg == 1)
1824 lvalue = true;
1825 break;
Rex Xu7a26c172015-12-08 17:12:09 +08001826 case glslang::EOpInterpolateAtSample:
1827 case glslang::EOpInterpolateAtOffset:
Rex Xu9d93a232016-05-05 12:30:44 +08001828#ifdef AMD_EXTENSIONS
1829 case glslang::EOpInterpolateAtVertex:
1830#endif
John Kessenich8c8505c2016-07-26 12:50:38 -06001831 if (arg == 0) {
Rex Xu7a26c172015-12-08 17:12:09 +08001832 lvalue = true;
John Kessenich8c8505c2016-07-26 12:50:38 -06001833
1834 // Does it need a swizzle inversion? If so, evaluation is inverted;
1835 // operate first on the swizzle base, then apply the swizzle.
John Kessenichecba76f2017-01-06 00:34:48 -07001836 if (glslangOperands[0]->getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06001837 glslangOperands[0]->getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
1838 invertedType = convertGlslangToSpvType(glslangOperands[0]->getAsBinaryNode()->getLeft()->getType());
1839 }
Rex Xu7a26c172015-12-08 17:12:09 +08001840 break;
Rex Xud4782c12015-09-06 16:30:11 +08001841 case glslang::EOpAtomicAdd:
1842 case glslang::EOpAtomicMin:
1843 case glslang::EOpAtomicMax:
1844 case glslang::EOpAtomicAnd:
1845 case glslang::EOpAtomicOr:
1846 case glslang::EOpAtomicXor:
1847 case glslang::EOpAtomicExchange:
1848 case glslang::EOpAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06001849 case glslang::EOpAtomicCounterAdd:
1850 case glslang::EOpAtomicCounterSubtract:
1851 case glslang::EOpAtomicCounterMin:
1852 case glslang::EOpAtomicCounterMax:
1853 case glslang::EOpAtomicCounterAnd:
1854 case glslang::EOpAtomicCounterOr:
1855 case glslang::EOpAtomicCounterXor:
1856 case glslang::EOpAtomicCounterExchange:
1857 case glslang::EOpAtomicCounterCompSwap:
Rex Xud4782c12015-09-06 16:30:11 +08001858 if (arg == 0)
1859 lvalue = true;
1860 break;
John Kessenich55e7d112015-11-15 21:33:39 -07001861 case glslang::EOpAddCarry:
1862 case glslang::EOpSubBorrow:
1863 if (arg == 2)
1864 lvalue = true;
1865 break;
1866 case glslang::EOpUMulExtended:
1867 case glslang::EOpIMulExtended:
1868 if (arg >= 2)
1869 lvalue = true;
1870 break;
John Kessenich140f3df2015-06-26 16:58:36 -06001871 default:
1872 break;
1873 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001874 builder.clearAccessChain();
1875 if (invertedType != spv::NoType && arg == 0)
1876 glslangOperands[0]->getAsBinaryNode()->getLeft()->traverse(this);
1877 else
1878 glslangOperands[arg]->traverse(this);
John Kessenich140f3df2015-06-26 16:58:36 -06001879 if (lvalue)
1880 operands.push_back(builder.accessChainGetLValue());
John Kesseniche485c7a2017-05-31 18:50:53 -06001881 else {
1882 builder.setLine(node->getLoc().line);
John Kessenich32cfd492016-02-02 12:37:46 -07001883 operands.push_back(accessChainLoad(glslangOperands[arg]->getAsTyped()->getType()));
John Kesseniche485c7a2017-05-31 18:50:53 -06001884 }
John Kessenich140f3df2015-06-26 16:58:36 -06001885 }
John Kessenich426394d2015-07-23 10:22:48 -06001886
John Kesseniche485c7a2017-05-31 18:50:53 -06001887 builder.setLine(node->getLoc().line);
John Kessenich426394d2015-07-23 10:22:48 -06001888 if (atomic) {
1889 // Handle all atomics
John Kessenich8c8505c2016-07-26 12:50:38 -06001890 result = createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001891 } else {
1892 // Pass through to generic operations.
1893 switch (glslangOperands.size()) {
1894 case 0:
John Kessenich8c8505c2016-07-26 12:50:38 -06001895 result = createNoArgOperation(node->getOp(), precision, resultType());
John Kessenich426394d2015-07-23 10:22:48 -06001896 break;
1897 case 1:
qining25262b32016-05-06 17:25:16 -04001898 result = createUnaryOperation(
1899 node->getOp(), precision,
1900 TranslateNoContractionDecoration(node->getType().getQualifier()),
John Kessenich8c8505c2016-07-26 12:50:38 -06001901 resultType(), operands.front(),
qining25262b32016-05-06 17:25:16 -04001902 glslangOperands[0]->getAsTyped()->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001903 break;
1904 default:
John Kessenich8c8505c2016-07-26 12:50:38 -06001905 result = createMiscOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
John Kessenich426394d2015-07-23 10:22:48 -06001906 break;
1907 }
John Kessenich8c8505c2016-07-26 12:50:38 -06001908 if (invertedType)
1909 result = createInvertedSwizzle(precision, *glslangOperands[0]->getAsBinaryNode(), result);
John Kessenich140f3df2015-06-26 16:58:36 -06001910 }
1911
1912 if (noReturnValue)
1913 return false;
1914
1915 if (! result) {
Lei Zhang17535f72016-05-04 15:55:59 -04001916 logger->missingFunctionality("unknown glslang aggregate");
John Kessenich50e57562015-12-21 21:21:11 -07001917 return true; // pick up a child as a placeholder operand
John Kessenich140f3df2015-06-26 16:58:36 -06001918 } else {
1919 builder.clearAccessChain();
1920 builder.setAccessChainRValue(result);
1921 return false;
1922 }
1923}
1924
John Kessenich433e9ff2017-01-26 20:31:11 -07001925// This path handles both if-then-else and ?:
1926// The if-then-else has a node type of void, while
1927// ?: has either a void or a non-void node type
1928//
1929// Leaving the result, when not void:
1930// GLSL only has r-values as the result of a :?, but
1931// if we have an l-value, that can be more efficient if it will
1932// become the base of a complex r-value expression, because the
1933// next layer copies r-values into memory to use the access-chain mechanism
John Kessenich140f3df2015-06-26 16:58:36 -06001934bool TGlslangToSpvTraverser::visitSelection(glslang::TVisit /* visit */, glslang::TIntermSelection* node)
1935{
John Kessenich433e9ff2017-01-26 20:31:11 -07001936 // See if it simple and safe to generate OpSelect instead of using control flow.
1937 // Crucially, side effects must be avoided, and there are performance trade-offs.
1938 // Return true if good idea (and safe) for OpSelect, false otherwise.
1939 const auto selectPolicy = [&]() -> bool {
John Kessenich04794372017-03-01 13:49:11 -07001940 if ((!node->getType().isScalar() && !node->getType().isVector()) ||
1941 node->getBasicType() == glslang::EbtVoid)
John Kessenich433e9ff2017-01-26 20:31:11 -07001942 return false;
1943
1944 if (node->getTrueBlock() == nullptr ||
1945 node->getFalseBlock() == nullptr)
1946 return false;
1947
1948 assert(node->getType() == node->getTrueBlock() ->getAsTyped()->getType() &&
1949 node->getType() == node->getFalseBlock()->getAsTyped()->getType());
1950
1951 // return true if a single operand to ? : is okay for OpSelect
1952 const auto operandOkay = [](glslang::TIntermTyped* node) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001953 return node->getAsSymbolNode() || node->getType().getQualifier().isConstant();
John Kessenich433e9ff2017-01-26 20:31:11 -07001954 };
1955
1956 return operandOkay(node->getTrueBlock() ->getAsTyped()) &&
1957 operandOkay(node->getFalseBlock()->getAsTyped());
1958 };
1959
1960 // Emit OpSelect for this selection.
1961 const auto handleAsOpSelect = [&]() {
1962 node->getCondition()->traverse(this);
1963 spv::Id condition = accessChainLoad(node->getCondition()->getType());
1964 node->getTrueBlock()->traverse(this);
1965 spv::Id trueValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1966 node->getFalseBlock()->traverse(this);
1967 spv::Id falseValue = accessChainLoad(node->getTrueBlock()->getAsTyped()->getType());
1968
John Kesseniche485c7a2017-05-31 18:50:53 -06001969 builder.setLine(node->getLoc().line);
1970
John Kesseniche434ad92017-03-30 10:09:28 -06001971 // smear condition to vector, if necessary (AST is always scalar)
1972 if (builder.isVector(trueValue))
1973 condition = builder.smearScalar(spv::NoPrecision, condition,
1974 builder.makeVectorType(builder.makeBoolType(),
1975 builder.getNumComponents(trueValue)));
1976
1977 spv::Id select = builder.createTriOp(spv::OpSelect,
1978 convertGlslangToSpvType(node->getType()), condition,
1979 trueValue, falseValue);
John Kessenich433e9ff2017-01-26 20:31:11 -07001980 builder.clearAccessChain();
1981 builder.setAccessChainRValue(select);
1982 };
1983
1984 // Try for OpSelect
1985
1986 if (selectPolicy()) {
John Kessenich8e6c6ce2017-01-28 19:29:42 -07001987 SpecConstantOpModeGuard spec_constant_op_mode_setter(&builder);
1988 if (node->getType().getQualifier().isSpecConstant())
1989 spec_constant_op_mode_setter.turnOnSpecConstantOpMode();
1990
John Kessenich433e9ff2017-01-26 20:31:11 -07001991 handleAsOpSelect();
1992 return false;
John Kessenich140f3df2015-06-26 16:58:36 -06001993 }
1994
Rex Xu57e65922017-07-04 23:23:40 +08001995 // Instead, emit control flow...
John Kessenich433e9ff2017-01-26 20:31:11 -07001996 // Don't handle results as temporaries, because there will be two names
1997 // and better to leave SSA to later passes.
1998 spv::Id result = (node->getBasicType() == glslang::EbtVoid)
1999 ? spv::NoResult
2000 : builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(node->getType()));
2001
John Kessenich140f3df2015-06-26 16:58:36 -06002002 // emit the condition before doing anything with selection
2003 node->getCondition()->traverse(this);
2004
Rex Xu57e65922017-07-04 23:23:40 +08002005 // Selection control:
2006 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2007
John Kessenich140f3df2015-06-26 16:58:36 -06002008 // make an "if" based on the value created by the condition
Rex Xu57e65922017-07-04 23:23:40 +08002009 spv::Builder::If ifBuilder(accessChainLoad(node->getCondition()->getType()), control, builder);
John Kessenich140f3df2015-06-26 16:58:36 -06002010
John Kessenich433e9ff2017-01-26 20:31:11 -07002011 // emit the "then" statement
2012 if (node->getTrueBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002013 node->getTrueBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002014 if (result != spv::NoResult)
2015 builder.createStore(accessChainLoad(node->getTrueBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002016 }
2017
John Kessenich433e9ff2017-01-26 20:31:11 -07002018 if (node->getFalseBlock() != nullptr) {
John Kessenich140f3df2015-06-26 16:58:36 -06002019 ifBuilder.makeBeginElse();
2020 // emit the "else" statement
2021 node->getFalseBlock()->traverse(this);
John Kessenich433e9ff2017-01-26 20:31:11 -07002022 if (result != spv::NoResult)
John Kessenich32cfd492016-02-02 12:37:46 -07002023 builder.createStore(accessChainLoad(node->getFalseBlock()->getAsTyped()->getType()), result);
John Kessenich140f3df2015-06-26 16:58:36 -06002024 }
2025
John Kessenich433e9ff2017-01-26 20:31:11 -07002026 // finish off the control flow
John Kessenich140f3df2015-06-26 16:58:36 -06002027 ifBuilder.makeEndIf();
2028
John Kessenich433e9ff2017-01-26 20:31:11 -07002029 if (result != spv::NoResult) {
John Kessenich140f3df2015-06-26 16:58:36 -06002030 // GLSL only has r-values as the result of a :?, but
2031 // if we have an l-value, that can be more efficient if it will
2032 // become the base of a complex r-value expression, because the
2033 // next layer copies r-values into memory to use the access-chain mechanism
2034 builder.clearAccessChain();
2035 builder.setAccessChainLValue(result);
2036 }
2037
2038 return false;
2039}
2040
2041bool TGlslangToSpvTraverser::visitSwitch(glslang::TVisit /* visit */, glslang::TIntermSwitch* node)
2042{
2043 // emit and get the condition before doing anything with switch
2044 node->getCondition()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07002045 spv::Id selector = accessChainLoad(node->getCondition()->getAsTyped()->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002046
Rex Xu57e65922017-07-04 23:23:40 +08002047 // Selection control:
2048 const spv::SelectionControlMask control = TranslateSelectionControl(node->getSelectionControl());
2049
John Kessenich140f3df2015-06-26 16:58:36 -06002050 // browse the children to sort out code segments
2051 int defaultSegment = -1;
2052 std::vector<TIntermNode*> codeSegments;
2053 glslang::TIntermSequence& sequence = node->getBody()->getSequence();
2054 std::vector<int> caseValues;
2055 std::vector<int> valueIndexToSegment(sequence.size()); // note: probably not all are used, it is an overestimate
2056 for (glslang::TIntermSequence::iterator c = sequence.begin(); c != sequence.end(); ++c) {
2057 TIntermNode* child = *c;
2058 if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpDefault)
baldurkd76692d2015-07-12 11:32:58 +02002059 defaultSegment = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002060 else if (child->getAsBranchNode() && child->getAsBranchNode()->getFlowOp() == glslang::EOpCase) {
baldurkd76692d2015-07-12 11:32:58 +02002061 valueIndexToSegment[caseValues.size()] = (int)codeSegments.size();
John Kessenich140f3df2015-06-26 16:58:36 -06002062 caseValues.push_back(child->getAsBranchNode()->getExpression()->getAsConstantUnion()->getConstArray()[0].getIConst());
2063 } else
2064 codeSegments.push_back(child);
2065 }
2066
qining25262b32016-05-06 17:25:16 -04002067 // handle the case where the last code segment is missing, due to no code
John Kessenich140f3df2015-06-26 16:58:36 -06002068 // statements between the last case and the end of the switch statement
2069 if ((caseValues.size() && (int)codeSegments.size() == valueIndexToSegment[caseValues.size() - 1]) ||
2070 (int)codeSegments.size() == defaultSegment)
2071 codeSegments.push_back(nullptr);
2072
2073 // make the switch statement
2074 std::vector<spv::Block*> segmentBlocks; // returned, as the blocks allocated in the call
Rex Xu57e65922017-07-04 23:23:40 +08002075 builder.makeSwitch(selector, control, (int)codeSegments.size(), caseValues, valueIndexToSegment, defaultSegment, segmentBlocks);
John Kessenich140f3df2015-06-26 16:58:36 -06002076
2077 // emit all the code in the segments
2078 breakForLoop.push(false);
2079 for (unsigned int s = 0; s < codeSegments.size(); ++s) {
2080 builder.nextSwitchSegment(segmentBlocks, s);
2081 if (codeSegments[s])
2082 codeSegments[s]->traverse(this);
2083 else
2084 builder.addSwitchBreak();
2085 }
2086 breakForLoop.pop();
2087
2088 builder.endSwitch(segmentBlocks);
2089
2090 return false;
2091}
2092
2093void TGlslangToSpvTraverser::visitConstantUnion(glslang::TIntermConstantUnion* node)
2094{
2095 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04002096 spv::Id constant = createSpvConstantFromConstUnionArray(node->getType(), node->getConstArray(), nextConst, false);
John Kessenich140f3df2015-06-26 16:58:36 -06002097
2098 builder.clearAccessChain();
2099 builder.setAccessChainRValue(constant);
2100}
2101
2102bool TGlslangToSpvTraverser::visitLoop(glslang::TVisit /* visit */, glslang::TIntermLoop* node)
2103{
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002104 auto blocks = builder.makeNewLoop();
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002105 builder.createBranch(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002106
2107 // Loop control:
2108 const spv::LoopControlMask control = TranslateLoopControl(node->getLoopControl());
2109
2110 // TODO: dependency length
2111
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002112 // Spec requires back edges to target header blocks, and every header block
2113 // must dominate its merge block. Make a header block first to ensure these
2114 // conditions are met. By definition, it will contain OpLoopMerge, followed
2115 // by a block-ending branch. But we don't want to put any other body/test
2116 // instructions in it, since the body/test may have arbitrary instructions,
2117 // including merges of its own.
John Kesseniche485c7a2017-05-31 18:50:53 -06002118 builder.setLine(node->getLoc().line);
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002119 builder.setBuildPoint(&blocks.head);
steve-lunargf1709e72017-05-02 20:14:50 -06002120 builder.createLoopMerge(&blocks.merge, &blocks.continue_target, control);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002121 if (node->testFirst() && node->getTest()) {
Dejan Mircevski213bbbe2016-01-20 11:51:43 -05002122 spv::Block& test = builder.makeNewBlock();
2123 builder.createBranch(&test);
2124
2125 builder.setBuildPoint(&test);
John Kessenich140f3df2015-06-26 16:58:36 -06002126 node->getTest()->traverse(this);
John Kesseniche485c7a2017-05-31 18:50:53 -06002127 spv::Id condition = accessChainLoad(node->getTest()->getType());
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002128 builder.createConditionalBranch(condition, &blocks.body, &blocks.merge);
2129
2130 builder.setBuildPoint(&blocks.body);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002131 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002132 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002133 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002134 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002135 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002136
2137 builder.setBuildPoint(&blocks.continue_target);
2138 if (node->getTerminal())
2139 node->getTerminal()->traverse(this);
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002140 builder.createBranch(&blocks.head);
David Netoc22f37c2015-07-15 16:21:26 -04002141 } else {
John Kesseniche485c7a2017-05-31 18:50:53 -06002142 builder.setLine(node->getLoc().line);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002143 builder.createBranch(&blocks.body);
2144
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002145 breakForLoop.push(true);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002146 builder.setBuildPoint(&blocks.body);
2147 if (node->getBody())
Dejan Mircevskie537b8b2016-01-10 19:37:00 -05002148 node->getBody()->traverse(this);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002149 builder.createBranch(&blocks.continue_target);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002150 breakForLoop.pop();
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002151
2152 builder.setBuildPoint(&blocks.continue_target);
2153 if (node->getTerminal())
2154 node->getTerminal()->traverse(this);
2155 if (node->getTest()) {
2156 node->getTest()->traverse(this);
2157 spv::Id condition =
John Kessenich32cfd492016-02-02 12:37:46 -07002158 accessChainLoad(node->getTest()->getType());
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002159 builder.createConditionalBranch(condition, &blocks.head, &blocks.merge);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002160 } else {
Dejan Mircevskied55bcd2016-01-19 21:13:38 -05002161 // TODO: unless there was a break/return/discard instruction
2162 // somewhere in the body, this is an infinite loop, so we should
2163 // issue a warning.
Dejan Mircevski832c65c2016-01-11 15:57:11 -05002164 builder.createBranch(&blocks.head);
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002165 }
John Kessenich140f3df2015-06-26 16:58:36 -06002166 }
Dejan Mircevski9c6734c2016-01-10 12:15:13 -05002167 builder.setBuildPoint(&blocks.merge);
Dejan Mircevskic8fbbab2016-01-11 14:48:36 -05002168 builder.closeLoop();
John Kessenich140f3df2015-06-26 16:58:36 -06002169 return false;
2170}
2171
2172bool TGlslangToSpvTraverser::visitBranch(glslang::TVisit /* visit */, glslang::TIntermBranch* node)
2173{
2174 if (node->getExpression())
2175 node->getExpression()->traverse(this);
2176
John Kesseniche485c7a2017-05-31 18:50:53 -06002177 builder.setLine(node->getLoc().line);
2178
John Kessenich140f3df2015-06-26 16:58:36 -06002179 switch (node->getFlowOp()) {
2180 case glslang::EOpKill:
2181 builder.makeDiscard();
2182 break;
2183 case glslang::EOpBreak:
2184 if (breakForLoop.top())
2185 builder.createLoopExit();
2186 else
2187 builder.addSwitchBreak();
2188 break;
2189 case glslang::EOpContinue:
John Kessenich140f3df2015-06-26 16:58:36 -06002190 builder.createLoopContinue();
2191 break;
2192 case glslang::EOpReturn:
John Kesseniched33e052016-10-06 12:59:51 -06002193 if (node->getExpression()) {
2194 const glslang::TType& glslangReturnType = node->getExpression()->getType();
2195 spv::Id returnId = accessChainLoad(glslangReturnType);
2196 if (builder.getTypeId(returnId) != currentFunction->getReturnType()) {
2197 builder.clearAccessChain();
2198 spv::Id copyId = builder.createVariable(spv::StorageClassFunction, currentFunction->getReturnType());
2199 builder.setAccessChainLValue(copyId);
2200 multiTypeStore(glslangReturnType, returnId);
2201 returnId = builder.createLoad(copyId);
2202 }
2203 builder.makeReturn(false, returnId);
2204 } else
John Kesseniche770b3e2015-09-14 20:58:02 -06002205 builder.makeReturn(false);
John Kessenich140f3df2015-06-26 16:58:36 -06002206
2207 builder.clearAccessChain();
2208 break;
2209
2210 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002211 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002212 break;
2213 }
2214
2215 return false;
2216}
2217
2218spv::Id TGlslangToSpvTraverser::createSpvVariable(const glslang::TIntermSymbol* node)
2219{
qining25262b32016-05-06 17:25:16 -04002220 // First, steer off constants, which are not SPIR-V variables, but
John Kessenich140f3df2015-06-26 16:58:36 -06002221 // can still have a mapping to a SPIR-V Id.
John Kessenich55e7d112015-11-15 21:33:39 -07002222 // This includes specialization constants.
John Kessenich7cc0e282016-03-20 00:46:02 -06002223 if (node->getQualifier().isConstant()) {
qining08408382016-03-21 09:51:37 -04002224 return createSpvConstant(*node);
John Kessenich140f3df2015-06-26 16:58:36 -06002225 }
2226
2227 // Now, handle actual variables
John Kessenicha5c5fb62017-05-05 05:09:58 -06002228 spv::StorageClass storageClass = TranslateStorageClass(node->getType());
John Kessenich140f3df2015-06-26 16:58:36 -06002229 spv::Id spvType = convertGlslangToSpvType(node->getType());
2230
Rex Xuf89ad982017-04-07 23:22:33 +08002231#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08002232 const bool contains16BitType = node->getType().containsBasicType(glslang::EbtFloat16) ||
2233 node->getType().containsBasicType(glslang::EbtInt16) ||
2234 node->getType().containsBasicType(glslang::EbtUint16);
Rex Xuf89ad982017-04-07 23:22:33 +08002235 if (contains16BitType) {
2236 if (storageClass == spv::StorageClassInput || storageClass == spv::StorageClassOutput) {
2237 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2238 builder.addCapability(spv::CapabilityStorageInputOutput16);
2239 } else if (storageClass == spv::StorageClassPushConstant) {
2240 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2241 builder.addCapability(spv::CapabilityStoragePushConstant16);
2242 } else if (storageClass == spv::StorageClassUniform) {
2243 builder.addExtension(spv::E_SPV_KHR_16bit_storage);
2244 builder.addCapability(spv::CapabilityStorageUniform16);
2245 if (node->getType().getQualifier().storage == glslang::EvqBuffer)
2246 builder.addCapability(spv::CapabilityStorageUniformBufferBlock16);
2247 }
2248 }
2249#endif
2250
John Kessenich140f3df2015-06-26 16:58:36 -06002251 const char* name = node->getName().c_str();
2252 if (glslang::IsAnonymous(name))
2253 name = "";
2254
2255 return builder.createVariable(storageClass, spvType, name);
2256}
2257
2258// Return type Id of the sampled type.
2259spv::Id TGlslangToSpvTraverser::getSampledType(const glslang::TSampler& sampler)
2260{
2261 switch (sampler.type) {
2262 case glslang::EbtFloat: return builder.makeFloatType(32);
2263 case glslang::EbtInt: return builder.makeIntType(32);
2264 case glslang::EbtUint: return builder.makeUintType(32);
2265 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002266 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002267 return builder.makeFloatType(32);
2268 }
2269}
2270
John Kessenich8c8505c2016-07-26 12:50:38 -06002271// If node is a swizzle operation, return the type that should be used if
2272// the swizzle base is first consumed by another operation, before the swizzle
2273// is applied.
2274spv::Id TGlslangToSpvTraverser::getInvertedSwizzleType(const glslang::TIntermTyped& node)
2275{
John Kessenichecba76f2017-01-06 00:34:48 -07002276 if (node.getAsOperator() &&
John Kessenich8c8505c2016-07-26 12:50:38 -06002277 node.getAsOperator()->getOp() == glslang::EOpVectorSwizzle)
2278 return convertGlslangToSpvType(node.getAsBinaryNode()->getLeft()->getType());
2279 else
2280 return spv::NoType;
2281}
2282
2283// When inverting a swizzle with a parent op, this function
2284// will apply the swizzle operation to a completed parent operation.
2285spv::Id TGlslangToSpvTraverser::createInvertedSwizzle(spv::Decoration precision, const glslang::TIntermTyped& node, spv::Id parentResult)
2286{
2287 std::vector<unsigned> swizzle;
2288 convertSwizzle(*node.getAsBinaryNode()->getRight()->getAsAggregate(), swizzle);
2289 return builder.createRvalueSwizzle(precision, convertGlslangToSpvType(node.getType()), parentResult, swizzle);
2290}
2291
John Kessenich8c8505c2016-07-26 12:50:38 -06002292// Convert a glslang AST swizzle node to a swizzle vector for building SPIR-V.
2293void TGlslangToSpvTraverser::convertSwizzle(const glslang::TIntermAggregate& node, std::vector<unsigned>& swizzle)
2294{
2295 const glslang::TIntermSequence& swizzleSequence = node.getSequence();
2296 for (int i = 0; i < (int)swizzleSequence.size(); ++i)
2297 swizzle.push_back(swizzleSequence[i]->getAsConstantUnion()->getConstArray()[0].getIConst());
2298}
2299
John Kessenich3ac051e2015-12-20 11:29:16 -07002300// Convert from a glslang type to an SPV type, by calling into a
2301// recursive version of this function. This establishes the inherited
2302// layout state rooted from the top-level type.
John Kessenich140f3df2015-06-26 16:58:36 -06002303spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type)
2304{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002305 return convertGlslangToSpvType(type, getExplicitLayout(type), type.getQualifier());
John Kessenich31ed4832015-09-09 17:51:38 -06002306}
2307
2308// Do full recursive conversion of an arbitrary glslang type to a SPIR-V Id.
John Kessenich7b9fa252016-01-21 18:56:57 -07002309// explicitLayout can be kept the same throughout the hierarchical recursive walk.
John Kessenich6090df02016-06-30 21:18:02 -06002310// Mutually recursive with convertGlslangStructToSpvType().
John Kesseniche0b6cad2015-12-24 10:30:13 -07002311spv::Id TGlslangToSpvTraverser::convertGlslangToSpvType(const glslang::TType& type, glslang::TLayoutPacking explicitLayout, const glslang::TQualifier& qualifier)
John Kessenich31ed4832015-09-09 17:51:38 -06002312{
John Kesseniche0b6cad2015-12-24 10:30:13 -07002313 spv::Id spvType = spv::NoResult;
John Kessenich140f3df2015-06-26 16:58:36 -06002314
2315 switch (type.getBasicType()) {
2316 case glslang::EbtVoid:
2317 spvType = builder.makeVoidType();
John Kessenich55e7d112015-11-15 21:33:39 -07002318 assert (! type.isArray());
John Kessenich140f3df2015-06-26 16:58:36 -06002319 break;
2320 case glslang::EbtFloat:
2321 spvType = builder.makeFloatType(32);
2322 break;
2323 case glslang::EbtDouble:
2324 spvType = builder.makeFloatType(64);
2325 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002326#ifdef AMD_EXTENSIONS
2327 case glslang::EbtFloat16:
2328 builder.addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
Rex Xuc9e3c3c2016-07-29 16:00:05 +08002329 spvType = builder.makeFloatType(16);
2330 break;
2331#endif
John Kessenich140f3df2015-06-26 16:58:36 -06002332 case glslang::EbtBool:
John Kessenich103bef92016-02-08 21:38:15 -07002333 // "transparent" bool doesn't exist in SPIR-V. The GLSL convention is
2334 // a 32-bit int where non-0 means true.
2335 if (explicitLayout != glslang::ElpNone)
2336 spvType = builder.makeUintType(32);
2337 else
2338 spvType = builder.makeBoolType();
John Kessenich140f3df2015-06-26 16:58:36 -06002339 break;
2340 case glslang::EbtInt:
2341 spvType = builder.makeIntType(32);
2342 break;
2343 case glslang::EbtUint:
2344 spvType = builder.makeUintType(32);
2345 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08002346 case glslang::EbtInt64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002347 spvType = builder.makeIntType(64);
2348 break;
2349 case glslang::EbtUint64:
Rex Xu8ff43de2016-04-22 16:51:45 +08002350 spvType = builder.makeUintType(64);
2351 break;
Rex Xucabbb782017-03-24 13:41:14 +08002352#ifdef AMD_EXTENSIONS
2353 case glslang::EbtInt16:
2354 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2355 spvType = builder.makeIntType(16);
2356 break;
2357 case glslang::EbtUint16:
2358 builder.addExtension(spv::E_SPV_AMD_gpu_shader_int16);
2359 spvType = builder.makeUintType(16);
2360 break;
2361#endif
John Kessenich426394d2015-07-23 10:22:48 -06002362 case glslang::EbtAtomicUint:
John Kessenich2d0cc782016-07-07 13:20:00 -06002363 builder.addCapability(spv::CapabilityAtomicStorage);
John Kessenich426394d2015-07-23 10:22:48 -06002364 spvType = builder.makeUintType(32);
2365 break;
John Kessenich140f3df2015-06-26 16:58:36 -06002366 case glslang::EbtSampler:
2367 {
2368 const glslang::TSampler& sampler = type.getSampler();
John Kessenich6c292d32016-02-15 20:58:50 -07002369 if (sampler.sampler) {
2370 // pure sampler
2371 spvType = builder.makeSamplerType();
2372 } else {
2373 // an image is present, make its type
2374 spvType = builder.makeImageType(getSampledType(sampler), TranslateDimensionality(sampler), sampler.shadow, sampler.arrayed, sampler.ms,
2375 sampler.image ? 2 : 1, TranslateImageFormat(type));
2376 if (sampler.combined) {
2377 // already has both image and sampler, make the combined type
2378 spvType = builder.makeSampledImageType(spvType);
2379 }
John Kessenich55e7d112015-11-15 21:33:39 -07002380 }
John Kesseniche0b6cad2015-12-24 10:30:13 -07002381 }
John Kessenich140f3df2015-06-26 16:58:36 -06002382 break;
2383 case glslang::EbtStruct:
2384 case glslang::EbtBlock:
2385 {
2386 // If we've seen this struct type, return it
John Kessenich6090df02016-06-30 21:18:02 -06002387 const glslang::TTypeList* glslangMembers = type.getStruct();
John Kesseniche0b6cad2015-12-24 10:30:13 -07002388
2389 // Try to share structs for different layouts, but not yet for other
2390 // kinds of qualification (primarily not yet including interpolant qualification).
John Kessenichf2b7f332016-09-01 17:05:23 -06002391 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002392 spvType = structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers];
John Kesseniche0b6cad2015-12-24 10:30:13 -07002393 if (spvType != spv::NoResult)
John Kessenich140f3df2015-06-26 16:58:36 -06002394 break;
2395
2396 // else, we haven't seen it...
John Kessenich140f3df2015-06-26 16:58:36 -06002397 if (type.getBasicType() == glslang::EbtBlock)
John Kessenich6090df02016-06-30 21:18:02 -06002398 memberRemapper[glslangMembers].resize(glslangMembers->size());
2399 spvType = convertGlslangStructToSpvType(type, glslangMembers, explicitLayout, qualifier);
John Kessenich140f3df2015-06-26 16:58:36 -06002400 }
2401 break;
2402 default:
John Kessenich55e7d112015-11-15 21:33:39 -07002403 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06002404 break;
2405 }
2406
2407 if (type.isMatrix())
2408 spvType = builder.makeMatrixType(spvType, type.getMatrixCols(), type.getMatrixRows());
2409 else {
2410 // If this variable has a vector element count greater than 1, create a SPIR-V vector
2411 if (type.getVectorSize() > 1)
2412 spvType = builder.makeVectorType(spvType, type.getVectorSize());
2413 }
2414
2415 if (type.isArray()) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002416 int stride = 0; // keep this 0 unless doing an explicit layout; 0 will mean no decoration, no stride
2417
John Kessenichc9a80832015-09-12 12:17:44 -06002418 // Do all but the outer dimension
John Kessenichc9e0a422015-12-29 21:27:24 -07002419 if (type.getArraySizes()->getNumDims() > 1) {
John Kessenichf8842e52016-01-04 19:22:56 -07002420 // We need to decorate array strides for types needing explicit layout, except blocks.
2421 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock) {
John Kessenichc9e0a422015-12-29 21:27:24 -07002422 // Use a dummy glslang type for querying internal strides of
2423 // arrays of arrays, but using just a one-dimensional array.
2424 glslang::TType simpleArrayType(type, 0); // deference type of the array
2425 while (simpleArrayType.getArraySizes().getNumDims() > 1)
2426 simpleArrayType.getArraySizes().dereference();
2427
2428 // Will compute the higher-order strides here, rather than making a whole
2429 // pile of types and doing repetitive recursion on their contents.
2430 stride = getArrayStride(simpleArrayType, explicitLayout, qualifier.layoutMatrix);
2431 }
John Kessenichf8842e52016-01-04 19:22:56 -07002432
2433 // make the arrays
John Kessenichc9e0a422015-12-29 21:27:24 -07002434 for (int dim = type.getArraySizes()->getNumDims() - 1; dim > 0; --dim) {
John Kessenich6c292d32016-02-15 20:58:50 -07002435 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), dim), stride);
John Kessenichc9e0a422015-12-29 21:27:24 -07002436 if (stride > 0)
2437 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich6c292d32016-02-15 20:58:50 -07002438 stride *= type.getArraySizes()->getDimSize(dim);
John Kessenichc9e0a422015-12-29 21:27:24 -07002439 }
2440 } else {
2441 // single-dimensional array, and don't yet have stride
2442
John Kessenichf8842e52016-01-04 19:22:56 -07002443 // We need to decorate array strides for types needing explicit layout, except blocks.
John Kessenichc9e0a422015-12-29 21:27:24 -07002444 if (explicitLayout != glslang::ElpNone && type.getBasicType() != glslang::EbtBlock)
2445 stride = getArrayStride(type, explicitLayout, qualifier.layoutMatrix);
John Kessenichc9a80832015-09-12 12:17:44 -06002446 }
John Kessenich31ed4832015-09-09 17:51:38 -06002447
John Kessenichc9a80832015-09-12 12:17:44 -06002448 // Do the outer dimension, which might not be known for a runtime-sized array
2449 if (type.isRuntimeSizedArray()) {
2450 spvType = builder.makeRuntimeArray(spvType);
2451 } else {
2452 assert(type.getOuterArraySize() > 0);
John Kessenich6c292d32016-02-15 20:58:50 -07002453 spvType = builder.makeArrayType(spvType, makeArraySizeId(*type.getArraySizes(), 0), stride);
John Kessenichc9a80832015-09-12 12:17:44 -06002454 }
John Kessenichc9e0a422015-12-29 21:27:24 -07002455 if (stride > 0)
2456 builder.addDecoration(spvType, spv::DecorationArrayStride, stride);
John Kessenich140f3df2015-06-26 16:58:36 -06002457 }
2458
2459 return spvType;
2460}
2461
John Kessenich0e737842017-03-24 18:38:16 -06002462// TODO: this functionality should exist at a higher level, in creating the AST
2463//
2464// Identify interface members that don't have their required extension turned on.
2465//
2466bool TGlslangToSpvTraverser::filterMember(const glslang::TType& member)
2467{
2468 auto& extensions = glslangIntermediate->getRequestedExtensions();
2469
Rex Xubcf291a2017-03-29 23:01:36 +08002470 if (member.getFieldName() == "gl_ViewportMask" &&
2471 extensions.find("GL_NV_viewport_array2") == extensions.end())
2472 return true;
2473 if (member.getFieldName() == "gl_SecondaryViewportMaskNV" &&
2474 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2475 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002476 if (member.getFieldName() == "gl_SecondaryPositionNV" &&
2477 extensions.find("GL_NV_stereo_view_rendering") == extensions.end())
2478 return true;
2479 if (member.getFieldName() == "gl_PositionPerViewNV" &&
2480 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2481 return true;
Rex Xubcf291a2017-03-29 23:01:36 +08002482 if (member.getFieldName() == "gl_ViewportMaskPerViewNV" &&
2483 extensions.find("GL_NVX_multiview_per_view_attributes") == extensions.end())
2484 return true;
John Kessenich0e737842017-03-24 18:38:16 -06002485
2486 return false;
2487};
2488
John Kessenich6090df02016-06-30 21:18:02 -06002489// Do full recursive conversion of a glslang structure (or block) type to a SPIR-V Id.
2490// explicitLayout can be kept the same throughout the hierarchical recursive walk.
2491// Mutually recursive with convertGlslangToSpvType().
2492spv::Id TGlslangToSpvTraverser::convertGlslangStructToSpvType(const glslang::TType& type,
2493 const glslang::TTypeList* glslangMembers,
2494 glslang::TLayoutPacking explicitLayout,
2495 const glslang::TQualifier& qualifier)
2496{
2497 // Create a vector of struct types for SPIR-V to consume
2498 std::vector<spv::Id> spvMembers;
2499 int memberDelta = 0; // how much the member's index changes from glslang to SPIR-V, normally 0, except sometimes for blocks
John Kessenich6090df02016-06-30 21:18:02 -06002500 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2501 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2502 if (glslangMember.hiddenMember()) {
2503 ++memberDelta;
2504 if (type.getBasicType() == glslang::EbtBlock)
2505 memberRemapper[glslangMembers][i] = -1;
2506 } else {
John Kessenich0e737842017-03-24 18:38:16 -06002507 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002508 memberRemapper[glslangMembers][i] = i - memberDelta;
John Kessenich0e737842017-03-24 18:38:16 -06002509 if (filterMember(glslangMember))
2510 continue;
2511 }
John Kessenich6090df02016-06-30 21:18:02 -06002512 // modify just this child's view of the qualifier
2513 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2514 InheritQualifiers(memberQualifier, qualifier);
2515
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002516 // manually inherit location
John Kessenich6090df02016-06-30 21:18:02 -06002517 if (! memberQualifier.hasLocation() && qualifier.hasLocation())
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002518 memberQualifier.layoutLocation = qualifier.layoutLocation;
John Kessenich6090df02016-06-30 21:18:02 -06002519
2520 // recurse
2521 spvMembers.push_back(convertGlslangToSpvType(glslangMember, explicitLayout, memberQualifier));
2522 }
2523 }
2524
2525 // Make the SPIR-V type
2526 spv::Id spvType = builder.makeStructType(spvMembers, type.getTypeName().c_str());
John Kessenichf2b7f332016-09-01 17:05:23 -06002527 if (! HasNonLayoutQualifiers(type, qualifier))
John Kessenich6090df02016-06-30 21:18:02 -06002528 structMap[explicitLayout][qualifier.layoutMatrix][glslangMembers] = spvType;
2529
2530 // Decorate it
2531 decorateStructType(type, glslangMembers, explicitLayout, qualifier, spvType);
2532
2533 return spvType;
2534}
2535
2536void TGlslangToSpvTraverser::decorateStructType(const glslang::TType& type,
2537 const glslang::TTypeList* glslangMembers,
2538 glslang::TLayoutPacking explicitLayout,
2539 const glslang::TQualifier& qualifier,
2540 spv::Id spvType)
2541{
2542 // Name and decorate the non-hidden members
2543 int offset = -1;
2544 int locationOffset = 0; // for use within the members of this struct
2545 for (int i = 0; i < (int)glslangMembers->size(); i++) {
2546 glslang::TType& glslangMember = *(*glslangMembers)[i].type;
2547 int member = i;
John Kessenich0e737842017-03-24 18:38:16 -06002548 if (type.getBasicType() == glslang::EbtBlock) {
John Kessenich6090df02016-06-30 21:18:02 -06002549 member = memberRemapper[glslangMembers][i];
John Kessenich0e737842017-03-24 18:38:16 -06002550 if (filterMember(glslangMember))
2551 continue;
2552 }
John Kessenich6090df02016-06-30 21:18:02 -06002553
2554 // modify just this child's view of the qualifier
2555 glslang::TQualifier memberQualifier = glslangMember.getQualifier();
2556 InheritQualifiers(memberQualifier, qualifier);
2557
2558 // using -1 above to indicate a hidden member
2559 if (member >= 0) {
2560 builder.addMemberName(spvType, member, glslangMember.getFieldName().c_str());
2561 addMemberDecoration(spvType, member, TranslateLayoutDecoration(glslangMember, memberQualifier.layoutMatrix));
2562 addMemberDecoration(spvType, member, TranslatePrecisionDecoration(glslangMember));
2563 // Add interpolation and auxiliary storage decorations only to top-level members of Input and Output storage classes
John Kessenich65ee2302017-02-06 18:44:52 -07002564 if (type.getQualifier().storage == glslang::EvqVaryingIn ||
2565 type.getQualifier().storage == glslang::EvqVaryingOut) {
2566 if (type.getBasicType() == glslang::EbtBlock ||
2567 glslangIntermediate->getSource() == glslang::EShSourceHlsl) {
John Kessenich6090df02016-06-30 21:18:02 -06002568 addMemberDecoration(spvType, member, TranslateInterpolationDecoration(memberQualifier));
2569 addMemberDecoration(spvType, member, TranslateAuxiliaryStorageDecoration(memberQualifier));
2570 }
2571 }
2572 addMemberDecoration(spvType, member, TranslateInvariantDecoration(memberQualifier));
2573
Rex Xu286ca432017-07-27 14:33:16 +08002574 if (type.getBasicType() == glslang::EbtBlock &&
2575 qualifier.storage == glslang::EvqBuffer) {
2576 // Add memory decorations only to top-level members of shader storage block
John Kessenich6090df02016-06-30 21:18:02 -06002577 std::vector<spv::Decoration> memory;
2578 TranslateMemoryDecoration(memberQualifier, memory);
2579 for (unsigned int i = 0; i < memory.size(); ++i)
2580 addMemberDecoration(spvType, member, memory[i]);
2581 }
2582
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002583 // Location assignment was already completed correctly by the front end,
2584 // just track whether a member needs to be decorated.
John Kessenich2f47bc92016-06-30 21:47:35 -06002585 // Ignore member locations if the container is an array, as that's
John Kessenich7cdf3fc2017-06-04 13:22:39 -06002586 // ill-specified and decisions have been made to not allow this.
2587 if (! type.isArray() && memberQualifier.hasLocation())
2588 builder.addMemberDecoration(spvType, member, spv::DecorationLocation, memberQualifier.layoutLocation);
John Kessenich6090df02016-06-30 21:18:02 -06002589
John Kessenich2f47bc92016-06-30 21:47:35 -06002590 if (qualifier.hasLocation()) // track for upcoming inheritance
2591 locationOffset += glslangIntermediate->computeTypeLocationSize(glslangMember);
2592
John Kessenich6090df02016-06-30 21:18:02 -06002593 // component, XFB, others
2594 if (glslangMember.getQualifier().hasComponent())
2595 builder.addMemberDecoration(spvType, member, spv::DecorationComponent, glslangMember.getQualifier().layoutComponent);
2596 if (glslangMember.getQualifier().hasXfbOffset())
2597 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, glslangMember.getQualifier().layoutXfbOffset);
2598 else if (explicitLayout != glslang::ElpNone) {
2599 // figure out what to do with offset, which is accumulating
2600 int nextOffset;
2601 updateMemberOffset(type, glslangMember, offset, nextOffset, explicitLayout, memberQualifier.layoutMatrix);
2602 if (offset >= 0)
2603 builder.addMemberDecoration(spvType, member, spv::DecorationOffset, offset);
2604 offset = nextOffset;
2605 }
2606
2607 if (glslangMember.isMatrix() && explicitLayout != glslang::ElpNone)
2608 builder.addMemberDecoration(spvType, member, spv::DecorationMatrixStride, getMatrixStride(glslangMember, explicitLayout, memberQualifier.layoutMatrix));
2609
2610 // built-in variable decorations
2611 spv::BuiltIn builtIn = TranslateBuiltInDecoration(glslangMember.getQualifier().builtIn, true);
John Kessenich4016e382016-07-15 11:53:56 -06002612 if (builtIn != spv::BuiltInMax)
John Kessenich6090df02016-06-30 21:18:02 -06002613 addMemberDecoration(spvType, member, spv::DecorationBuiltIn, (int)builtIn);
chaoc771d89f2017-01-13 01:10:53 -08002614
2615#ifdef NV_EXTENSIONS
2616 if (builtIn == spv::BuiltInLayer) {
2617 // SPV_NV_viewport_array2 extension
2618 if (glslangMember.getQualifier().layoutViewportRelative){
2619 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationViewportRelativeNV);
2620 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
2621 builder.addExtension(spv::E_SPV_NV_viewport_array2);
2622 }
2623 if (glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset != -2048){
2624 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, glslangMember.getQualifier().layoutSecondaryViewportRelativeOffset);
2625 builder.addCapability(spv::CapabilityShaderStereoViewNV);
2626 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
2627 }
2628 }
chaocdf3956c2017-02-14 14:52:34 -08002629 if (glslangMember.getQualifier().layoutPassthrough) {
2630 addMemberDecoration(spvType, member, (spv::Decoration)spv::DecorationPassthroughNV);
2631 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
2632 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
2633 }
chaoc771d89f2017-01-13 01:10:53 -08002634#endif
John Kessenich6090df02016-06-30 21:18:02 -06002635 }
2636 }
2637
2638 // Decorate the structure
2639 addDecoration(spvType, TranslateLayoutDecoration(type, qualifier.layoutMatrix));
John Kessenich67027182017-04-19 18:34:49 -06002640 addDecoration(spvType, TranslateBlockDecoration(type, glslangIntermediate->usingStorageBuffer()));
John Kessenich6090df02016-06-30 21:18:02 -06002641 if (type.getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
2642 builder.addCapability(spv::CapabilityGeometryStreams);
2643 builder.addDecoration(spvType, spv::DecorationStream, type.getQualifier().layoutStream);
2644 }
2645 if (glslangIntermediate->getXfbMode()) {
2646 builder.addCapability(spv::CapabilityTransformFeedback);
2647 if (type.getQualifier().hasXfbStride())
2648 builder.addDecoration(spvType, spv::DecorationXfbStride, type.getQualifier().layoutXfbStride);
2649 if (type.getQualifier().hasXfbBuffer())
2650 builder.addDecoration(spvType, spv::DecorationXfbBuffer, type.getQualifier().layoutXfbBuffer);
2651 }
2652}
2653
John Kessenich6c292d32016-02-15 20:58:50 -07002654// Turn the expression forming the array size into an id.
2655// This is not quite trivial, because of specialization constants.
2656// Sometimes, a raw constant is turned into an Id, and sometimes
2657// a specialization constant expression is.
2658spv::Id TGlslangToSpvTraverser::makeArraySizeId(const glslang::TArraySizes& arraySizes, int dim)
2659{
2660 // First, see if this is sized with a node, meaning a specialization constant:
2661 glslang::TIntermTyped* specNode = arraySizes.getDimNode(dim);
2662 if (specNode != nullptr) {
2663 builder.clearAccessChain();
2664 specNode->traverse(this);
2665 return accessChainLoad(specNode->getAsTyped()->getType());
2666 }
qining25262b32016-05-06 17:25:16 -04002667
John Kessenich6c292d32016-02-15 20:58:50 -07002668 // Otherwise, need a compile-time (front end) size, get it:
2669 int size = arraySizes.getDimSize(dim);
2670 assert(size > 0);
2671 return builder.makeUintConstant(size);
2672}
2673
John Kessenich103bef92016-02-08 21:38:15 -07002674// Wrap the builder's accessChainLoad to:
2675// - localize handling of RelaxedPrecision
2676// - use the SPIR-V inferred type instead of another conversion of the glslang type
2677// (avoids unnecessary work and possible type punning for structures)
2678// - do conversion of concrete to abstract type
John Kessenich32cfd492016-02-02 12:37:46 -07002679spv::Id TGlslangToSpvTraverser::accessChainLoad(const glslang::TType& type)
2680{
John Kessenich103bef92016-02-08 21:38:15 -07002681 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2682 spv::Id loadedId = builder.accessChainLoad(TranslatePrecisionDecoration(type), nominalTypeId);
2683
2684 // Need to convert to abstract types when necessary
Rex Xu27253232016-02-23 17:51:09 +08002685 if (type.getBasicType() == glslang::EbtBool) {
2686 if (builder.isScalarType(nominalTypeId)) {
2687 // Conversion for bool
2688 spv::Id boolType = builder.makeBoolType();
2689 if (nominalTypeId != boolType)
2690 loadedId = builder.createBinOp(spv::OpINotEqual, boolType, loadedId, builder.makeUintConstant(0));
2691 } else if (builder.isVectorType(nominalTypeId)) {
2692 // Conversion for bvec
2693 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2694 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
2695 if (nominalTypeId != bvecType)
2696 loadedId = builder.createBinOp(spv::OpINotEqual, bvecType, loadedId, makeSmearedConstant(builder.makeUintConstant(0), vecSize));
2697 }
2698 }
John Kessenich103bef92016-02-08 21:38:15 -07002699
2700 return loadedId;
John Kessenich32cfd492016-02-02 12:37:46 -07002701}
2702
Rex Xu27253232016-02-23 17:51:09 +08002703// Wrap the builder's accessChainStore to:
2704// - do conversion of concrete to abstract type
John Kessenich4bf71552016-09-02 11:20:21 -06002705//
2706// Implicitly uses the existing builder.accessChain as the storage target.
Rex Xu27253232016-02-23 17:51:09 +08002707void TGlslangToSpvTraverser::accessChainStore(const glslang::TType& type, spv::Id rvalue)
2708{
2709 // Need to convert to abstract types when necessary
2710 if (type.getBasicType() == glslang::EbtBool) {
2711 spv::Id nominalTypeId = builder.accessChainGetInferredType();
2712
2713 if (builder.isScalarType(nominalTypeId)) {
2714 // Conversion for bool
2715 spv::Id boolType = builder.makeBoolType();
John Kessenichb6cabc42017-05-19 23:29:50 -06002716 if (nominalTypeId != boolType) {
2717 // keep these outside arguments, for determinant order-of-evaluation
2718 spv::Id one = builder.makeUintConstant(1);
2719 spv::Id zero = builder.makeUintConstant(0);
2720 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
2721 } else if (builder.getTypeId(rvalue) != boolType)
John Kessenich80f92a12017-05-19 23:00:13 -06002722 rvalue = builder.createBinOp(spv::OpINotEqual, boolType, rvalue, builder.makeUintConstant(0));
Rex Xu27253232016-02-23 17:51:09 +08002723 } else if (builder.isVectorType(nominalTypeId)) {
2724 // Conversion for bvec
2725 int vecSize = builder.getNumTypeComponents(nominalTypeId);
2726 spv::Id bvecType = builder.makeVectorType(builder.makeBoolType(), vecSize);
John Kessenichb6cabc42017-05-19 23:29:50 -06002727 if (nominalTypeId != bvecType) {
2728 // keep these outside arguments, for determinant order-of-evaluation
John Kessenich7b8c3862017-05-19 23:44:51 -06002729 spv::Id one = makeSmearedConstant(builder.makeUintConstant(1), vecSize);
2730 spv::Id zero = makeSmearedConstant(builder.makeUintConstant(0), vecSize);
2731 rvalue = builder.createTriOp(spv::OpSelect, nominalTypeId, rvalue, one, zero);
John Kessenichb6cabc42017-05-19 23:29:50 -06002732 } else if (builder.getTypeId(rvalue) != bvecType)
John Kessenich80f92a12017-05-19 23:00:13 -06002733 rvalue = builder.createBinOp(spv::OpINotEqual, bvecType, rvalue,
2734 makeSmearedConstant(builder.makeUintConstant(0), vecSize));
Rex Xu27253232016-02-23 17:51:09 +08002735 }
2736 }
2737
2738 builder.accessChainStore(rvalue);
2739}
2740
John Kessenich4bf71552016-09-02 11:20:21 -06002741// For storing when types match at the glslang level, but not might match at the
2742// SPIR-V level.
2743//
2744// This especially happens when a single glslang type expands to multiple
John Kesseniched33e052016-10-06 12:59:51 -06002745// SPIR-V types, like a struct that is used in a member-undecorated way as well
John Kessenich4bf71552016-09-02 11:20:21 -06002746// as in a member-decorated way.
2747//
2748// NOTE: This function can handle any store request; if it's not special it
2749// simplifies to a simple OpStore.
2750//
2751// Implicitly uses the existing builder.accessChain as the storage target.
2752void TGlslangToSpvTraverser::multiTypeStore(const glslang::TType& type, spv::Id rValue)
2753{
John Kessenichb3e24e42016-09-11 12:33:43 -06002754 // we only do the complex path here if it's an aggregate
2755 if (! type.isStruct() && ! type.isArray()) {
John Kessenich4bf71552016-09-02 11:20:21 -06002756 accessChainStore(type, rValue);
2757 return;
2758 }
2759
John Kessenichb3e24e42016-09-11 12:33:43 -06002760 // and, it has to be a case of type aliasing
John Kessenich4bf71552016-09-02 11:20:21 -06002761 spv::Id rType = builder.getTypeId(rValue);
2762 spv::Id lValue = builder.accessChainGetLValue();
2763 spv::Id lType = builder.getContainedTypeId(builder.getTypeId(lValue));
2764 if (lType == rType) {
2765 accessChainStore(type, rValue);
2766 return;
2767 }
2768
John Kessenichb3e24e42016-09-11 12:33:43 -06002769 // Recursively (as needed) copy an aggregate type to a different aggregate type,
John Kessenich4bf71552016-09-02 11:20:21 -06002770 // where the two types were the same type in GLSL. This requires member
2771 // by member copy, recursively.
2772
John Kessenichb3e24e42016-09-11 12:33:43 -06002773 // If an array, copy element by element.
2774 if (type.isArray()) {
2775 glslang::TType glslangElementType(type, 0);
2776 spv::Id elementRType = builder.getContainedTypeId(rType);
2777 for (int index = 0; index < type.getOuterArraySize(); ++index) {
2778 // get the source member
2779 spv::Id elementRValue = builder.createCompositeExtract(rValue, elementRType, index);
John Kessenich4bf71552016-09-02 11:20:21 -06002780
John Kessenichb3e24e42016-09-11 12:33:43 -06002781 // set up the target storage
2782 builder.clearAccessChain();
2783 builder.setAccessChainLValue(lValue);
2784 builder.accessChainPush(builder.makeIntConstant(index));
John Kessenich4bf71552016-09-02 11:20:21 -06002785
John Kessenichb3e24e42016-09-11 12:33:43 -06002786 // store the member
2787 multiTypeStore(glslangElementType, elementRValue);
2788 }
2789 } else {
2790 assert(type.isStruct());
John Kessenich4bf71552016-09-02 11:20:21 -06002791
John Kessenichb3e24e42016-09-11 12:33:43 -06002792 // loop over structure members
2793 const glslang::TTypeList& members = *type.getStruct();
2794 for (int m = 0; m < (int)members.size(); ++m) {
2795 const glslang::TType& glslangMemberType = *members[m].type;
2796
2797 // get the source member
2798 spv::Id memberRType = builder.getContainedTypeId(rType, m);
2799 spv::Id memberRValue = builder.createCompositeExtract(rValue, memberRType, m);
2800
2801 // set up the target storage
2802 builder.clearAccessChain();
2803 builder.setAccessChainLValue(lValue);
2804 builder.accessChainPush(builder.makeIntConstant(m));
2805
2806 // store the member
2807 multiTypeStore(glslangMemberType, memberRValue);
2808 }
John Kessenich4bf71552016-09-02 11:20:21 -06002809 }
2810}
2811
John Kessenichf85e8062015-12-19 13:57:10 -07002812// Decide whether or not this type should be
2813// decorated with offsets and strides, and if so
2814// whether std140 or std430 rules should be applied.
2815glslang::TLayoutPacking TGlslangToSpvTraverser::getExplicitLayout(const glslang::TType& type) const
John Kessenich31ed4832015-09-09 17:51:38 -06002816{
John Kessenichf85e8062015-12-19 13:57:10 -07002817 // has to be a block
2818 if (type.getBasicType() != glslang::EbtBlock)
2819 return glslang::ElpNone;
2820
2821 // has to be a uniform or buffer block
2822 if (type.getQualifier().storage != glslang::EvqUniform &&
2823 type.getQualifier().storage != glslang::EvqBuffer)
2824 return glslang::ElpNone;
2825
2826 // return the layout to use
2827 switch (type.getQualifier().layoutPacking) {
2828 case glslang::ElpStd140:
2829 case glslang::ElpStd430:
2830 return type.getQualifier().layoutPacking;
2831 default:
2832 return glslang::ElpNone;
2833 }
John Kessenich31ed4832015-09-09 17:51:38 -06002834}
2835
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002836// Given an array type, returns the integer stride required for that array
John Kessenich3ac051e2015-12-20 11:29:16 -07002837int TGlslangToSpvTraverser::getArrayStride(const glslang::TType& arrayType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002838{
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002839 int size;
John Kessenich49987892015-12-29 17:11:44 -07002840 int stride;
2841 glslangIntermediate->getBaseAlignment(arrayType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kesseniche721f492015-12-06 19:17:49 -07002842
2843 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002844}
2845
John Kessenich49987892015-12-29 17:11:44 -07002846// 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 -07002847// when used as a member of an interface block
John Kessenich3ac051e2015-12-20 11:29:16 -07002848int TGlslangToSpvTraverser::getMatrixStride(const glslang::TType& matrixType, glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002849{
John Kessenich49987892015-12-29 17:11:44 -07002850 glslang::TType elementType;
2851 elementType.shallowCopy(matrixType);
2852 elementType.clearArraySizes();
2853
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002854 int size;
John Kessenich49987892015-12-29 17:11:44 -07002855 int stride;
2856 glslangIntermediate->getBaseAlignment(elementType, size, stride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
2857
2858 return stride;
Jason Ekstrand54aedf12015-09-05 09:50:58 -07002859}
2860
John Kessenich5e4b1242015-08-06 22:53:06 -06002861// Given a member type of a struct, realign the current offset for it, and compute
2862// the next (not yet aligned) offset for the next member, which will get aligned
2863// on the next call.
2864// 'currentOffset' should be passed in already initialized, ready to modify, and reflecting
2865// the migration of data from nextOffset -> currentOffset. It should be -1 on the first call.
2866// -1 means a non-forced member offset (no decoration needed).
John Kessenich735d7e52017-07-13 11:39:16 -06002867void TGlslangToSpvTraverser::updateMemberOffset(const glslang::TType& structType, const glslang::TType& memberType, int& currentOffset, int& nextOffset,
John Kessenich3ac051e2015-12-20 11:29:16 -07002868 glslang::TLayoutPacking explicitLayout, glslang::TLayoutMatrix matrixLayout)
John Kessenich5e4b1242015-08-06 22:53:06 -06002869{
2870 // this will get a positive value when deemed necessary
2871 nextOffset = -1;
2872
John Kessenich5e4b1242015-08-06 22:53:06 -06002873 // override anything in currentOffset with user-set offset
2874 if (memberType.getQualifier().hasOffset())
2875 currentOffset = memberType.getQualifier().layoutOffset;
2876
2877 // It could be that current linker usage in glslang updated all the layoutOffset,
2878 // in which case the following code does not matter. But, that's not quite right
2879 // once cross-compilation unit GLSL validation is done, as the original user
2880 // settings are needed in layoutOffset, and then the following will come into play.
2881
John Kessenichf85e8062015-12-19 13:57:10 -07002882 if (explicitLayout == glslang::ElpNone) {
John Kessenich5e4b1242015-08-06 22:53:06 -06002883 if (! memberType.getQualifier().hasOffset())
2884 currentOffset = -1;
2885
2886 return;
2887 }
2888
John Kessenichf85e8062015-12-19 13:57:10 -07002889 // Getting this far means we need explicit offsets
John Kessenich5e4b1242015-08-06 22:53:06 -06002890 if (currentOffset < 0)
2891 currentOffset = 0;
qining25262b32016-05-06 17:25:16 -04002892
John Kessenich5e4b1242015-08-06 22:53:06 -06002893 // Now, currentOffset is valid (either 0, or from a previous nextOffset),
2894 // but possibly not yet correctly aligned.
2895
2896 int memberSize;
John Kessenich49987892015-12-29 17:11:44 -07002897 int dummyStride;
2898 int memberAlignment = glslangIntermediate->getBaseAlignment(memberType, memberSize, dummyStride, explicitLayout == glslang::ElpStd140, matrixLayout == glslang::ElmRowMajor);
John Kessenich4f1403e2017-04-05 17:38:20 -06002899
2900 // Adjust alignment for HLSL rules
John Kessenich735d7e52017-07-13 11:39:16 -06002901 // TODO: make this consistent in early phases of code:
2902 // adjusting this late means inconsistencies with earlier code, which for reflection is an issue
2903 // Until reflection is brought in sync with these adjustments, don't apply to $Global,
2904 // which is the most likely to rely on reflection, and least likely to rely implicit layouts
John Kessenich4f1403e2017-04-05 17:38:20 -06002905 if (glslangIntermediate->usingHlslOFfsets() &&
John Kessenich735d7e52017-07-13 11:39:16 -06002906 ! memberType.isArray() && memberType.isVector() && structType.getTypeName().compare("$Global") != 0) {
John Kessenich4f1403e2017-04-05 17:38:20 -06002907 int dummySize;
2908 int componentAlignment = glslangIntermediate->getBaseAlignmentScalar(memberType, dummySize);
2909 if (componentAlignment <= 4)
2910 memberAlignment = componentAlignment;
2911 }
2912
2913 // Bump up to member alignment
John Kessenich5e4b1242015-08-06 22:53:06 -06002914 glslang::RoundToPow2(currentOffset, memberAlignment);
John Kessenich4f1403e2017-04-05 17:38:20 -06002915
2916 // Bump up to vec4 if there is a bad straddle
2917 if (glslangIntermediate->improperStraddle(memberType, memberSize, currentOffset))
2918 glslang::RoundToPow2(currentOffset, 16);
2919
John Kessenich5e4b1242015-08-06 22:53:06 -06002920 nextOffset = currentOffset + memberSize;
2921}
2922
David Netoa901ffe2016-06-08 14:11:40 +01002923void TGlslangToSpvTraverser::declareUseOfStructMember(const glslang::TTypeList& members, int glslangMember)
John Kessenichebb50532016-05-16 19:22:05 -06002924{
David Netoa901ffe2016-06-08 14:11:40 +01002925 const glslang::TBuiltInVariable glslangBuiltIn = members[glslangMember].type->getQualifier().builtIn;
2926 switch (glslangBuiltIn)
2927 {
2928 case glslang::EbvClipDistance:
2929 case glslang::EbvCullDistance:
2930 case glslang::EbvPointSize:
chaoc771d89f2017-01-13 01:10:53 -08002931#ifdef NV_EXTENSIONS
chaoc771d89f2017-01-13 01:10:53 -08002932 case glslang::EbvViewportMaskNV:
2933 case glslang::EbvSecondaryPositionNV:
2934 case glslang::EbvSecondaryViewportMaskNV:
chaocdf3956c2017-02-14 14:52:34 -08002935 case glslang::EbvPositionPerViewNV:
2936 case glslang::EbvViewportMaskPerViewNV:
chaoc771d89f2017-01-13 01:10:53 -08002937#endif
David Netoa901ffe2016-06-08 14:11:40 +01002938 // Generate the associated capability. Delegate to TranslateBuiltInDecoration.
2939 // Alternately, we could just call this for any glslang built-in, since the
2940 // capability already guards against duplicates.
2941 TranslateBuiltInDecoration(glslangBuiltIn, false);
2942 break;
2943 default:
2944 // Capabilities were already generated when the struct was declared.
2945 break;
2946 }
John Kessenichebb50532016-05-16 19:22:05 -06002947}
2948
John Kessenich6fccb3c2016-09-19 16:01:41 -06002949bool TGlslangToSpvTraverser::isShaderEntryPoint(const glslang::TIntermAggregate* node)
John Kessenich140f3df2015-06-26 16:58:36 -06002950{
John Kessenicheee9d532016-09-19 18:09:30 -06002951 return node->getName().compare(glslangIntermediate->getEntryPointMangledName().c_str()) == 0;
John Kessenich140f3df2015-06-26 16:58:36 -06002952}
2953
2954// Make all the functions, skeletally, without actually visiting their bodies.
2955void TGlslangToSpvTraverser::makeFunctions(const glslang::TIntermSequence& glslFunctions)
2956{
John Kessenichfad62972017-07-18 02:35:46 -06002957 const auto getParamDecorations = [](std::vector<spv::Decoration>& decorations, const glslang::TType& type) {
2958 spv::Decoration paramPrecision = TranslatePrecisionDecoration(type);
2959 if (paramPrecision != spv::NoPrecision)
2960 decorations.push_back(paramPrecision);
John Kessenich961cd352017-07-18 02:58:06 -06002961 TranslateMemoryDecoration(type.getQualifier(), decorations);
John Kessenichfad62972017-07-18 02:35:46 -06002962 };
2963
John Kessenich140f3df2015-06-26 16:58:36 -06002964 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
2965 glslang::TIntermAggregate* glslFunction = glslFunctions[f]->getAsAggregate();
John Kessenich6fccb3c2016-09-19 16:01:41 -06002966 if (! glslFunction || glslFunction->getOp() != glslang::EOpFunction || isShaderEntryPoint(glslFunction))
John Kessenich140f3df2015-06-26 16:58:36 -06002967 continue;
2968
2969 // We're on a user function. Set up the basic interface for the function now,
John Kessenich4bf71552016-09-02 11:20:21 -06002970 // so that it's available to call. Translating the body will happen later.
John Kessenich140f3df2015-06-26 16:58:36 -06002971 //
qining25262b32016-05-06 17:25:16 -04002972 // Typically (except for a "const in" parameter), an address will be passed to the
John Kessenich140f3df2015-06-26 16:58:36 -06002973 // function. What it is an address of varies:
2974 //
John Kessenich4bf71552016-09-02 11:20:21 -06002975 // - "in" parameters not marked as "const" can be written to without modifying the calling
2976 // argument so that write needs to be to a copy, hence the address of a copy works.
John Kessenich140f3df2015-06-26 16:58:36 -06002977 //
2978 // - "const in" parameters can just be the r-value, as no writes need occur.
2979 //
John Kessenich4bf71552016-09-02 11:20:21 -06002980 // - "out" and "inout" arguments can't be done as pointers to the calling argument, because
2981 // 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 -06002982
2983 std::vector<spv::Id> paramTypes;
John Kessenichfad62972017-07-18 02:35:46 -06002984 std::vector<std::vector<spv::Decoration>> paramDecorations; // list of decorations per parameter
John Kessenich140f3df2015-06-26 16:58:36 -06002985 glslang::TIntermSequence& parameters = glslFunction->getSequence()[0]->getAsAggregate()->getSequence();
2986
John Kessenichfad62972017-07-18 02:35:46 -06002987 bool implicitThis = (int)parameters.size() > 0 && parameters[0]->getAsSymbolNode()->getName() ==
2988 glslangIntermediate->implicitThisName;
John Kessenich37789792017-03-21 23:56:40 -06002989
John Kessenichfad62972017-07-18 02:35:46 -06002990 paramDecorations.resize(parameters.size());
John Kessenich140f3df2015-06-26 16:58:36 -06002991 for (int p = 0; p < (int)parameters.size(); ++p) {
2992 const glslang::TType& paramType = parameters[p]->getAsTyped()->getType();
2993 spv::Id typeId = convertGlslangToSpvType(paramType);
John Kessenich37789792017-03-21 23:56:40 -06002994 // can we pass by reference?
2995 if (paramType.containsOpaque() || // sampler, etc.
John Kessenich4960baa2017-03-19 18:09:59 -06002996 (paramType.getBasicType() == glslang::EbtBlock &&
John Kessenich37789792017-03-21 23:56:40 -06002997 paramType.getQualifier().storage == glslang::EvqBuffer) || // SSBO
John Kessenichaa3c64c2017-03-28 09:52:38 -06002998 (p == 0 && implicitThis)) // implicit 'this'
John Kessenicha5c5fb62017-05-05 05:09:58 -06002999 typeId = builder.makePointer(TranslateStorageClass(paramType), typeId);
Jason Ekstranded15ef12016-06-08 13:54:48 -07003000 else if (paramType.getQualifier().storage != glslang::EvqConstReadOnly)
John Kessenich140f3df2015-06-26 16:58:36 -06003001 typeId = builder.makePointer(spv::StorageClassFunction, typeId);
3002 else
John Kessenich4bf71552016-09-02 11:20:21 -06003003 rValueParameters.insert(parameters[p]->getAsSymbolNode()->getId());
John Kessenichfad62972017-07-18 02:35:46 -06003004 getParamDecorations(paramDecorations[p], paramType);
John Kessenich140f3df2015-06-26 16:58:36 -06003005 paramTypes.push_back(typeId);
3006 }
3007
3008 spv::Block* functionBlock;
John Kessenich32cfd492016-02-02 12:37:46 -07003009 spv::Function *function = builder.makeFunctionEntry(TranslatePrecisionDecoration(glslFunction->getType()),
3010 convertGlslangToSpvType(glslFunction->getType()),
John Kessenichfad62972017-07-18 02:35:46 -06003011 glslFunction->getName().c_str(), paramTypes,
3012 paramDecorations, &functionBlock);
John Kessenich37789792017-03-21 23:56:40 -06003013 if (implicitThis)
3014 function->setImplicitThis();
John Kessenich140f3df2015-06-26 16:58:36 -06003015
3016 // Track function to emit/call later
3017 functionMap[glslFunction->getName().c_str()] = function;
3018
3019 // Set the parameter id's
3020 for (int p = 0; p < (int)parameters.size(); ++p) {
3021 symbolValues[parameters[p]->getAsSymbolNode()->getId()] = function->getParamId(p);
3022 // give a name too
3023 builder.addName(function->getParamId(p), parameters[p]->getAsSymbolNode()->getName().c_str());
3024 }
3025 }
3026}
3027
3028// Process all the initializers, while skipping the functions and link objects
3029void TGlslangToSpvTraverser::makeGlobalInitializers(const glslang::TIntermSequence& initializers)
3030{
3031 builder.setBuildPoint(shaderEntry->getLastBlock());
3032 for (int i = 0; i < (int)initializers.size(); ++i) {
3033 glslang::TIntermAggregate* initializer = initializers[i]->getAsAggregate();
3034 if (initializer && initializer->getOp() != glslang::EOpFunction && initializer->getOp() != glslang::EOpLinkerObjects) {
3035
3036 // We're on a top-level node that's not a function. Treat as an initializer, whose
John Kessenich6fccb3c2016-09-19 16:01:41 -06003037 // code goes into the beginning of the entry point.
John Kessenich140f3df2015-06-26 16:58:36 -06003038 initializer->traverse(this);
3039 }
3040 }
3041}
3042
3043// Process all the functions, while skipping initializers.
3044void TGlslangToSpvTraverser::visitFunctions(const glslang::TIntermSequence& glslFunctions)
3045{
3046 for (int f = 0; f < (int)glslFunctions.size(); ++f) {
3047 glslang::TIntermAggregate* node = glslFunctions[f]->getAsAggregate();
John Kessenich6a60c2f2016-12-08 21:01:59 -07003048 if (node && (node->getOp() == glslang::EOpFunction || node->getOp() == glslang::EOpLinkerObjects))
John Kessenich140f3df2015-06-26 16:58:36 -06003049 node->traverse(this);
3050 }
3051}
3052
3053void TGlslangToSpvTraverser::handleFunctionEntry(const glslang::TIntermAggregate* node)
3054{
qining25262b32016-05-06 17:25:16 -04003055 // SPIR-V functions should already be in the functionMap from the prepass
John Kessenich140f3df2015-06-26 16:58:36 -06003056 // that called makeFunctions().
John Kesseniched33e052016-10-06 12:59:51 -06003057 currentFunction = functionMap[node->getName().c_str()];
3058 spv::Block* functionBlock = currentFunction->getEntryBlock();
John Kessenich140f3df2015-06-26 16:58:36 -06003059 builder.setBuildPoint(functionBlock);
3060}
3061
Rex Xu04db3f52015-09-16 11:44:02 +08003062void TGlslangToSpvTraverser::translateArguments(const glslang::TIntermAggregate& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003063{
Rex Xufc618912015-09-09 16:42:49 +08003064 const glslang::TIntermSequence& glslangArguments = node.getSequence();
Rex Xu48edadf2015-12-31 16:11:41 +08003065
3066 glslang::TSampler sampler = {};
3067 bool cubeCompare = false;
Rex Xu5eafa472016-02-19 22:24:03 +08003068 if (node.isTexture() || node.isImage()) {
Rex Xu48edadf2015-12-31 16:11:41 +08003069 sampler = glslangArguments[0]->getAsTyped()->getType().getSampler();
3070 cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3071 }
3072
John Kessenich140f3df2015-06-26 16:58:36 -06003073 for (int i = 0; i < (int)glslangArguments.size(); ++i) {
3074 builder.clearAccessChain();
3075 glslangArguments[i]->traverse(this);
Rex Xufc618912015-09-09 16:42:49 +08003076
3077 // Special case l-value operands
3078 bool lvalue = false;
3079 switch (node.getOp()) {
3080 case glslang::EOpImageAtomicAdd:
3081 case glslang::EOpImageAtomicMin:
3082 case glslang::EOpImageAtomicMax:
3083 case glslang::EOpImageAtomicAnd:
3084 case glslang::EOpImageAtomicOr:
3085 case glslang::EOpImageAtomicXor:
3086 case glslang::EOpImageAtomicExchange:
3087 case glslang::EOpImageAtomicCompSwap:
3088 if (i == 0)
3089 lvalue = true;
3090 break;
Rex Xu5eafa472016-02-19 22:24:03 +08003091 case glslang::EOpSparseImageLoad:
3092 if ((sampler.ms && i == 3) || (! sampler.ms && i == 2))
3093 lvalue = true;
3094 break;
Rex Xu48edadf2015-12-31 16:11:41 +08003095 case glslang::EOpSparseTexture:
3096 if ((cubeCompare && i == 3) || (! cubeCompare && i == 2))
3097 lvalue = true;
3098 break;
3099 case glslang::EOpSparseTextureClamp:
3100 if ((cubeCompare && i == 4) || (! cubeCompare && i == 3))
3101 lvalue = true;
3102 break;
3103 case glslang::EOpSparseTextureLod:
3104 case glslang::EOpSparseTextureOffset:
3105 if (i == 3)
3106 lvalue = true;
3107 break;
3108 case glslang::EOpSparseTextureFetch:
3109 if ((sampler.dim != glslang::EsdRect && i == 3) || (sampler.dim == glslang::EsdRect && i == 2))
3110 lvalue = true;
3111 break;
3112 case glslang::EOpSparseTextureFetchOffset:
3113 if ((sampler.dim != glslang::EsdRect && i == 4) || (sampler.dim == glslang::EsdRect && i == 3))
3114 lvalue = true;
3115 break;
3116 case glslang::EOpSparseTextureLodOffset:
3117 case glslang::EOpSparseTextureGrad:
3118 case glslang::EOpSparseTextureOffsetClamp:
3119 if (i == 4)
3120 lvalue = true;
3121 break;
3122 case glslang::EOpSparseTextureGradOffset:
3123 case glslang::EOpSparseTextureGradClamp:
3124 if (i == 5)
3125 lvalue = true;
3126 break;
3127 case glslang::EOpSparseTextureGradOffsetClamp:
3128 if (i == 6)
3129 lvalue = true;
3130 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003131 case glslang::EOpSparseTextureGather:
Rex Xu48edadf2015-12-31 16:11:41 +08003132 if ((sampler.shadow && i == 3) || (! sampler.shadow && i == 2))
3133 lvalue = true;
3134 break;
3135 case glslang::EOpSparseTextureGatherOffset:
3136 case glslang::EOpSparseTextureGatherOffsets:
3137 if ((sampler.shadow && i == 4) || (! sampler.shadow && i == 3))
3138 lvalue = true;
3139 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003140#ifdef AMD_EXTENSIONS
3141 case glslang::EOpSparseTextureGatherLod:
3142 if (i == 3)
3143 lvalue = true;
3144 break;
3145 case glslang::EOpSparseTextureGatherLodOffset:
3146 case glslang::EOpSparseTextureGatherLodOffsets:
3147 if (i == 4)
3148 lvalue = true;
3149 break;
Rex Xu129799a2017-07-05 17:23:28 +08003150 case glslang::EOpSparseImageLoadLod:
3151 if (i == 3)
3152 lvalue = true;
3153 break;
Rex Xu225e0fc2016-11-17 17:47:59 +08003154#endif
Rex Xufc618912015-09-09 16:42:49 +08003155 default:
3156 break;
3157 }
3158
Rex Xu6b86d492015-09-16 17:48:22 +08003159 if (lvalue)
Rex Xufc618912015-09-09 16:42:49 +08003160 arguments.push_back(builder.accessChainGetLValue());
Rex Xu6b86d492015-09-16 17:48:22 +08003161 else
John Kessenich32cfd492016-02-02 12:37:46 -07003162 arguments.push_back(accessChainLoad(glslangArguments[i]->getAsTyped()->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003163 }
3164}
3165
John Kessenichfc51d282015-08-19 13:34:18 -06003166void TGlslangToSpvTraverser::translateArguments(glslang::TIntermUnary& node, std::vector<spv::Id>& arguments)
John Kessenich140f3df2015-06-26 16:58:36 -06003167{
John Kessenichfc51d282015-08-19 13:34:18 -06003168 builder.clearAccessChain();
3169 node.getOperand()->traverse(this);
John Kessenich32cfd492016-02-02 12:37:46 -07003170 arguments.push_back(accessChainLoad(node.getOperand()->getType()));
John Kessenichfc51d282015-08-19 13:34:18 -06003171}
John Kessenich140f3df2015-06-26 16:58:36 -06003172
John Kessenichfc51d282015-08-19 13:34:18 -06003173spv::Id TGlslangToSpvTraverser::createImageTextureFunctionCall(glslang::TIntermOperator* node)
3174{
John Kesseniche485c7a2017-05-31 18:50:53 -06003175 if (! node->isImage() && ! node->isTexture())
John Kessenichfc51d282015-08-19 13:34:18 -06003176 return spv::NoResult;
John Kesseniche485c7a2017-05-31 18:50:53 -06003177
3178 builder.setLine(node->getLoc().line);
3179
John Kessenich8c8505c2016-07-26 12:50:38 -06003180 auto resultType = [&node,this]{ return convertGlslangToSpvType(node->getType()); };
John Kessenich140f3df2015-06-26 16:58:36 -06003181
John Kessenichfc51d282015-08-19 13:34:18 -06003182 // Process a GLSL texturing op (will be SPV image)
John Kessenichfc51d282015-08-19 13:34:18 -06003183 const glslang::TSampler sampler = node->getAsAggregate() ? node->getAsAggregate()->getSequence()[0]->getAsTyped()->getType().getSampler()
3184 : node->getAsUnaryNode()->getOperand()->getAsTyped()->getType().getSampler();
3185 std::vector<spv::Id> arguments;
3186 if (node->getAsAggregate())
Rex Xufc618912015-09-09 16:42:49 +08003187 translateArguments(*node->getAsAggregate(), arguments);
John Kessenichfc51d282015-08-19 13:34:18 -06003188 else
3189 translateArguments(*node->getAsUnaryNode(), arguments);
John Kessenichf6640762016-08-01 19:44:00 -06003190 spv::Decoration precision = TranslatePrecisionDecoration(node->getOperationPrecision());
John Kessenichfc51d282015-08-19 13:34:18 -06003191
3192 spv::Builder::TextureParameters params = { };
3193 params.sampler = arguments[0];
3194
Rex Xu04db3f52015-09-16 11:44:02 +08003195 glslang::TCrackedTextureOp cracked;
3196 node->crackTexture(sampler, cracked);
3197
amhagan05506bb2017-06-13 16:53:02 -04003198 const bool isUnsignedResult = node->getType().getBasicType() == glslang::EbtUint;
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003199
John Kessenichfc51d282015-08-19 13:34:18 -06003200 // Check for queries
3201 if (cracked.query) {
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003202 // OpImageQueryLod works on a sampled image, for other queries the image has to be extracted first
3203 if (node->getOp() != glslang::EOpTextureQueryLod && builder.isSampledImage(params.sampler))
John Kessenich33661452015-12-08 19:32:47 -07003204 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
Maciej Jesionowski7208a972016-10-12 15:40:37 +02003205
John Kessenichfc51d282015-08-19 13:34:18 -06003206 switch (node->getOp()) {
3207 case glslang::EOpImageQuerySize:
3208 case glslang::EOpTextureQuerySize:
John Kessenich140f3df2015-06-26 16:58:36 -06003209 if (arguments.size() > 1) {
3210 params.lod = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003211 return builder.createTextureQueryCall(spv::OpImageQuerySizeLod, params, isUnsignedResult);
John Kessenich140f3df2015-06-26 16:58:36 -06003212 } else
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003213 return builder.createTextureQueryCall(spv::OpImageQuerySize, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003214 case glslang::EOpImageQuerySamples:
3215 case glslang::EOpTextureQuerySamples:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003216 return builder.createTextureQueryCall(spv::OpImageQuerySamples, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003217 case glslang::EOpTextureQueryLod:
3218 params.coords = arguments[1];
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003219 return builder.createTextureQueryCall(spv::OpImageQueryLod, params, isUnsignedResult);
John Kessenichfc51d282015-08-19 13:34:18 -06003220 case glslang::EOpTextureQueryLevels:
steve-lunarg0b5c2ae2017-03-10 12:45:50 -07003221 return builder.createTextureQueryCall(spv::OpImageQueryLevels, params, isUnsignedResult);
Rex Xu48edadf2015-12-31 16:11:41 +08003222 case glslang::EOpSparseTexelsResident:
3223 return builder.createUnaryOp(spv::OpImageSparseTexelsResident, builder.makeBoolType(), arguments[0]);
John Kessenichfc51d282015-08-19 13:34:18 -06003224 default:
3225 assert(0);
3226 break;
John Kessenich140f3df2015-06-26 16:58:36 -06003227 }
John Kessenich140f3df2015-06-26 16:58:36 -06003228 }
3229
Rex Xufc618912015-09-09 16:42:49 +08003230 // Check for image functions other than queries
3231 if (node->isImage()) {
John Kessenich56bab042015-09-16 10:54:31 -06003232 std::vector<spv::Id> operands;
3233 auto opIt = arguments.begin();
3234 operands.push_back(*(opIt++));
John Kessenich6c292d32016-02-15 20:58:50 -07003235
3236 // Handle subpass operations
3237 // TODO: GLSL should change to have the "MS" only on the type rather than the
3238 // built-in function.
3239 if (cracked.subpass) {
3240 // add on the (0,0) coordinate
3241 spv::Id zero = builder.makeIntConstant(0);
3242 std::vector<spv::Id> comps;
3243 comps.push_back(zero);
3244 comps.push_back(zero);
3245 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3246 if (sampler.ms) {
3247 operands.push_back(spv::ImageOperandsSampleMask);
3248 operands.push_back(*(opIt++));
3249 }
John Kessenich8c8505c2016-07-26 12:50:38 -06003250 return builder.createOp(spv::OpImageRead, resultType(), operands);
John Kessenich6c292d32016-02-15 20:58:50 -07003251 }
3252
John Kessenich56bab042015-09-16 10:54:31 -06003253 operands.push_back(*(opIt++));
Rex Xu129799a2017-07-05 17:23:28 +08003254#ifdef AMD_EXTENSIONS
3255 if (node->getOp() == glslang::EOpImageLoad || node->getOp() == glslang::EOpImageLoadLod) {
3256#else
John Kessenich56bab042015-09-16 10:54:31 -06003257 if (node->getOp() == glslang::EOpImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003258#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003259 if (sampler.ms) {
3260 operands.push_back(spv::ImageOperandsSampleMask);
Rex Xu7beb4412015-12-15 17:52:45 +08003261 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003262#ifdef AMD_EXTENSIONS
3263 } else if (cracked.lod) {
3264 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3265 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3266
3267 operands.push_back(spv::ImageOperandsLodMask);
3268 operands.push_back(*opIt);
3269#endif
John Kessenich55e7d112015-11-15 21:33:39 -07003270 }
John Kessenich5d0fa972016-02-15 11:57:00 -07003271 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3272 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
John Kessenich8c8505c2016-07-26 12:50:38 -06003273 return builder.createOp(spv::OpImageRead, resultType(), operands);
Rex Xu129799a2017-07-05 17:23:28 +08003274#ifdef AMD_EXTENSIONS
3275 } else if (node->getOp() == glslang::EOpImageStore || node->getOp() == glslang::EOpImageStoreLod) {
3276#else
John Kessenich56bab042015-09-16 10:54:31 -06003277 } else if (node->getOp() == glslang::EOpImageStore) {
Rex Xu129799a2017-07-05 17:23:28 +08003278#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003279 if (sampler.ms) {
3280 operands.push_back(*(opIt + 1));
3281 operands.push_back(spv::ImageOperandsSampleMask);
3282 operands.push_back(*opIt);
Rex Xu129799a2017-07-05 17:23:28 +08003283#ifdef AMD_EXTENSIONS
3284 } else if (cracked.lod) {
3285 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3286 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3287
3288 operands.push_back(*(opIt + 1));
3289 operands.push_back(spv::ImageOperandsLodMask);
3290 operands.push_back(*opIt);
3291#endif
Rex Xu7beb4412015-12-15 17:52:45 +08003292 } else
3293 operands.push_back(*opIt);
John Kessenich56bab042015-09-16 10:54:31 -06003294 builder.createNoResultOp(spv::OpImageWrite, operands);
John Kessenich5d0fa972016-02-15 11:57:00 -07003295 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3296 builder.addCapability(spv::CapabilityStorageImageWriteWithoutFormat);
John Kessenich56bab042015-09-16 10:54:31 -06003297 return spv::NoResult;
Rex Xu129799a2017-07-05 17:23:28 +08003298#ifdef AMD_EXTENSIONS
3299 } else if (node->getOp() == glslang::EOpSparseImageLoad || node->getOp() == glslang::EOpSparseImageLoadLod) {
3300#else
Rex Xu5eafa472016-02-19 22:24:03 +08003301 } else if (node->getOp() == glslang::EOpSparseImageLoad) {
Rex Xu129799a2017-07-05 17:23:28 +08003302#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003303 builder.addCapability(spv::CapabilitySparseResidency);
3304 if (builder.getImageTypeFormat(builder.getImageType(operands.front())) == spv::ImageFormatUnknown)
3305 builder.addCapability(spv::CapabilityStorageImageReadWithoutFormat);
3306
3307 if (sampler.ms) {
3308 operands.push_back(spv::ImageOperandsSampleMask);
3309 operands.push_back(*opIt++);
Rex Xu129799a2017-07-05 17:23:28 +08003310#ifdef AMD_EXTENSIONS
3311 } else if (cracked.lod) {
3312 builder.addExtension(spv::E_SPV_AMD_shader_image_load_store_lod);
3313 builder.addCapability(spv::CapabilityImageReadWriteLodAMD);
3314
3315 operands.push_back(spv::ImageOperandsLodMask);
3316 operands.push_back(*opIt++);
3317#endif
Rex Xu5eafa472016-02-19 22:24:03 +08003318 }
3319
3320 // Create the return type that was a special structure
3321 spv::Id texelOut = *opIt;
John Kessenich8c8505c2016-07-26 12:50:38 -06003322 spv::Id typeId0 = resultType();
Rex Xu5eafa472016-02-19 22:24:03 +08003323 spv::Id typeId1 = builder.getDerefTypeId(texelOut);
3324 spv::Id resultTypeId = builder.makeStructResultType(typeId0, typeId1);
3325
3326 spv::Id resultId = builder.createOp(spv::OpImageSparseRead, resultTypeId, operands);
3327
3328 // Decode the return type
3329 builder.createStore(builder.createCompositeExtract(resultId, typeId1, 1), texelOut);
3330 return builder.createCompositeExtract(resultId, typeId0, 0);
John Kessenichcd261442016-01-22 09:54:12 -07003331 } else {
Rex Xu6b86d492015-09-16 17:48:22 +08003332 // Process image atomic operations
3333
3334 // GLSL "IMAGE_PARAMS" will involve in constructing an image texel pointer and this pointer,
3335 // as the first source operand, is required by SPIR-V atomic operations.
John Kessenichcd261442016-01-22 09:54:12 -07003336 operands.push_back(sampler.ms ? *(opIt++) : builder.makeUintConstant(0)); // For non-MS, the value should be 0
John Kessenich140f3df2015-06-26 16:58:36 -06003337
John Kessenich8c8505c2016-07-26 12:50:38 -06003338 spv::Id resultTypeId = builder.makePointer(spv::StorageClassImage, resultType());
John Kessenich56bab042015-09-16 10:54:31 -06003339 spv::Id pointer = builder.createOp(spv::OpImageTexelPointer, resultTypeId, operands);
Rex Xufc618912015-09-09 16:42:49 +08003340
3341 std::vector<spv::Id> operands;
3342 operands.push_back(pointer);
3343 for (; opIt != arguments.end(); ++opIt)
3344 operands.push_back(*opIt);
3345
John Kessenich8c8505c2016-07-26 12:50:38 -06003346 return createAtomicOperation(node->getOp(), precision, resultType(), operands, node->getBasicType());
Rex Xufc618912015-09-09 16:42:49 +08003347 }
3348 }
3349
amhagan05506bb2017-06-13 16:53:02 -04003350#ifdef AMD_EXTENSIONS
3351 // Check for fragment mask functions other than queries
3352 if (cracked.fragMask) {
3353 assert(sampler.ms);
3354
3355 auto opIt = arguments.begin();
3356 std::vector<spv::Id> operands;
3357
3358 // Extract the image if necessary
3359 if (builder.isSampledImage(params.sampler))
3360 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3361
3362 operands.push_back(params.sampler);
3363 ++opIt;
3364
3365 if (sampler.isSubpass()) {
3366 // add on the (0,0) coordinate
3367 spv::Id zero = builder.makeIntConstant(0);
3368 std::vector<spv::Id> comps;
3369 comps.push_back(zero);
3370 comps.push_back(zero);
3371 operands.push_back(builder.makeCompositeConstant(builder.makeVectorType(builder.makeIntType(32), 2), comps));
3372 }
3373
3374 for (; opIt != arguments.end(); ++opIt)
3375 operands.push_back(*opIt);
3376
3377 spv::Op fragMaskOp = spv::OpNop;
3378 if (node->getOp() == glslang::EOpFragmentMaskFetch)
3379 fragMaskOp = spv::OpFragmentMaskFetchAMD;
3380 else if (node->getOp() == glslang::EOpFragmentFetch)
3381 fragMaskOp = spv::OpFragmentFetchAMD;
3382
3383 builder.addExtension(spv::E_SPV_AMD_shader_fragment_mask);
3384 builder.addCapability(spv::CapabilityFragmentMaskAMD);
3385 return builder.createOp(fragMaskOp, resultType(), operands);
3386 }
3387#endif
3388
Rex Xufc618912015-09-09 16:42:49 +08003389 // Check for texture functions other than queries
Rex Xu48edadf2015-12-31 16:11:41 +08003390 bool sparse = node->isSparseTexture();
Rex Xu71519fe2015-11-11 15:35:47 +08003391 bool cubeCompare = sampler.dim == glslang::EsdCube && sampler.arrayed && sampler.shadow;
3392
John Kessenichfc51d282015-08-19 13:34:18 -06003393 // check for bias argument
3394 bool bias = false;
Rex Xu225e0fc2016-11-17 17:47:59 +08003395#ifdef AMD_EXTENSIONS
3396 if (! cracked.lod && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
3397#else
Rex Xu71519fe2015-11-11 15:35:47 +08003398 if (! cracked.lod && ! cracked.gather && ! cracked.grad && ! cracked.fetch && ! cubeCompare) {
Rex Xu225e0fc2016-11-17 17:47:59 +08003399#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003400 int nonBiasArgCount = 2;
Rex Xu225e0fc2016-11-17 17:47:59 +08003401#ifdef AMD_EXTENSIONS
3402 if (cracked.gather)
3403 ++nonBiasArgCount; // comp argument should be present when bias argument is present
3404#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003405 if (cracked.offset)
3406 ++nonBiasArgCount;
Rex Xu225e0fc2016-11-17 17:47:59 +08003407#ifdef AMD_EXTENSIONS
3408 else if (cracked.offsets)
3409 ++nonBiasArgCount;
3410#endif
John Kessenichfc51d282015-08-19 13:34:18 -06003411 if (cracked.grad)
3412 nonBiasArgCount += 2;
Rex Xu48edadf2015-12-31 16:11:41 +08003413 if (cracked.lodClamp)
3414 ++nonBiasArgCount;
3415 if (sparse)
3416 ++nonBiasArgCount;
John Kessenichfc51d282015-08-19 13:34:18 -06003417
3418 if ((int)arguments.size() > nonBiasArgCount)
3419 bias = true;
3420 }
3421
John Kessenicha5c33d62016-06-02 23:45:21 -06003422 // See if the sampler param should really be just the SPV image part
3423 if (cracked.fetch) {
3424 // a fetch needs to have the image extracted first
3425 if (builder.isSampledImage(params.sampler))
3426 params.sampler = builder.createUnaryOp(spv::OpImage, builder.getImageType(params.sampler), params.sampler);
3427 }
3428
Rex Xu225e0fc2016-11-17 17:47:59 +08003429#ifdef AMD_EXTENSIONS
3430 if (cracked.gather) {
3431 const auto& sourceExtensions = glslangIntermediate->getRequestedExtensions();
3432 if (bias || cracked.lod ||
3433 sourceExtensions.find(glslang::E_GL_AMD_texture_gather_bias_lod) != sourceExtensions.end()) {
3434 builder.addExtension(spv::E_SPV_AMD_texture_gather_bias_lod);
Rex Xu301a2bc2017-06-14 23:09:39 +08003435 builder.addCapability(spv::CapabilityImageGatherBiasLodAMD);
Rex Xu225e0fc2016-11-17 17:47:59 +08003436 }
3437 }
3438#endif
3439
John Kessenichfc51d282015-08-19 13:34:18 -06003440 // set the rest of the arguments
John Kessenich55e7d112015-11-15 21:33:39 -07003441
John Kessenichfc51d282015-08-19 13:34:18 -06003442 params.coords = arguments[1];
3443 int extraArgs = 0;
John Kessenich019f08f2016-02-15 15:40:42 -07003444 bool noImplicitLod = false;
John Kessenich55e7d112015-11-15 21:33:39 -07003445
3446 // sort out where Dref is coming from
Rex Xu48edadf2015-12-31 16:11:41 +08003447 if (cubeCompare) {
John Kessenichfc51d282015-08-19 13:34:18 -06003448 params.Dref = arguments[2];
Rex Xu48edadf2015-12-31 16:11:41 +08003449 ++extraArgs;
3450 } else if (sampler.shadow && cracked.gather) {
John Kessenich55e7d112015-11-15 21:33:39 -07003451 params.Dref = arguments[2];
3452 ++extraArgs;
3453 } else if (sampler.shadow) {
John Kessenichfc51d282015-08-19 13:34:18 -06003454 std::vector<spv::Id> indexes;
John Kessenich76d4dfc2016-06-16 12:43:23 -06003455 int dRefComp;
John Kessenichfc51d282015-08-19 13:34:18 -06003456 if (cracked.proj)
John Kessenich76d4dfc2016-06-16 12:43:23 -06003457 dRefComp = 2; // "The resulting 3rd component of P in the shadow forms is used as Dref"
John Kessenichfc51d282015-08-19 13:34:18 -06003458 else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003459 dRefComp = builder.getNumComponents(params.coords) - 1;
3460 indexes.push_back(dRefComp);
John Kessenichfc51d282015-08-19 13:34:18 -06003461 params.Dref = builder.createCompositeExtract(params.coords, builder.getScalarTypeId(builder.getTypeId(params.coords)), indexes);
3462 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003463
3464 // lod
John Kessenichfc51d282015-08-19 13:34:18 -06003465 if (cracked.lod) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003466 params.lod = arguments[2 + extraArgs];
John Kessenichfc51d282015-08-19 13:34:18 -06003467 ++extraArgs;
John Kessenich019f08f2016-02-15 15:40:42 -07003468 } else if (glslangIntermediate->getStage() != EShLangFragment) {
3469 // we need to invent the default lod for an explicit lod instruction for a non-fragment stage
3470 noImplicitLod = true;
3471 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003472
3473 // multisample
John Kessenich019f08f2016-02-15 15:40:42 -07003474 if (sampler.ms) {
LoopDawgef94b1a2017-07-24 18:45:37 -06003475 params.sample = arguments[2 + extraArgs]; // For MS, "sample" should be specified
Rex Xu04db3f52015-09-16 11:44:02 +08003476 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003477 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003478
3479 // gradient
John Kessenichfc51d282015-08-19 13:34:18 -06003480 if (cracked.grad) {
3481 params.gradX = arguments[2 + extraArgs];
3482 params.gradY = arguments[3 + extraArgs];
3483 extraArgs += 2;
3484 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003485
3486 // offset and offsets
John Kessenich55e7d112015-11-15 21:33:39 -07003487 if (cracked.offset) {
John Kessenichfc51d282015-08-19 13:34:18 -06003488 params.offset = arguments[2 + extraArgs];
3489 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003490 } else if (cracked.offsets) {
3491 params.offsets = arguments[2 + extraArgs];
3492 ++extraArgs;
John Kessenichfc51d282015-08-19 13:34:18 -06003493 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003494
3495 // lod clamp
Rex Xu48edadf2015-12-31 16:11:41 +08003496 if (cracked.lodClamp) {
3497 params.lodClamp = arguments[2 + extraArgs];
3498 ++extraArgs;
3499 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003500
3501 // sparse
Rex Xu48edadf2015-12-31 16:11:41 +08003502 if (sparse) {
3503 params.texelOut = arguments[2 + extraArgs];
3504 ++extraArgs;
3505 }
John Kessenich76d4dfc2016-06-16 12:43:23 -06003506
John Kessenich76d4dfc2016-06-16 12:43:23 -06003507 // gather component
John Kessenich55e7d112015-11-15 21:33:39 -07003508 if (cracked.gather && ! sampler.shadow) {
3509 // default component is 0, if missing, otherwise an argument
3510 if (2 + extraArgs < (int)arguments.size()) {
John Kessenich76d4dfc2016-06-16 12:43:23 -06003511 params.component = arguments[2 + extraArgs];
John Kessenich55e7d112015-11-15 21:33:39 -07003512 ++extraArgs;
Rex Xu225e0fc2016-11-17 17:47:59 +08003513 } else
John Kessenich76d4dfc2016-06-16 12:43:23 -06003514 params.component = builder.makeIntConstant(0);
Rex Xu225e0fc2016-11-17 17:47:59 +08003515 }
3516
3517 // bias
3518 if (bias) {
3519 params.bias = arguments[2 + extraArgs];
3520 ++extraArgs;
John Kessenich55e7d112015-11-15 21:33:39 -07003521 }
John Kessenichfc51d282015-08-19 13:34:18 -06003522
John Kessenich65336482016-06-16 14:06:26 -06003523 // projective component (might not to move)
3524 // GLSL: "The texture coordinates consumed from P, not including the last component of P,
3525 // are divided by the last component of P."
3526 // SPIR-V: "... (u [, v] [, w], q)... It may be a vector larger than needed, but all
3527 // unused components will appear after all used components."
3528 if (cracked.proj) {
3529 int projSourceComp = builder.getNumComponents(params.coords) - 1;
3530 int projTargetComp;
3531 switch (sampler.dim) {
3532 case glslang::Esd1D: projTargetComp = 1; break;
3533 case glslang::Esd2D: projTargetComp = 2; break;
3534 case glslang::EsdRect: projTargetComp = 2; break;
3535 default: projTargetComp = projSourceComp; break;
3536 }
3537 // copy the projective coordinate if we have to
3538 if (projTargetComp != projSourceComp) {
John Kessenichecba76f2017-01-06 00:34:48 -07003539 spv::Id projComp = builder.createCompositeExtract(params.coords,
John Kessenich65336482016-06-16 14:06:26 -06003540 builder.getScalarTypeId(builder.getTypeId(params.coords)),
3541 projSourceComp);
3542 params.coords = builder.createCompositeInsert(projComp, params.coords,
3543 builder.getTypeId(params.coords), projTargetComp);
3544 }
3545 }
3546
John Kessenich8c8505c2016-07-26 12:50:38 -06003547 return builder.createTextureCall(precision, resultType(), sparse, cracked.fetch, cracked.proj, cracked.gather, noImplicitLod, params);
John Kessenich140f3df2015-06-26 16:58:36 -06003548}
3549
3550spv::Id TGlslangToSpvTraverser::handleUserFunctionCall(const glslang::TIntermAggregate* node)
3551{
3552 // Grab the function's pointer from the previously created function
3553 spv::Function* function = functionMap[node->getName().c_str()];
3554 if (! function)
3555 return 0;
3556
3557 const glslang::TIntermSequence& glslangArgs = node->getSequence();
3558 const glslang::TQualifierList& qualifiers = node->getQualifierList();
3559
LoopDawga5d86162017-09-10 09:46:55 -06003560 // Encapsulate lvalue logic, used in several places below, for safety.
LoopDawg76117922017-09-06 14:59:06 -06003561 const auto isLValue = [](int qualifier, const glslang::TType& paramType) -> bool {
3562 return qualifier != glslang::EvqConstReadOnly || paramType.containsOpaque();
3563 };
3564
John Kessenich140f3df2015-06-26 16:58:36 -06003565 // See comments in makeFunctions() for details about the semantics for parameter passing.
3566 //
3567 // These imply we need a four step process:
3568 // 1. Evaluate the arguments
3569 // 2. Allocate and make copies of in, out, and inout arguments
3570 // 3. Make the call
3571 // 4. Copy back the results
3572
3573 // 1. Evaluate the arguments
3574 std::vector<spv::Builder::AccessChain> lValues;
3575 std::vector<spv::Id> rValues;
John Kessenich32cfd492016-02-02 12:37:46 -07003576 std::vector<const glslang::TType*> argTypes;
John Kessenich140f3df2015-06-26 16:58:36 -06003577 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003578 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003579 // build l-value
3580 builder.clearAccessChain();
3581 glslangArgs[a]->traverse(this);
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003582 argTypes.push_back(&paramType);
John Kessenich11765302016-07-31 12:39:46 -06003583 // keep outputs and opaque objects as l-values, evaluate input-only as r-values
LoopDawg76117922017-09-06 14:59:06 -06003584 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003585 // save l-value
3586 lValues.push_back(builder.getAccessChain());
3587 } else {
3588 // process r-value
John Kessenich32cfd492016-02-02 12:37:46 -07003589 rValues.push_back(accessChainLoad(*argTypes.back()));
John Kessenich140f3df2015-06-26 16:58:36 -06003590 }
3591 }
3592
3593 // 2. Allocate space for anything needing a copy, and if it's "in" or "inout"
3594 // copy the original into that space.
3595 //
3596 // Also, build up the list of actual arguments to pass in for the call
3597 int lValueCount = 0;
3598 int rValueCount = 0;
3599 std::vector<spv::Id> spvArgs;
3600 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003601 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
John Kessenich140f3df2015-06-26 16:58:36 -06003602 spv::Id arg;
steve-lunargdd8287a2017-02-23 18:04:12 -07003603 if (paramType.containsOpaque() ||
John Kessenich37789792017-03-21 23:56:40 -06003604 (paramType.getBasicType() == glslang::EbtBlock && qualifiers[a] == glslang::EvqBuffer) ||
3605 (a == 0 && function->hasImplicitThis())) {
Jason Ekstrand76d0ac12016-05-25 11:50:21 -07003606 builder.setAccessChain(lValues[lValueCount]);
3607 arg = builder.accessChainGetLValue();
3608 ++lValueCount;
LoopDawg76117922017-09-06 14:59:06 -06003609 } else if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003610 // need space to hold the copy
John Kessenich140f3df2015-06-26 16:58:36 -06003611 arg = builder.createVariable(spv::StorageClassFunction, convertGlslangToSpvType(paramType), "param");
3612 if (qualifiers[a] == glslang::EvqIn || qualifiers[a] == glslang::EvqInOut) {
3613 // need to copy the input into output space
3614 builder.setAccessChain(lValues[lValueCount]);
John Kessenich32cfd492016-02-02 12:37:46 -07003615 spv::Id copy = accessChainLoad(*argTypes[a]);
John Kessenich4bf71552016-09-02 11:20:21 -06003616 builder.clearAccessChain();
3617 builder.setAccessChainLValue(arg);
3618 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003619 }
3620 ++lValueCount;
3621 } else {
3622 arg = rValues[rValueCount];
3623 ++rValueCount;
3624 }
3625 spvArgs.push_back(arg);
3626 }
3627
3628 // 3. Make the call.
3629 spv::Id result = builder.createFunctionCall(function, spvArgs);
John Kessenich32cfd492016-02-02 12:37:46 -07003630 builder.setPrecision(result, TranslatePrecisionDecoration(node->getType()));
John Kessenich140f3df2015-06-26 16:58:36 -06003631
3632 // 4. Copy back out an "out" arguments.
3633 lValueCount = 0;
3634 for (int a = 0; a < (int)glslangArgs.size(); ++a) {
John Kessenich4bf71552016-09-02 11:20:21 -06003635 const glslang::TType& paramType = glslangArgs[a]->getAsTyped()->getType();
LoopDawg76117922017-09-06 14:59:06 -06003636 if (isLValue(qualifiers[a], paramType)) {
John Kessenich140f3df2015-06-26 16:58:36 -06003637 if (qualifiers[a] == glslang::EvqOut || qualifiers[a] == glslang::EvqInOut) {
3638 spv::Id copy = builder.createLoad(spvArgs[a]);
3639 builder.setAccessChain(lValues[lValueCount]);
John Kessenich4bf71552016-09-02 11:20:21 -06003640 multiTypeStore(paramType, copy);
John Kessenich140f3df2015-06-26 16:58:36 -06003641 }
3642 ++lValueCount;
3643 }
3644 }
3645
3646 return result;
3647}
3648
3649// Translate AST operation to SPV operation, already having SPV-based operands/types.
qining25262b32016-05-06 17:25:16 -04003650spv::Id TGlslangToSpvTraverser::createBinaryOperation(glslang::TOperator op, spv::Decoration precision,
3651 spv::Decoration noContraction,
John Kessenich140f3df2015-06-26 16:58:36 -06003652 spv::Id typeId, spv::Id left, spv::Id right,
3653 glslang::TBasicType typeProxy, bool reduceComparison)
3654{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003655#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003656 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003657 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3658#else
Rex Xucabbb782017-03-24 13:41:14 +08003659 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich140f3df2015-06-26 16:58:36 -06003660 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003661#endif
Rex Xuc7d36562016-04-27 08:15:37 +08003662 bool isBool = typeProxy == glslang::EbtBool;
John Kessenich140f3df2015-06-26 16:58:36 -06003663
3664 spv::Op binOp = spv::OpNop;
John Kessenichec43d0a2015-07-04 17:17:31 -06003665 bool needMatchingVectors = true; // for non-matrix ops, would a scalar need to smear to match a vector?
John Kessenich140f3df2015-06-26 16:58:36 -06003666 bool comparison = false;
3667
3668 switch (op) {
3669 case glslang::EOpAdd:
3670 case glslang::EOpAddAssign:
3671 if (isFloat)
3672 binOp = spv::OpFAdd;
3673 else
3674 binOp = spv::OpIAdd;
3675 break;
3676 case glslang::EOpSub:
3677 case glslang::EOpSubAssign:
3678 if (isFloat)
3679 binOp = spv::OpFSub;
3680 else
3681 binOp = spv::OpISub;
3682 break;
3683 case glslang::EOpMul:
3684 case glslang::EOpMulAssign:
3685 if (isFloat)
3686 binOp = spv::OpFMul;
3687 else
3688 binOp = spv::OpIMul;
3689 break;
3690 case glslang::EOpVectorTimesScalar:
3691 case glslang::EOpVectorTimesScalarAssign:
John Kessenich8d72f1a2016-05-20 12:06:03 -06003692 if (isFloat && (builder.isVector(left) || builder.isVector(right))) {
John Kessenichec43d0a2015-07-04 17:17:31 -06003693 if (builder.isVector(right))
3694 std::swap(left, right);
3695 assert(builder.isScalar(right));
3696 needMatchingVectors = false;
3697 binOp = spv::OpVectorTimesScalar;
3698 } else
3699 binOp = spv::OpIMul;
John Kessenich140f3df2015-06-26 16:58:36 -06003700 break;
3701 case glslang::EOpVectorTimesMatrix:
3702 case glslang::EOpVectorTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003703 binOp = spv::OpVectorTimesMatrix;
3704 break;
3705 case glslang::EOpMatrixTimesVector:
John Kessenich140f3df2015-06-26 16:58:36 -06003706 binOp = spv::OpMatrixTimesVector;
3707 break;
3708 case glslang::EOpMatrixTimesScalar:
3709 case glslang::EOpMatrixTimesScalarAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003710 binOp = spv::OpMatrixTimesScalar;
3711 break;
3712 case glslang::EOpMatrixTimesMatrix:
3713 case glslang::EOpMatrixTimesMatrixAssign:
John Kessenich140f3df2015-06-26 16:58:36 -06003714 binOp = spv::OpMatrixTimesMatrix;
3715 break;
3716 case glslang::EOpOuterProduct:
3717 binOp = spv::OpOuterProduct;
John Kessenichec43d0a2015-07-04 17:17:31 -06003718 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003719 break;
3720
3721 case glslang::EOpDiv:
3722 case glslang::EOpDivAssign:
3723 if (isFloat)
3724 binOp = spv::OpFDiv;
3725 else if (isUnsigned)
3726 binOp = spv::OpUDiv;
3727 else
3728 binOp = spv::OpSDiv;
3729 break;
3730 case glslang::EOpMod:
3731 case glslang::EOpModAssign:
3732 if (isFloat)
3733 binOp = spv::OpFMod;
3734 else if (isUnsigned)
3735 binOp = spv::OpUMod;
3736 else
3737 binOp = spv::OpSMod;
3738 break;
3739 case glslang::EOpRightShift:
3740 case glslang::EOpRightShiftAssign:
3741 if (isUnsigned)
3742 binOp = spv::OpShiftRightLogical;
3743 else
3744 binOp = spv::OpShiftRightArithmetic;
3745 break;
3746 case glslang::EOpLeftShift:
3747 case glslang::EOpLeftShiftAssign:
3748 binOp = spv::OpShiftLeftLogical;
3749 break;
3750 case glslang::EOpAnd:
3751 case glslang::EOpAndAssign:
3752 binOp = spv::OpBitwiseAnd;
3753 break;
3754 case glslang::EOpLogicalAnd:
John Kessenichec43d0a2015-07-04 17:17:31 -06003755 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003756 binOp = spv::OpLogicalAnd;
3757 break;
3758 case glslang::EOpInclusiveOr:
3759 case glslang::EOpInclusiveOrAssign:
3760 binOp = spv::OpBitwiseOr;
3761 break;
3762 case glslang::EOpLogicalOr:
John Kessenichec43d0a2015-07-04 17:17:31 -06003763 needMatchingVectors = false;
John Kessenich140f3df2015-06-26 16:58:36 -06003764 binOp = spv::OpLogicalOr;
3765 break;
3766 case glslang::EOpExclusiveOr:
3767 case glslang::EOpExclusiveOrAssign:
3768 binOp = spv::OpBitwiseXor;
3769 break;
3770 case glslang::EOpLogicalXor:
John Kessenichec43d0a2015-07-04 17:17:31 -06003771 needMatchingVectors = false;
John Kessenich5e4b1242015-08-06 22:53:06 -06003772 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003773 break;
3774
3775 case glslang::EOpLessThan:
3776 case glslang::EOpGreaterThan:
3777 case glslang::EOpLessThanEqual:
3778 case glslang::EOpGreaterThanEqual:
3779 case glslang::EOpEqual:
3780 case glslang::EOpNotEqual:
3781 case glslang::EOpVectorEqual:
3782 case glslang::EOpVectorNotEqual:
3783 comparison = true;
3784 break;
3785 default:
3786 break;
3787 }
3788
John Kessenich7c1aa102015-10-15 13:29:11 -06003789 // handle mapped binary operations (should be non-comparison)
John Kessenich140f3df2015-06-26 16:58:36 -06003790 if (binOp != spv::OpNop) {
John Kessenich7c1aa102015-10-15 13:29:11 -06003791 assert(comparison == false);
John Kessenich04bb8a02015-12-12 12:28:14 -07003792 if (builder.isMatrix(left) || builder.isMatrix(right))
qining25262b32016-05-06 17:25:16 -04003793 return createBinaryMatrixOperation(binOp, precision, noContraction, typeId, left, right);
John Kessenich140f3df2015-06-26 16:58:36 -06003794
3795 // No matrix involved; make both operands be the same number of components, if needed
John Kessenichec43d0a2015-07-04 17:17:31 -06003796 if (needMatchingVectors)
John Kessenich140f3df2015-06-26 16:58:36 -06003797 builder.promoteScalar(precision, left, right);
3798
qining25262b32016-05-06 17:25:16 -04003799 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3800 addDecoration(result, noContraction);
3801 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06003802 }
3803
3804 if (! comparison)
3805 return 0;
3806
John Kessenich7c1aa102015-10-15 13:29:11 -06003807 // Handle comparison instructions
John Kessenich140f3df2015-06-26 16:58:36 -06003808
John Kessenich4583b612016-08-07 19:14:22 -06003809 if (reduceComparison && (op == glslang::EOpEqual || op == glslang::EOpNotEqual)
3810 && (builder.isVector(left) || builder.isMatrix(left) || builder.isAggregate(left)))
John Kessenich22118352015-12-21 20:54:09 -07003811 return builder.createCompositeCompare(precision, left, right, op == glslang::EOpEqual);
John Kessenich140f3df2015-06-26 16:58:36 -06003812
3813 switch (op) {
3814 case glslang::EOpLessThan:
3815 if (isFloat)
3816 binOp = spv::OpFOrdLessThan;
3817 else if (isUnsigned)
3818 binOp = spv::OpULessThan;
3819 else
3820 binOp = spv::OpSLessThan;
3821 break;
3822 case glslang::EOpGreaterThan:
3823 if (isFloat)
3824 binOp = spv::OpFOrdGreaterThan;
3825 else if (isUnsigned)
3826 binOp = spv::OpUGreaterThan;
3827 else
3828 binOp = spv::OpSGreaterThan;
3829 break;
3830 case glslang::EOpLessThanEqual:
3831 if (isFloat)
3832 binOp = spv::OpFOrdLessThanEqual;
3833 else if (isUnsigned)
3834 binOp = spv::OpULessThanEqual;
3835 else
3836 binOp = spv::OpSLessThanEqual;
3837 break;
3838 case glslang::EOpGreaterThanEqual:
3839 if (isFloat)
3840 binOp = spv::OpFOrdGreaterThanEqual;
3841 else if (isUnsigned)
3842 binOp = spv::OpUGreaterThanEqual;
3843 else
3844 binOp = spv::OpSGreaterThanEqual;
3845 break;
3846 case glslang::EOpEqual:
3847 case glslang::EOpVectorEqual:
3848 if (isFloat)
3849 binOp = spv::OpFOrdEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003850 else if (isBool)
3851 binOp = spv::OpLogicalEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003852 else
3853 binOp = spv::OpIEqual;
3854 break;
3855 case glslang::EOpNotEqual:
3856 case glslang::EOpVectorNotEqual:
3857 if (isFloat)
3858 binOp = spv::OpFOrdNotEqual;
Rex Xuc7d36562016-04-27 08:15:37 +08003859 else if (isBool)
3860 binOp = spv::OpLogicalNotEqual;
John Kessenich140f3df2015-06-26 16:58:36 -06003861 else
3862 binOp = spv::OpINotEqual;
3863 break;
3864 default:
3865 break;
3866 }
3867
qining25262b32016-05-06 17:25:16 -04003868 if (binOp != spv::OpNop) {
3869 spv::Id result = builder.createBinOp(binOp, typeId, left, right);
3870 addDecoration(result, noContraction);
3871 return builder.setPrecision(result, precision);
3872 }
John Kessenich140f3df2015-06-26 16:58:36 -06003873
3874 return 0;
3875}
3876
John Kessenich04bb8a02015-12-12 12:28:14 -07003877//
3878// Translate AST matrix operation to SPV operation, already having SPV-based operands/types.
3879// These can be any of:
3880//
3881// matrix * scalar
3882// scalar * matrix
3883// matrix * matrix linear algebraic
3884// matrix * vector
3885// vector * matrix
3886// matrix * matrix componentwise
3887// matrix op matrix op in {+, -, /}
3888// matrix op scalar op in {+, -, /}
3889// scalar op matrix op in {+, -, /}
3890//
qining25262b32016-05-06 17:25:16 -04003891spv::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 -07003892{
3893 bool firstClass = true;
3894
3895 // First, handle first-class matrix operations (* and matrix/scalar)
3896 switch (op) {
3897 case spv::OpFDiv:
3898 if (builder.isMatrix(left) && builder.isScalar(right)) {
3899 // turn matrix / scalar into a multiply...
3900 right = builder.createBinOp(spv::OpFDiv, builder.getTypeId(right), builder.makeFloatConstant(1.0F), right);
3901 op = spv::OpMatrixTimesScalar;
3902 } else
3903 firstClass = false;
3904 break;
3905 case spv::OpMatrixTimesScalar:
3906 if (builder.isMatrix(right))
3907 std::swap(left, right);
3908 assert(builder.isScalar(right));
3909 break;
3910 case spv::OpVectorTimesMatrix:
3911 assert(builder.isVector(left));
3912 assert(builder.isMatrix(right));
3913 break;
3914 case spv::OpMatrixTimesVector:
3915 assert(builder.isMatrix(left));
3916 assert(builder.isVector(right));
3917 break;
3918 case spv::OpMatrixTimesMatrix:
3919 assert(builder.isMatrix(left));
3920 assert(builder.isMatrix(right));
3921 break;
3922 default:
3923 firstClass = false;
3924 break;
3925 }
3926
qining25262b32016-05-06 17:25:16 -04003927 if (firstClass) {
3928 spv::Id result = builder.createBinOp(op, typeId, left, right);
3929 addDecoration(result, noContraction);
3930 return builder.setPrecision(result, precision);
3931 }
John Kessenich04bb8a02015-12-12 12:28:14 -07003932
LoopDawg592860c2016-06-09 08:57:35 -06003933 // Handle component-wise +, -, *, %, and / for all combinations of type.
John Kessenich04bb8a02015-12-12 12:28:14 -07003934 // The result type of all of them is the same type as the (a) matrix operand.
3935 // The algorithm is to:
3936 // - break the matrix(es) into vectors
3937 // - smear any scalar to a vector
3938 // - do vector operations
3939 // - make a matrix out the vector results
3940 switch (op) {
3941 case spv::OpFAdd:
3942 case spv::OpFSub:
3943 case spv::OpFDiv:
LoopDawg592860c2016-06-09 08:57:35 -06003944 case spv::OpFMod:
John Kessenich04bb8a02015-12-12 12:28:14 -07003945 case spv::OpFMul:
3946 {
3947 // one time set up...
3948 bool leftMat = builder.isMatrix(left);
3949 bool rightMat = builder.isMatrix(right);
3950 unsigned int numCols = leftMat ? builder.getNumColumns(left) : builder.getNumColumns(right);
3951 int numRows = leftMat ? builder.getNumRows(left) : builder.getNumRows(right);
3952 spv::Id scalarType = builder.getScalarTypeId(typeId);
3953 spv::Id vecType = builder.makeVectorType(scalarType, numRows);
3954 std::vector<spv::Id> results;
3955 spv::Id smearVec = spv::NoResult;
3956 if (builder.isScalar(left))
3957 smearVec = builder.smearScalar(precision, left, vecType);
3958 else if (builder.isScalar(right))
3959 smearVec = builder.smearScalar(precision, right, vecType);
3960
3961 // do each vector op
3962 for (unsigned int c = 0; c < numCols; ++c) {
3963 std::vector<unsigned int> indexes;
3964 indexes.push_back(c);
3965 spv::Id leftVec = leftMat ? builder.createCompositeExtract( left, vecType, indexes) : smearVec;
3966 spv::Id rightVec = rightMat ? builder.createCompositeExtract(right, vecType, indexes) : smearVec;
qining25262b32016-05-06 17:25:16 -04003967 spv::Id result = builder.createBinOp(op, vecType, leftVec, rightVec);
3968 addDecoration(result, noContraction);
3969 results.push_back(builder.setPrecision(result, precision));
John Kessenich04bb8a02015-12-12 12:28:14 -07003970 }
3971
3972 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07003973 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich04bb8a02015-12-12 12:28:14 -07003974 }
3975 default:
3976 assert(0);
3977 return spv::NoResult;
3978 }
3979}
3980
qining25262b32016-05-06 17:25:16 -04003981spv::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 -06003982{
3983 spv::Op unaryOp = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08003984 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06003985 int libCall = -1;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003986#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08003987 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003988 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
3989#else
Rex Xucabbb782017-03-24 13:41:14 +08003990 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xu04db3f52015-09-16 11:44:02 +08003991 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08003992#endif
John Kessenich140f3df2015-06-26 16:58:36 -06003993
3994 switch (op) {
3995 case glslang::EOpNegative:
John Kessenich7a53f762016-01-20 11:19:27 -07003996 if (isFloat) {
John Kessenich140f3df2015-06-26 16:58:36 -06003997 unaryOp = spv::OpFNegate;
John Kessenich7a53f762016-01-20 11:19:27 -07003998 if (builder.isMatrixType(typeId))
qining25262b32016-05-06 17:25:16 -04003999 return createUnaryMatrixOperation(unaryOp, precision, noContraction, typeId, operand, typeProxy);
John Kessenich7a53f762016-01-20 11:19:27 -07004000 } else
John Kessenich140f3df2015-06-26 16:58:36 -06004001 unaryOp = spv::OpSNegate;
4002 break;
4003
4004 case glslang::EOpLogicalNot:
4005 case glslang::EOpVectorLogicalNot:
John Kessenich5e4b1242015-08-06 22:53:06 -06004006 unaryOp = spv::OpLogicalNot;
4007 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004008 case glslang::EOpBitwiseNot:
4009 unaryOp = spv::OpNot;
4010 break;
John Kessenich5e4b1242015-08-06 22:53:06 -06004011
John Kessenich140f3df2015-06-26 16:58:36 -06004012 case glslang::EOpDeterminant:
John Kessenich5e4b1242015-08-06 22:53:06 -06004013 libCall = spv::GLSLstd450Determinant;
John Kessenich140f3df2015-06-26 16:58:36 -06004014 break;
4015 case glslang::EOpMatrixInverse:
John Kessenich5e4b1242015-08-06 22:53:06 -06004016 libCall = spv::GLSLstd450MatrixInverse;
John Kessenich140f3df2015-06-26 16:58:36 -06004017 break;
4018 case glslang::EOpTranspose:
4019 unaryOp = spv::OpTranspose;
4020 break;
4021
4022 case glslang::EOpRadians:
John Kessenich5e4b1242015-08-06 22:53:06 -06004023 libCall = spv::GLSLstd450Radians;
John Kessenich140f3df2015-06-26 16:58:36 -06004024 break;
4025 case glslang::EOpDegrees:
John Kessenich5e4b1242015-08-06 22:53:06 -06004026 libCall = spv::GLSLstd450Degrees;
John Kessenich140f3df2015-06-26 16:58:36 -06004027 break;
4028 case glslang::EOpSin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004029 libCall = spv::GLSLstd450Sin;
John Kessenich140f3df2015-06-26 16:58:36 -06004030 break;
4031 case glslang::EOpCos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004032 libCall = spv::GLSLstd450Cos;
John Kessenich140f3df2015-06-26 16:58:36 -06004033 break;
4034 case glslang::EOpTan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004035 libCall = spv::GLSLstd450Tan;
John Kessenich140f3df2015-06-26 16:58:36 -06004036 break;
4037 case glslang::EOpAcos:
John Kessenich5e4b1242015-08-06 22:53:06 -06004038 libCall = spv::GLSLstd450Acos;
John Kessenich140f3df2015-06-26 16:58:36 -06004039 break;
4040 case glslang::EOpAsin:
John Kessenich5e4b1242015-08-06 22:53:06 -06004041 libCall = spv::GLSLstd450Asin;
John Kessenich140f3df2015-06-26 16:58:36 -06004042 break;
4043 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06004044 libCall = spv::GLSLstd450Atan;
John Kessenich140f3df2015-06-26 16:58:36 -06004045 break;
4046
4047 case glslang::EOpAcosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004048 libCall = spv::GLSLstd450Acosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004049 break;
4050 case glslang::EOpAsinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004051 libCall = spv::GLSLstd450Asinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004052 break;
4053 case glslang::EOpAtanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004054 libCall = spv::GLSLstd450Atanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004055 break;
4056 case glslang::EOpTanh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004057 libCall = spv::GLSLstd450Tanh;
John Kessenich140f3df2015-06-26 16:58:36 -06004058 break;
4059 case glslang::EOpCosh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004060 libCall = spv::GLSLstd450Cosh;
John Kessenich140f3df2015-06-26 16:58:36 -06004061 break;
4062 case glslang::EOpSinh:
John Kessenich5e4b1242015-08-06 22:53:06 -06004063 libCall = spv::GLSLstd450Sinh;
John Kessenich140f3df2015-06-26 16:58:36 -06004064 break;
4065
4066 case glslang::EOpLength:
John Kessenich5e4b1242015-08-06 22:53:06 -06004067 libCall = spv::GLSLstd450Length;
John Kessenich140f3df2015-06-26 16:58:36 -06004068 break;
4069 case glslang::EOpNormalize:
John Kessenich5e4b1242015-08-06 22:53:06 -06004070 libCall = spv::GLSLstd450Normalize;
John Kessenich140f3df2015-06-26 16:58:36 -06004071 break;
4072
4073 case glslang::EOpExp:
John Kessenich5e4b1242015-08-06 22:53:06 -06004074 libCall = spv::GLSLstd450Exp;
John Kessenich140f3df2015-06-26 16:58:36 -06004075 break;
4076 case glslang::EOpLog:
John Kessenich5e4b1242015-08-06 22:53:06 -06004077 libCall = spv::GLSLstd450Log;
John Kessenich140f3df2015-06-26 16:58:36 -06004078 break;
4079 case glslang::EOpExp2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004080 libCall = spv::GLSLstd450Exp2;
John Kessenich140f3df2015-06-26 16:58:36 -06004081 break;
4082 case glslang::EOpLog2:
John Kessenich5e4b1242015-08-06 22:53:06 -06004083 libCall = spv::GLSLstd450Log2;
John Kessenich140f3df2015-06-26 16:58:36 -06004084 break;
4085 case glslang::EOpSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004086 libCall = spv::GLSLstd450Sqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004087 break;
4088 case glslang::EOpInverseSqrt:
John Kessenich5e4b1242015-08-06 22:53:06 -06004089 libCall = spv::GLSLstd450InverseSqrt;
John Kessenich140f3df2015-06-26 16:58:36 -06004090 break;
4091
4092 case glslang::EOpFloor:
John Kessenich5e4b1242015-08-06 22:53:06 -06004093 libCall = spv::GLSLstd450Floor;
John Kessenich140f3df2015-06-26 16:58:36 -06004094 break;
4095 case glslang::EOpTrunc:
John Kessenich5e4b1242015-08-06 22:53:06 -06004096 libCall = spv::GLSLstd450Trunc;
John Kessenich140f3df2015-06-26 16:58:36 -06004097 break;
4098 case glslang::EOpRound:
John Kessenich5e4b1242015-08-06 22:53:06 -06004099 libCall = spv::GLSLstd450Round;
John Kessenich140f3df2015-06-26 16:58:36 -06004100 break;
4101 case glslang::EOpRoundEven:
John Kessenich5e4b1242015-08-06 22:53:06 -06004102 libCall = spv::GLSLstd450RoundEven;
John Kessenich140f3df2015-06-26 16:58:36 -06004103 break;
4104 case glslang::EOpCeil:
John Kessenich5e4b1242015-08-06 22:53:06 -06004105 libCall = spv::GLSLstd450Ceil;
John Kessenich140f3df2015-06-26 16:58:36 -06004106 break;
4107 case glslang::EOpFract:
John Kessenich5e4b1242015-08-06 22:53:06 -06004108 libCall = spv::GLSLstd450Fract;
John Kessenich140f3df2015-06-26 16:58:36 -06004109 break;
4110
4111 case glslang::EOpIsNan:
4112 unaryOp = spv::OpIsNan;
4113 break;
4114 case glslang::EOpIsInf:
4115 unaryOp = spv::OpIsInf;
4116 break;
LoopDawg592860c2016-06-09 08:57:35 -06004117 case glslang::EOpIsFinite:
4118 unaryOp = spv::OpIsFinite;
4119 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004120
Rex Xucbc426e2015-12-15 16:03:10 +08004121 case glslang::EOpFloatBitsToInt:
4122 case glslang::EOpFloatBitsToUint:
4123 case glslang::EOpIntBitsToFloat:
4124 case glslang::EOpUintBitsToFloat:
Rex Xu8ff43de2016-04-22 16:51:45 +08004125 case glslang::EOpDoubleBitsToInt64:
4126 case glslang::EOpDoubleBitsToUint64:
4127 case glslang::EOpInt64BitsToDouble:
4128 case glslang::EOpUint64BitsToDouble:
Rex Xucabbb782017-03-24 13:41:14 +08004129#ifdef AMD_EXTENSIONS
4130 case glslang::EOpFloat16BitsToInt16:
4131 case glslang::EOpFloat16BitsToUint16:
4132 case glslang::EOpInt16BitsToFloat16:
4133 case glslang::EOpUint16BitsToFloat16:
4134#endif
Rex Xucbc426e2015-12-15 16:03:10 +08004135 unaryOp = spv::OpBitcast;
4136 break;
4137
John Kessenich140f3df2015-06-26 16:58:36 -06004138 case glslang::EOpPackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004139 libCall = spv::GLSLstd450PackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004140 break;
4141 case glslang::EOpUnpackSnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004142 libCall = spv::GLSLstd450UnpackSnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004143 break;
4144 case glslang::EOpPackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004145 libCall = spv::GLSLstd450PackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004146 break;
4147 case glslang::EOpUnpackUnorm2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004148 libCall = spv::GLSLstd450UnpackUnorm2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004149 break;
4150 case glslang::EOpPackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004151 libCall = spv::GLSLstd450PackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004152 break;
4153 case glslang::EOpUnpackHalf2x16:
John Kessenich5e4b1242015-08-06 22:53:06 -06004154 libCall = spv::GLSLstd450UnpackHalf2x16;
John Kessenich140f3df2015-06-26 16:58:36 -06004155 break;
John Kessenichfc51d282015-08-19 13:34:18 -06004156 case glslang::EOpPackSnorm4x8:
4157 libCall = spv::GLSLstd450PackSnorm4x8;
4158 break;
4159 case glslang::EOpUnpackSnorm4x8:
4160 libCall = spv::GLSLstd450UnpackSnorm4x8;
4161 break;
4162 case glslang::EOpPackUnorm4x8:
4163 libCall = spv::GLSLstd450PackUnorm4x8;
4164 break;
4165 case glslang::EOpUnpackUnorm4x8:
4166 libCall = spv::GLSLstd450UnpackUnorm4x8;
4167 break;
4168 case glslang::EOpPackDouble2x32:
4169 libCall = spv::GLSLstd450PackDouble2x32;
4170 break;
4171 case glslang::EOpUnpackDouble2x32:
4172 libCall = spv::GLSLstd450UnpackDouble2x32;
4173 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004174
Rex Xu8ff43de2016-04-22 16:51:45 +08004175 case glslang::EOpPackInt2x32:
4176 case glslang::EOpUnpackInt2x32:
4177 case glslang::EOpPackUint2x32:
4178 case glslang::EOpUnpackUint2x32:
Rex Xuc9f34922016-09-09 17:50:07 +08004179 unaryOp = spv::OpBitcast;
Rex Xu8ff43de2016-04-22 16:51:45 +08004180 break;
4181
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004182#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004183 case glslang::EOpPackInt2x16:
4184 case glslang::EOpUnpackInt2x16:
4185 case glslang::EOpPackUint2x16:
4186 case glslang::EOpUnpackUint2x16:
4187 case glslang::EOpPackInt4x16:
4188 case glslang::EOpUnpackInt4x16:
4189 case glslang::EOpPackUint4x16:
4190 case glslang::EOpUnpackUint4x16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004191 case glslang::EOpPackFloat2x16:
4192 case glslang::EOpUnpackFloat2x16:
4193 unaryOp = spv::OpBitcast;
4194 break;
4195#endif
4196
John Kessenich140f3df2015-06-26 16:58:36 -06004197 case glslang::EOpDPdx:
4198 unaryOp = spv::OpDPdx;
4199 break;
4200 case glslang::EOpDPdy:
4201 unaryOp = spv::OpDPdy;
4202 break;
4203 case glslang::EOpFwidth:
4204 unaryOp = spv::OpFwidth;
4205 break;
4206 case glslang::EOpDPdxFine:
John Kessenich92187592016-02-01 13:45:25 -07004207 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004208 unaryOp = spv::OpDPdxFine;
4209 break;
4210 case glslang::EOpDPdyFine:
John Kessenich92187592016-02-01 13:45:25 -07004211 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004212 unaryOp = spv::OpDPdyFine;
4213 break;
4214 case glslang::EOpFwidthFine:
John Kessenich92187592016-02-01 13:45:25 -07004215 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004216 unaryOp = spv::OpFwidthFine;
4217 break;
4218 case glslang::EOpDPdxCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004219 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004220 unaryOp = spv::OpDPdxCoarse;
4221 break;
4222 case glslang::EOpDPdyCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004223 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004224 unaryOp = spv::OpDPdyCoarse;
4225 break;
4226 case glslang::EOpFwidthCoarse:
John Kessenich92187592016-02-01 13:45:25 -07004227 builder.addCapability(spv::CapabilityDerivativeControl);
John Kessenich140f3df2015-06-26 16:58:36 -06004228 unaryOp = spv::OpFwidthCoarse;
4229 break;
Rex Xu7a26c172015-12-08 17:12:09 +08004230 case glslang::EOpInterpolateAtCentroid:
John Kessenich92187592016-02-01 13:45:25 -07004231 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08004232 libCall = spv::GLSLstd450InterpolateAtCentroid;
4233 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004234 case glslang::EOpAny:
4235 unaryOp = spv::OpAny;
4236 break;
4237 case glslang::EOpAll:
4238 unaryOp = spv::OpAll;
4239 break;
4240
4241 case glslang::EOpAbs:
John Kessenich5e4b1242015-08-06 22:53:06 -06004242 if (isFloat)
4243 libCall = spv::GLSLstd450FAbs;
4244 else
4245 libCall = spv::GLSLstd450SAbs;
John Kessenich140f3df2015-06-26 16:58:36 -06004246 break;
4247 case glslang::EOpSign:
John Kessenich5e4b1242015-08-06 22:53:06 -06004248 if (isFloat)
4249 libCall = spv::GLSLstd450FSign;
4250 else
4251 libCall = spv::GLSLstd450SSign;
John Kessenich140f3df2015-06-26 16:58:36 -06004252 break;
4253
John Kessenichfc51d282015-08-19 13:34:18 -06004254 case glslang::EOpAtomicCounterIncrement:
4255 case glslang::EOpAtomicCounterDecrement:
4256 case glslang::EOpAtomicCounter:
4257 {
4258 // Handle all of the atomics in one place, in createAtomicOperation()
4259 std::vector<spv::Id> operands;
4260 operands.push_back(operand);
Rex Xu04db3f52015-09-16 11:44:02 +08004261 return createAtomicOperation(op, precision, typeId, operands, typeProxy);
John Kessenichfc51d282015-08-19 13:34:18 -06004262 }
4263
John Kessenichfc51d282015-08-19 13:34:18 -06004264 case glslang::EOpBitFieldReverse:
4265 unaryOp = spv::OpBitReverse;
4266 break;
4267 case glslang::EOpBitCount:
4268 unaryOp = spv::OpBitCount;
4269 break;
4270 case glslang::EOpFindLSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004271 libCall = spv::GLSLstd450FindILsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004272 break;
4273 case glslang::EOpFindMSB:
John Kessenich55e7d112015-11-15 21:33:39 -07004274 if (isUnsigned)
4275 libCall = spv::GLSLstd450FindUMsb;
4276 else
4277 libCall = spv::GLSLstd450FindSMsb;
John Kessenichfc51d282015-08-19 13:34:18 -06004278 break;
4279
Rex Xu574ab042016-04-14 16:53:07 +08004280 case glslang::EOpBallot:
4281 case glslang::EOpReadFirstInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004282 case glslang::EOpAnyInvocation:
Rex Xu338b1852016-05-05 20:38:33 +08004283 case glslang::EOpAllInvocations:
Rex Xu338b1852016-05-05 20:38:33 +08004284 case glslang::EOpAllInvocationsEqual:
Rex Xu9d93a232016-05-05 12:30:44 +08004285#ifdef AMD_EXTENSIONS
4286 case glslang::EOpMinInvocations:
4287 case glslang::EOpMaxInvocations:
4288 case glslang::EOpAddInvocations:
4289 case glslang::EOpMinInvocationsNonUniform:
4290 case glslang::EOpMaxInvocationsNonUniform:
4291 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004292 case glslang::EOpMinInvocationsInclusiveScan:
4293 case glslang::EOpMaxInvocationsInclusiveScan:
4294 case glslang::EOpAddInvocationsInclusiveScan:
4295 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4296 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4297 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4298 case glslang::EOpMinInvocationsExclusiveScan:
4299 case glslang::EOpMaxInvocationsExclusiveScan:
4300 case glslang::EOpAddInvocationsExclusiveScan:
4301 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4302 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4303 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
Rex Xu9d93a232016-05-05 12:30:44 +08004304#endif
Rex Xu51596642016-09-21 18:56:12 +08004305 {
4306 std::vector<spv::Id> operands;
4307 operands.push_back(operand);
4308 return createInvocationsOperation(op, typeId, operands, typeProxy);
4309 }
Rex Xu9d93a232016-05-05 12:30:44 +08004310
4311#ifdef AMD_EXTENSIONS
4312 case glslang::EOpMbcnt:
4313 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
4314 libCall = spv::MbcntAMD;
4315 break;
4316
4317 case glslang::EOpCubeFaceIndex:
4318 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4319 libCall = spv::CubeFaceIndexAMD;
4320 break;
4321
4322 case glslang::EOpCubeFaceCoord:
4323 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_gcn_shader);
4324 libCall = spv::CubeFaceCoordAMD;
4325 break;
4326#endif
Rex Xu338b1852016-05-05 20:38:33 +08004327
John Kessenich140f3df2015-06-26 16:58:36 -06004328 default:
4329 return 0;
4330 }
4331
4332 spv::Id id;
4333 if (libCall >= 0) {
4334 std::vector<spv::Id> args;
4335 args.push_back(operand);
Rex Xu9d93a232016-05-05 12:30:44 +08004336 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, args);
Rex Xu338b1852016-05-05 20:38:33 +08004337 } else {
John Kessenich91cef522016-05-05 16:45:40 -06004338 id = builder.createUnaryOp(unaryOp, typeId, operand);
Rex Xu338b1852016-05-05 20:38:33 +08004339 }
John Kessenich140f3df2015-06-26 16:58:36 -06004340
qining25262b32016-05-06 17:25:16 -04004341 addDecoration(id, noContraction);
John Kessenich32cfd492016-02-02 12:37:46 -07004342 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004343}
4344
John Kessenich7a53f762016-01-20 11:19:27 -07004345// Create a unary operation on a matrix
qining25262b32016-05-06 17:25:16 -04004346spv::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 -07004347{
4348 // Handle unary operations vector by vector.
4349 // The result type is the same type as the original type.
4350 // The algorithm is to:
4351 // - break the matrix into vectors
4352 // - apply the operation to each vector
4353 // - make a matrix out the vector results
4354
4355 // get the types sorted out
4356 int numCols = builder.getNumColumns(operand);
4357 int numRows = builder.getNumRows(operand);
Rex Xuc1992e52016-05-17 18:57:18 +08004358 spv::Id srcVecType = builder.makeVectorType(builder.getScalarTypeId(builder.getTypeId(operand)), numRows);
4359 spv::Id destVecType = builder.makeVectorType(builder.getScalarTypeId(typeId), numRows);
John Kessenich7a53f762016-01-20 11:19:27 -07004360 std::vector<spv::Id> results;
4361
4362 // do each vector op
4363 for (int c = 0; c < numCols; ++c) {
4364 std::vector<unsigned int> indexes;
4365 indexes.push_back(c);
Rex Xuc1992e52016-05-17 18:57:18 +08004366 spv::Id srcVec = builder.createCompositeExtract(operand, srcVecType, indexes);
4367 spv::Id destVec = builder.createUnaryOp(op, destVecType, srcVec);
4368 addDecoration(destVec, noContraction);
4369 results.push_back(builder.setPrecision(destVec, precision));
John Kessenich7a53f762016-01-20 11:19:27 -07004370 }
4371
4372 // put the pieces together
John Kessenich32cfd492016-02-02 12:37:46 -07004373 return builder.setPrecision(builder.createCompositeConstruct(typeId, results), precision);
John Kessenich7a53f762016-01-20 11:19:27 -07004374}
4375
Rex Xu73e3ce72016-04-27 18:48:17 +08004376spv::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 -06004377{
4378 spv::Op convOp = spv::OpNop;
4379 spv::Id zero = 0;
4380 spv::Id one = 0;
Rex Xu8ff43de2016-04-22 16:51:45 +08004381 spv::Id type = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06004382
4383 int vectorSize = builder.isVectorType(destType) ? builder.getNumTypeComponents(destType) : 0;
4384
4385 switch (op) {
4386 case glslang::EOpConvIntToBool:
4387 case glslang::EOpConvUintToBool:
Rex Xu8ff43de2016-04-22 16:51:45 +08004388 case glslang::EOpConvInt64ToBool:
4389 case glslang::EOpConvUint64ToBool:
Rex Xucabbb782017-03-24 13:41:14 +08004390#ifdef AMD_EXTENSIONS
4391 case glslang::EOpConvInt16ToBool:
4392 case glslang::EOpConvUint16ToBool:
4393#endif
4394 if (op == glslang::EOpConvInt64ToBool || op == glslang::EOpConvUint64ToBool)
4395 zero = builder.makeUint64Constant(0);
4396#ifdef AMD_EXTENSIONS
4397 else if (op == glslang::EOpConvInt16ToBool || op == glslang::EOpConvUint16ToBool)
4398 zero = builder.makeUint16Constant(0);
4399#endif
4400 else
4401 zero = builder.makeUintConstant(0);
John Kessenich140f3df2015-06-26 16:58:36 -06004402 zero = makeSmearedConstant(zero, vectorSize);
4403 return builder.createBinOp(spv::OpINotEqual, destType, operand, zero);
4404
4405 case glslang::EOpConvFloatToBool:
4406 zero = builder.makeFloatConstant(0.0F);
4407 zero = makeSmearedConstant(zero, vectorSize);
4408 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4409
4410 case glslang::EOpConvDoubleToBool:
4411 zero = builder.makeDoubleConstant(0.0);
4412 zero = makeSmearedConstant(zero, vectorSize);
4413 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4414
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004415#ifdef AMD_EXTENSIONS
4416 case glslang::EOpConvFloat16ToBool:
4417 zero = builder.makeFloat16Constant(0.0F);
4418 zero = makeSmearedConstant(zero, vectorSize);
4419 return builder.createBinOp(spv::OpFOrdNotEqual, destType, operand, zero);
4420#endif
4421
John Kessenich140f3df2015-06-26 16:58:36 -06004422 case glslang::EOpConvBoolToFloat:
4423 convOp = spv::OpSelect;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004424 zero = builder.makeFloatConstant(0.0F);
4425 one = builder.makeFloatConstant(1.0F);
John Kessenich140f3df2015-06-26 16:58:36 -06004426 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004427
John Kessenich140f3df2015-06-26 16:58:36 -06004428 case glslang::EOpConvBoolToDouble:
4429 convOp = spv::OpSelect;
4430 zero = builder.makeDoubleConstant(0.0);
4431 one = builder.makeDoubleConstant(1.0);
4432 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004433
4434#ifdef AMD_EXTENSIONS
4435 case glslang::EOpConvBoolToFloat16:
4436 convOp = spv::OpSelect;
4437 zero = builder.makeFloat16Constant(0.0F);
4438 one = builder.makeFloat16Constant(1.0F);
4439 break;
4440#endif
4441
John Kessenich140f3df2015-06-26 16:58:36 -06004442 case glslang::EOpConvBoolToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004443 case glslang::EOpConvBoolToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004444#ifdef AMD_EXTENSIONS
4445 case glslang::EOpConvBoolToInt16:
4446#endif
4447 if (op == glslang::EOpConvBoolToInt64)
4448 zero = builder.makeInt64Constant(0);
4449#ifdef AMD_EXTENSIONS
4450 else if (op == glslang::EOpConvBoolToInt16)
4451 zero = builder.makeInt16Constant(0);
4452#endif
4453 else
4454 zero = builder.makeIntConstant(0);
4455
4456 if (op == glslang::EOpConvBoolToInt64)
4457 one = builder.makeInt64Constant(1);
4458#ifdef AMD_EXTENSIONS
4459 else if (op == glslang::EOpConvBoolToInt16)
4460 one = builder.makeInt16Constant(1);
4461#endif
4462 else
4463 one = builder.makeIntConstant(1);
4464
John Kessenich140f3df2015-06-26 16:58:36 -06004465 convOp = spv::OpSelect;
4466 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004467
John Kessenich140f3df2015-06-26 16:58:36 -06004468 case glslang::EOpConvBoolToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004469 case glslang::EOpConvBoolToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004470#ifdef AMD_EXTENSIONS
4471 case glslang::EOpConvBoolToUint16:
4472#endif
4473 if (op == glslang::EOpConvBoolToUint64)
4474 zero = builder.makeUint64Constant(0);
4475#ifdef AMD_EXTENSIONS
4476 else if (op == glslang::EOpConvBoolToUint16)
4477 zero = builder.makeUint16Constant(0);
4478#endif
4479 else
4480 zero = builder.makeUintConstant(0);
4481
4482 if (op == glslang::EOpConvBoolToUint64)
4483 one = builder.makeUint64Constant(1);
4484#ifdef AMD_EXTENSIONS
4485 else if (op == glslang::EOpConvBoolToUint16)
4486 one = builder.makeUint16Constant(1);
4487#endif
4488 else
4489 one = builder.makeUintConstant(1);
4490
John Kessenich140f3df2015-06-26 16:58:36 -06004491 convOp = spv::OpSelect;
4492 break;
4493
4494 case glslang::EOpConvIntToFloat:
4495 case glslang::EOpConvIntToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004496 case glslang::EOpConvInt64ToFloat:
4497 case glslang::EOpConvInt64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004498#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004499 case glslang::EOpConvInt16ToFloat:
4500 case glslang::EOpConvInt16ToDouble:
4501 case glslang::EOpConvInt16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004502 case glslang::EOpConvIntToFloat16:
4503 case glslang::EOpConvInt64ToFloat16:
4504#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004505 convOp = spv::OpConvertSToF;
4506 break;
4507
4508 case glslang::EOpConvUintToFloat:
4509 case glslang::EOpConvUintToDouble:
Rex Xu8ff43de2016-04-22 16:51:45 +08004510 case glslang::EOpConvUint64ToFloat:
4511 case glslang::EOpConvUint64ToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004512#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004513 case glslang::EOpConvUint16ToFloat:
4514 case glslang::EOpConvUint16ToDouble:
4515 case glslang::EOpConvUint16ToFloat16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004516 case glslang::EOpConvUintToFloat16:
4517 case glslang::EOpConvUint64ToFloat16:
4518#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004519 convOp = spv::OpConvertUToF;
4520 break;
4521
4522 case glslang::EOpConvDoubleToFloat:
4523 case glslang::EOpConvFloatToDouble:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004524#ifdef AMD_EXTENSIONS
4525 case glslang::EOpConvDoubleToFloat16:
4526 case glslang::EOpConvFloat16ToDouble:
4527 case glslang::EOpConvFloatToFloat16:
4528 case glslang::EOpConvFloat16ToFloat:
4529#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004530 convOp = spv::OpFConvert;
Rex Xu73e3ce72016-04-27 18:48:17 +08004531 if (builder.isMatrixType(destType))
4532 return createUnaryMatrixOperation(convOp, precision, noContraction, destType, operand, typeProxy);
John Kessenich140f3df2015-06-26 16:58:36 -06004533 break;
4534
4535 case glslang::EOpConvFloatToInt:
4536 case glslang::EOpConvDoubleToInt:
Rex Xu8ff43de2016-04-22 16:51:45 +08004537 case glslang::EOpConvFloatToInt64:
4538 case glslang::EOpConvDoubleToInt64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004539#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004540 case glslang::EOpConvFloatToInt16:
4541 case glslang::EOpConvDoubleToInt16:
4542 case glslang::EOpConvFloat16ToInt16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004543 case glslang::EOpConvFloat16ToInt:
4544 case glslang::EOpConvFloat16ToInt64:
4545#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004546 convOp = spv::OpConvertFToS;
4547 break;
4548
4549 case glslang::EOpConvUintToInt:
4550 case glslang::EOpConvIntToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004551 case glslang::EOpConvUint64ToInt64:
4552 case glslang::EOpConvInt64ToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004553#ifdef AMD_EXTENSIONS
4554 case glslang::EOpConvUint16ToInt16:
4555 case glslang::EOpConvInt16ToUint16:
4556#endif
qininge24aa5e2016-04-07 15:40:27 -04004557 if (builder.isInSpecConstCodeGenMode()) {
4558 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004559 if (op == glslang::EOpConvUint64ToInt64 || op == glslang::EOpConvInt64ToUint64)
4560 zero = builder.makeUint64Constant(0);
4561#ifdef AMD_EXTENSIONS
4562 else if (op == glslang::EOpConvUint16ToInt16 || op == glslang::EOpConvInt16ToUint16)
4563 zero = builder.makeUint16Constant(0);
4564#endif
4565 else
4566 zero = builder.makeUintConstant(0);
4567
qining189b2032016-04-12 23:16:20 -04004568 zero = makeSmearedConstant(zero, vectorSize);
qininge24aa5e2016-04-07 15:40:27 -04004569 // Use OpIAdd, instead of OpBitcast to do the conversion when
4570 // generating for OpSpecConstantOp instruction.
4571 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4572 }
4573 // For normal run-time conversion instruction, use OpBitcast.
John Kessenich140f3df2015-06-26 16:58:36 -06004574 convOp = spv::OpBitcast;
4575 break;
4576
4577 case glslang::EOpConvFloatToUint:
4578 case glslang::EOpConvDoubleToUint:
Rex Xu8ff43de2016-04-22 16:51:45 +08004579 case glslang::EOpConvFloatToUint64:
4580 case glslang::EOpConvDoubleToUint64:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004581#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08004582 case glslang::EOpConvFloatToUint16:
4583 case glslang::EOpConvDoubleToUint16:
4584 case glslang::EOpConvFloat16ToUint16:
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004585 case glslang::EOpConvFloat16ToUint:
4586 case glslang::EOpConvFloat16ToUint64:
4587#endif
John Kessenich140f3df2015-06-26 16:58:36 -06004588 convOp = spv::OpConvertFToU;
4589 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08004590
4591 case glslang::EOpConvIntToInt64:
4592 case glslang::EOpConvInt64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004593#ifdef AMD_EXTENSIONS
4594 case glslang::EOpConvIntToInt16:
4595 case glslang::EOpConvInt16ToInt:
4596 case glslang::EOpConvInt64ToInt16:
4597 case glslang::EOpConvInt16ToInt64:
4598#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004599 convOp = spv::OpSConvert;
4600 break;
4601
4602 case glslang::EOpConvUintToUint64:
4603 case glslang::EOpConvUint64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004604#ifdef AMD_EXTENSIONS
4605 case glslang::EOpConvUintToUint16:
4606 case glslang::EOpConvUint16ToUint:
4607 case glslang::EOpConvUint64ToUint16:
4608 case glslang::EOpConvUint16ToUint64:
4609#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004610 convOp = spv::OpUConvert;
4611 break;
4612
4613 case glslang::EOpConvIntToUint64:
4614 case glslang::EOpConvInt64ToUint:
4615 case glslang::EOpConvUint64ToInt:
4616 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004617#ifdef AMD_EXTENSIONS
4618 case glslang::EOpConvInt16ToUint:
4619 case glslang::EOpConvUintToInt16:
4620 case glslang::EOpConvInt16ToUint64:
4621 case glslang::EOpConvUint64ToInt16:
4622 case glslang::EOpConvUint16ToInt:
4623 case glslang::EOpConvIntToUint16:
4624 case glslang::EOpConvUint16ToInt64:
4625 case glslang::EOpConvInt64ToUint16:
4626#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004627 // OpSConvert/OpUConvert + OpBitCast
4628 switch (op) {
4629 case glslang::EOpConvIntToUint64:
Rex Xucabbb782017-03-24 13:41:14 +08004630#ifdef AMD_EXTENSIONS
4631 case glslang::EOpConvInt16ToUint64:
4632#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004633 convOp = spv::OpSConvert;
4634 type = builder.makeIntType(64);
4635 break;
4636 case glslang::EOpConvInt64ToUint:
Rex Xucabbb782017-03-24 13:41:14 +08004637#ifdef AMD_EXTENSIONS
4638 case glslang::EOpConvInt16ToUint:
4639#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004640 convOp = spv::OpSConvert;
4641 type = builder.makeIntType(32);
4642 break;
4643 case glslang::EOpConvUint64ToInt:
Rex Xucabbb782017-03-24 13:41:14 +08004644#ifdef AMD_EXTENSIONS
4645 case glslang::EOpConvUint16ToInt:
4646#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004647 convOp = spv::OpUConvert;
4648 type = builder.makeUintType(32);
4649 break;
4650 case glslang::EOpConvUintToInt64:
Rex Xucabbb782017-03-24 13:41:14 +08004651#ifdef AMD_EXTENSIONS
4652 case glslang::EOpConvUint16ToInt64:
4653#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004654 convOp = spv::OpUConvert;
4655 type = builder.makeUintType(64);
4656 break;
Rex Xucabbb782017-03-24 13:41:14 +08004657#ifdef AMD_EXTENSIONS
4658 case glslang::EOpConvUintToInt16:
4659 case glslang::EOpConvUint64ToInt16:
4660 convOp = spv::OpUConvert;
4661 type = builder.makeUintType(16);
4662 break;
4663 case glslang::EOpConvIntToUint16:
4664 case glslang::EOpConvInt64ToUint16:
4665 convOp = spv::OpSConvert;
4666 type = builder.makeIntType(16);
4667 break;
4668#endif
Rex Xu8ff43de2016-04-22 16:51:45 +08004669 default:
4670 assert(0);
4671 break;
4672 }
4673
4674 if (vectorSize > 0)
4675 type = builder.makeVectorType(type, vectorSize);
4676
4677 operand = builder.createUnaryOp(convOp, type, operand);
4678
4679 if (builder.isInSpecConstCodeGenMode()) {
4680 // Build zero scalar or vector for OpIAdd.
Rex Xucabbb782017-03-24 13:41:14 +08004681#ifdef AMD_EXTENSIONS
4682 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64 ||
4683 op == glslang::EOpConvInt16ToUint64 || op == glslang::EOpConvUint16ToInt64)
4684 zero = builder.makeUint64Constant(0);
4685 else if (op == glslang::EOpConvIntToUint16 || op == glslang::EOpConvUintToInt16 ||
4686 op == glslang::EOpConvInt64ToUint16 || op == glslang::EOpConvUint64ToInt16)
4687 zero = builder.makeUint16Constant(0);
4688 else
4689 zero = builder.makeUintConstant(0);
4690#else
4691 if (op == glslang::EOpConvIntToUint64 || op == glslang::EOpConvUintToInt64)
4692 zero = builder.makeUint64Constant(0);
4693 else
4694 zero = builder.makeUintConstant(0);
4695#endif
4696
Rex Xu8ff43de2016-04-22 16:51:45 +08004697 zero = makeSmearedConstant(zero, vectorSize);
4698 // Use OpIAdd, instead of OpBitcast to do the conversion when
4699 // generating for OpSpecConstantOp instruction.
4700 return builder.createBinOp(spv::OpIAdd, destType, operand, zero);
4701 }
4702 // For normal run-time conversion instruction, use OpBitcast.
4703 convOp = spv::OpBitcast;
4704 break;
John Kessenich140f3df2015-06-26 16:58:36 -06004705 default:
4706 break;
4707 }
4708
4709 spv::Id result = 0;
4710 if (convOp == spv::OpNop)
4711 return result;
4712
4713 if (convOp == spv::OpSelect) {
4714 zero = makeSmearedConstant(zero, vectorSize);
4715 one = makeSmearedConstant(one, vectorSize);
4716 result = builder.createTriOp(convOp, destType, operand, one, zero);
4717 } else
4718 result = builder.createUnaryOp(convOp, destType, operand);
4719
John Kessenich32cfd492016-02-02 12:37:46 -07004720 return builder.setPrecision(result, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06004721}
4722
4723spv::Id TGlslangToSpvTraverser::makeSmearedConstant(spv::Id constant, int vectorSize)
4724{
4725 if (vectorSize == 0)
4726 return constant;
4727
4728 spv::Id vectorTypeId = builder.makeVectorType(builder.getTypeId(constant), vectorSize);
4729 std::vector<spv::Id> components;
4730 for (int c = 0; c < vectorSize; ++c)
4731 components.push_back(constant);
4732 return builder.makeCompositeConstant(vectorTypeId, components);
4733}
4734
John Kessenich426394d2015-07-23 10:22:48 -06004735// For glslang ops that map to SPV atomic opCodes
John Kessenich6c292d32016-02-15 20:58:50 -07004736spv::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 -06004737{
4738 spv::Op opCode = spv::OpNop;
4739
4740 switch (op) {
4741 case glslang::EOpAtomicAdd:
Rex Xufc618912015-09-09 16:42:49 +08004742 case glslang::EOpImageAtomicAdd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004743 case glslang::EOpAtomicCounterAdd:
John Kessenich426394d2015-07-23 10:22:48 -06004744 opCode = spv::OpAtomicIAdd;
4745 break;
John Kessenich0d0c6d32017-07-23 16:08:26 -06004746 case glslang::EOpAtomicCounterSubtract:
4747 opCode = spv::OpAtomicISub;
4748 break;
John Kessenich426394d2015-07-23 10:22:48 -06004749 case glslang::EOpAtomicMin:
Rex Xufc618912015-09-09 16:42:49 +08004750 case glslang::EOpImageAtomicMin:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004751 case glslang::EOpAtomicCounterMin:
Rex Xue8fe8b02017-09-26 15:42:56 +08004752 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMin : spv::OpAtomicSMin;
John Kessenich426394d2015-07-23 10:22:48 -06004753 break;
4754 case glslang::EOpAtomicMax:
Rex Xufc618912015-09-09 16:42:49 +08004755 case glslang::EOpImageAtomicMax:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004756 case glslang::EOpAtomicCounterMax:
Rex Xue8fe8b02017-09-26 15:42:56 +08004757 opCode = (typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64) ? spv::OpAtomicUMax : spv::OpAtomicSMax;
John Kessenich426394d2015-07-23 10:22:48 -06004758 break;
4759 case glslang::EOpAtomicAnd:
Rex Xufc618912015-09-09 16:42:49 +08004760 case glslang::EOpImageAtomicAnd:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004761 case glslang::EOpAtomicCounterAnd:
John Kessenich426394d2015-07-23 10:22:48 -06004762 opCode = spv::OpAtomicAnd;
4763 break;
4764 case glslang::EOpAtomicOr:
Rex Xufc618912015-09-09 16:42:49 +08004765 case glslang::EOpImageAtomicOr:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004766 case glslang::EOpAtomicCounterOr:
John Kessenich426394d2015-07-23 10:22:48 -06004767 opCode = spv::OpAtomicOr;
4768 break;
4769 case glslang::EOpAtomicXor:
Rex Xufc618912015-09-09 16:42:49 +08004770 case glslang::EOpImageAtomicXor:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004771 case glslang::EOpAtomicCounterXor:
John Kessenich426394d2015-07-23 10:22:48 -06004772 opCode = spv::OpAtomicXor;
4773 break;
4774 case glslang::EOpAtomicExchange:
Rex Xufc618912015-09-09 16:42:49 +08004775 case glslang::EOpImageAtomicExchange:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004776 case glslang::EOpAtomicCounterExchange:
John Kessenich426394d2015-07-23 10:22:48 -06004777 opCode = spv::OpAtomicExchange;
4778 break;
4779 case glslang::EOpAtomicCompSwap:
Rex Xufc618912015-09-09 16:42:49 +08004780 case glslang::EOpImageAtomicCompSwap:
John Kessenich0d0c6d32017-07-23 16:08:26 -06004781 case glslang::EOpAtomicCounterCompSwap:
John Kessenich426394d2015-07-23 10:22:48 -06004782 opCode = spv::OpAtomicCompareExchange;
4783 break;
4784 case glslang::EOpAtomicCounterIncrement:
4785 opCode = spv::OpAtomicIIncrement;
4786 break;
4787 case glslang::EOpAtomicCounterDecrement:
4788 opCode = spv::OpAtomicIDecrement;
4789 break;
4790 case glslang::EOpAtomicCounter:
4791 opCode = spv::OpAtomicLoad;
4792 break;
4793 default:
John Kessenich55e7d112015-11-15 21:33:39 -07004794 assert(0);
John Kessenich426394d2015-07-23 10:22:48 -06004795 break;
4796 }
4797
Rex Xue8fe8b02017-09-26 15:42:56 +08004798 if (typeProxy == glslang::EbtInt64 || typeProxy == glslang::EbtUint64)
4799 builder.addCapability(spv::CapabilityInt64Atomics);
4800
John Kessenich426394d2015-07-23 10:22:48 -06004801 // Sort out the operands
4802 // - mapping from glslang -> SPV
4803 // - there are extra SPV operands with no glslang source
John Kessenich3e60a6f2015-09-14 22:45:16 -06004804 // - compare-exchange swaps the value and comparator
4805 // - compare-exchange has an extra memory semantics
John Kessenich426394d2015-07-23 10:22:48 -06004806 std::vector<spv::Id> spvAtomicOperands; // hold the spv operands
4807 auto opIt = operands.begin(); // walk the glslang operands
4808 spvAtomicOperands.push_back(*(opIt++));
Rex Xu04db3f52015-09-16 11:44:02 +08004809 spvAtomicOperands.push_back(builder.makeUintConstant(spv::ScopeDevice)); // TBD: what is the correct scope?
4810 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone)); // TBD: what are the correct memory semantics?
4811 if (opCode == spv::OpAtomicCompareExchange) {
Rex Xubba5c802015-09-16 13:20:37 +08004812 // There are 2 memory semantics for compare-exchange. And the operand order of "comparator" and "new value" in GLSL
4813 // differs from that in SPIR-V. Hence, special processing is required.
Rex Xu04db3f52015-09-16 11:44:02 +08004814 spvAtomicOperands.push_back(builder.makeUintConstant(spv::MemorySemanticsMaskNone));
John Kessenich3e60a6f2015-09-14 22:45:16 -06004815 spvAtomicOperands.push_back(*(opIt + 1));
4816 spvAtomicOperands.push_back(*opIt);
4817 opIt += 2;
Rex Xu04db3f52015-09-16 11:44:02 +08004818 }
John Kessenich426394d2015-07-23 10:22:48 -06004819
John Kessenich3e60a6f2015-09-14 22:45:16 -06004820 // Add the rest of the operands, skipping any that were dealt with above.
John Kessenich426394d2015-07-23 10:22:48 -06004821 for (; opIt != operands.end(); ++opIt)
4822 spvAtomicOperands.push_back(*opIt);
4823
4824 return builder.createOp(opCode, typeId, spvAtomicOperands);
4825}
4826
John Kessenich91cef522016-05-05 16:45:40 -06004827// Create group invocation operations.
Rex Xu51596642016-09-21 18:56:12 +08004828spv::Id TGlslangToSpvTraverser::createInvocationsOperation(glslang::TOperator op, spv::Id typeId, std::vector<spv::Id>& operands, glslang::TBasicType typeProxy)
John Kessenich91cef522016-05-05 16:45:40 -06004829{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004830#ifdef AMD_EXTENSIONS
Jamie Madill57cb69a2016-11-09 13:49:24 -05004831 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004832 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08004833#endif
Rex Xu9d93a232016-05-05 12:30:44 +08004834
Rex Xu51596642016-09-21 18:56:12 +08004835 spv::Op opCode = spv::OpNop;
Rex Xu51596642016-09-21 18:56:12 +08004836 std::vector<spv::Id> spvGroupOperands;
Rex Xu430ef402016-10-14 17:22:23 +08004837 spv::GroupOperation groupOperation = spv::GroupOperationMax;
4838
chaocf200da82016-12-20 12:44:35 -08004839 if (op == glslang::EOpBallot || op == glslang::EOpReadFirstInvocation ||
4840 op == glslang::EOpReadInvocation) {
Rex Xu51596642016-09-21 18:56:12 +08004841 builder.addExtension(spv::E_SPV_KHR_shader_ballot);
4842 builder.addCapability(spv::CapabilitySubgroupBallotKHR);
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004843 } else if (op == glslang::EOpAnyInvocation ||
4844 op == glslang::EOpAllInvocations ||
4845 op == glslang::EOpAllInvocationsEqual) {
4846 builder.addExtension(spv::E_SPV_KHR_subgroup_vote);
4847 builder.addCapability(spv::CapabilitySubgroupVoteKHR);
Rex Xu51596642016-09-21 18:56:12 +08004848 } else {
4849 builder.addCapability(spv::CapabilityGroups);
David Netobb5c02f2016-10-19 10:16:29 -04004850#ifdef AMD_EXTENSIONS
Rex Xu17ff3432016-10-14 17:41:45 +08004851 if (op == glslang::EOpMinInvocationsNonUniform ||
4852 op == glslang::EOpMaxInvocationsNonUniform ||
Rex Xu430ef402016-10-14 17:22:23 +08004853 op == glslang::EOpAddInvocationsNonUniform ||
4854 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4855 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
4856 op == glslang::EOpAddInvocationsInclusiveScanNonUniform ||
4857 op == glslang::EOpMinInvocationsExclusiveScanNonUniform ||
4858 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform ||
4859 op == glslang::EOpAddInvocationsExclusiveScanNonUniform)
Rex Xu17ff3432016-10-14 17:41:45 +08004860 builder.addExtension(spv::E_SPV_AMD_shader_ballot);
David Netobb5c02f2016-10-19 10:16:29 -04004861#endif
Rex Xu51596642016-09-21 18:56:12 +08004862
4863 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu9d93a232016-05-05 12:30:44 +08004864#ifdef AMD_EXTENSIONS
Rex Xu430ef402016-10-14 17:22:23 +08004865 switch (op) {
4866 case glslang::EOpMinInvocations:
4867 case glslang::EOpMaxInvocations:
4868 case glslang::EOpAddInvocations:
4869 case glslang::EOpMinInvocationsNonUniform:
4870 case glslang::EOpMaxInvocationsNonUniform:
4871 case glslang::EOpAddInvocationsNonUniform:
4872 groupOperation = spv::GroupOperationReduce;
4873 spvGroupOperands.push_back(groupOperation);
4874 break;
4875 case glslang::EOpMinInvocationsInclusiveScan:
4876 case glslang::EOpMaxInvocationsInclusiveScan:
4877 case glslang::EOpAddInvocationsInclusiveScan:
4878 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4879 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4880 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4881 groupOperation = spv::GroupOperationInclusiveScan;
4882 spvGroupOperands.push_back(groupOperation);
4883 break;
4884 case glslang::EOpMinInvocationsExclusiveScan:
4885 case glslang::EOpMaxInvocationsExclusiveScan:
4886 case glslang::EOpAddInvocationsExclusiveScan:
4887 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4888 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4889 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4890 groupOperation = spv::GroupOperationExclusiveScan;
4891 spvGroupOperands.push_back(groupOperation);
4892 break;
Mike Weiblen4e9e4002017-01-20 13:34:10 -07004893 default:
4894 break;
Rex Xu430ef402016-10-14 17:22:23 +08004895 }
Rex Xu9d93a232016-05-05 12:30:44 +08004896#endif
Rex Xu51596642016-09-21 18:56:12 +08004897 }
4898
4899 for (auto opIt = operands.begin(); opIt != operands.end(); ++opIt)
4900 spvGroupOperands.push_back(*opIt);
John Kessenich91cef522016-05-05 16:45:40 -06004901
4902 switch (op) {
4903 case glslang::EOpAnyInvocation:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004904 opCode = spv::OpSubgroupAnyKHR;
Rex Xu51596642016-09-21 18:56:12 +08004905 break;
John Kessenich91cef522016-05-05 16:45:40 -06004906 case glslang::EOpAllInvocations:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004907 opCode = spv::OpSubgroupAllKHR;
Rex Xu51596642016-09-21 18:56:12 +08004908 break;
John Kessenich91cef522016-05-05 16:45:40 -06004909 case glslang::EOpAllInvocationsEqual:
Ashwin Kolhec720f3e2017-01-18 14:16:49 -08004910 opCode = spv::OpSubgroupAllEqualKHR;
4911 break;
Rex Xu51596642016-09-21 18:56:12 +08004912 case glslang::EOpReadInvocation:
chaocf200da82016-12-20 12:44:35 -08004913 opCode = spv::OpSubgroupReadInvocationKHR;
Rex Xub7072052016-09-26 15:53:40 +08004914 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004915 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004916 break;
4917 case glslang::EOpReadFirstInvocation:
4918 opCode = spv::OpSubgroupFirstInvocationKHR;
4919 break;
4920 case glslang::EOpBallot:
4921 {
4922 // NOTE: According to the spec, the result type of "OpSubgroupBallotKHR" must be a 4 component vector of 32
4923 // bit integer types. The GLSL built-in function "ballotARB()" assumes the maximum number of invocations in
4924 // a subgroup is 64. Thus, we have to convert uvec4.xy to uint64_t as follow:
4925 //
4926 // result = Bitcast(SubgroupBallotKHR(Predicate).xy)
4927 //
4928 spv::Id uintType = builder.makeUintType(32);
4929 spv::Id uvec4Type = builder.makeVectorType(uintType, 4);
4930 spv::Id result = builder.createOp(spv::OpSubgroupBallotKHR, uvec4Type, spvGroupOperands);
4931
4932 std::vector<spv::Id> components;
4933 components.push_back(builder.createCompositeExtract(result, uintType, 0));
4934 components.push_back(builder.createCompositeExtract(result, uintType, 1));
4935
4936 spv::Id uvec2Type = builder.makeVectorType(uintType, 2);
4937 return builder.createUnaryOp(spv::OpBitcast, typeId,
4938 builder.createCompositeConstruct(uvec2Type, components));
4939 }
4940
Rex Xu9d93a232016-05-05 12:30:44 +08004941#ifdef AMD_EXTENSIONS
4942 case glslang::EOpMinInvocations:
4943 case glslang::EOpMaxInvocations:
4944 case glslang::EOpAddInvocations:
Rex Xu430ef402016-10-14 17:22:23 +08004945 case glslang::EOpMinInvocationsInclusiveScan:
4946 case glslang::EOpMaxInvocationsInclusiveScan:
4947 case glslang::EOpAddInvocationsInclusiveScan:
4948 case glslang::EOpMinInvocationsExclusiveScan:
4949 case glslang::EOpMaxInvocationsExclusiveScan:
4950 case glslang::EOpAddInvocationsExclusiveScan:
4951 if (op == glslang::EOpMinInvocations ||
4952 op == glslang::EOpMinInvocationsInclusiveScan ||
4953 op == glslang::EOpMinInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004954 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004955 opCode = spv::OpGroupFMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004956 else {
4957 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004958 opCode = spv::OpGroupUMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004959 else
Rex Xu51596642016-09-21 18:56:12 +08004960 opCode = spv::OpGroupSMin;
Rex Xu9d93a232016-05-05 12:30:44 +08004961 }
Rex Xu430ef402016-10-14 17:22:23 +08004962 } else if (op == glslang::EOpMaxInvocations ||
4963 op == glslang::EOpMaxInvocationsInclusiveScan ||
4964 op == glslang::EOpMaxInvocationsExclusiveScan) {
Rex Xu9d93a232016-05-05 12:30:44 +08004965 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004966 opCode = spv::OpGroupFMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004967 else {
4968 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08004969 opCode = spv::OpGroupUMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004970 else
Rex Xu51596642016-09-21 18:56:12 +08004971 opCode = spv::OpGroupSMax;
Rex Xu9d93a232016-05-05 12:30:44 +08004972 }
4973 } else {
4974 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004975 opCode = spv::OpGroupFAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004976 else
Rex Xu51596642016-09-21 18:56:12 +08004977 opCode = spv::OpGroupIAdd;
Rex Xu9d93a232016-05-05 12:30:44 +08004978 }
4979
Rex Xu2bbbe062016-08-23 15:41:05 +08004980 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08004981 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08004982
4983 break;
Rex Xu9d93a232016-05-05 12:30:44 +08004984 case glslang::EOpMinInvocationsNonUniform:
4985 case glslang::EOpMaxInvocationsNonUniform:
4986 case glslang::EOpAddInvocationsNonUniform:
Rex Xu430ef402016-10-14 17:22:23 +08004987 case glslang::EOpMinInvocationsInclusiveScanNonUniform:
4988 case glslang::EOpMaxInvocationsInclusiveScanNonUniform:
4989 case glslang::EOpAddInvocationsInclusiveScanNonUniform:
4990 case glslang::EOpMinInvocationsExclusiveScanNonUniform:
4991 case glslang::EOpMaxInvocationsExclusiveScanNonUniform:
4992 case glslang::EOpAddInvocationsExclusiveScanNonUniform:
4993 if (op == glslang::EOpMinInvocationsNonUniform ||
4994 op == glslang::EOpMinInvocationsInclusiveScanNonUniform ||
4995 op == glslang::EOpMinInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08004996 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08004997 opCode = spv::OpGroupFMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08004998 else {
4999 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005000 opCode = spv::OpGroupUMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005001 else
Rex Xu51596642016-09-21 18:56:12 +08005002 opCode = spv::OpGroupSMinNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005003 }
5004 }
Rex Xu430ef402016-10-14 17:22:23 +08005005 else if (op == glslang::EOpMaxInvocationsNonUniform ||
5006 op == glslang::EOpMaxInvocationsInclusiveScanNonUniform ||
5007 op == glslang::EOpMaxInvocationsExclusiveScanNonUniform) {
Rex Xu9d93a232016-05-05 12:30:44 +08005008 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005009 opCode = spv::OpGroupFMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005010 else {
5011 if (isUnsigned)
Rex Xu51596642016-09-21 18:56:12 +08005012 opCode = spv::OpGroupUMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005013 else
Rex Xu51596642016-09-21 18:56:12 +08005014 opCode = spv::OpGroupSMaxNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005015 }
5016 }
5017 else {
5018 if (isFloat)
Rex Xu51596642016-09-21 18:56:12 +08005019 opCode = spv::OpGroupFAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005020 else
Rex Xu51596642016-09-21 18:56:12 +08005021 opCode = spv::OpGroupIAddNonUniformAMD;
Rex Xu9d93a232016-05-05 12:30:44 +08005022 }
5023
Rex Xu2bbbe062016-08-23 15:41:05 +08005024 if (builder.isVectorType(typeId))
Rex Xu430ef402016-10-14 17:22:23 +08005025 return CreateInvocationsVectorOperation(opCode, groupOperation, typeId, operands);
Rex Xu51596642016-09-21 18:56:12 +08005026
5027 break;
Rex Xu9d93a232016-05-05 12:30:44 +08005028#endif
John Kessenich91cef522016-05-05 16:45:40 -06005029 default:
5030 logger->missingFunctionality("invocation operation");
5031 return spv::NoResult;
5032 }
Rex Xu51596642016-09-21 18:56:12 +08005033
5034 assert(opCode != spv::OpNop);
5035 return builder.createOp(opCode, typeId, spvGroupOperands);
John Kessenich91cef522016-05-05 16:45:40 -06005036}
5037
Rex Xu2bbbe062016-08-23 15:41:05 +08005038// Create group invocation operations on a vector
Rex Xu430ef402016-10-14 17:22:23 +08005039spv::Id TGlslangToSpvTraverser::CreateInvocationsVectorOperation(spv::Op op, spv::GroupOperation groupOperation, spv::Id typeId, std::vector<spv::Id>& operands)
Rex Xu2bbbe062016-08-23 15:41:05 +08005040{
Rex Xub7072052016-09-26 15:53:40 +08005041#ifdef AMD_EXTENSIONS
Rex Xu2bbbe062016-08-23 15:41:05 +08005042 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5043 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
Rex Xub7072052016-09-26 15:53:40 +08005044 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
chaocf200da82016-12-20 12:44:35 -08005045 op == spv::OpSubgroupReadInvocationKHR ||
Rex Xu2bbbe062016-08-23 15:41:05 +08005046 op == spv::OpGroupFMinNonUniformAMD || op == spv::OpGroupUMinNonUniformAMD || op == spv::OpGroupSMinNonUniformAMD ||
5047 op == spv::OpGroupFMaxNonUniformAMD || op == spv::OpGroupUMaxNonUniformAMD || op == spv::OpGroupSMaxNonUniformAMD ||
5048 op == spv::OpGroupFAddNonUniformAMD || op == spv::OpGroupIAddNonUniformAMD);
Rex Xub7072052016-09-26 15:53:40 +08005049#else
5050 assert(op == spv::OpGroupFMin || op == spv::OpGroupUMin || op == spv::OpGroupSMin ||
5051 op == spv::OpGroupFMax || op == spv::OpGroupUMax || op == spv::OpGroupSMax ||
chaocf200da82016-12-20 12:44:35 -08005052 op == spv::OpGroupFAdd || op == spv::OpGroupIAdd || op == spv::OpGroupBroadcast ||
5053 op == spv::OpSubgroupReadInvocationKHR);
Rex Xub7072052016-09-26 15:53:40 +08005054#endif
Rex Xu2bbbe062016-08-23 15:41:05 +08005055
5056 // Handle group invocation operations scalar by scalar.
5057 // The result type is the same type as the original type.
5058 // The algorithm is to:
5059 // - break the vector into scalars
5060 // - apply the operation to each scalar
5061 // - make a vector out the scalar results
5062
5063 // get the types sorted out
Rex Xub7072052016-09-26 15:53:40 +08005064 int numComponents = builder.getNumComponents(operands[0]);
5065 spv::Id scalarType = builder.getScalarTypeId(builder.getTypeId(operands[0]));
Rex Xu2bbbe062016-08-23 15:41:05 +08005066 std::vector<spv::Id> results;
5067
5068 // do each scalar op
5069 for (int comp = 0; comp < numComponents; ++comp) {
5070 std::vector<unsigned int> indexes;
5071 indexes.push_back(comp);
Rex Xub7072052016-09-26 15:53:40 +08005072 spv::Id scalar = builder.createCompositeExtract(operands[0], scalarType, indexes);
Rex Xub7072052016-09-26 15:53:40 +08005073 std::vector<spv::Id> spvGroupOperands;
chaocf200da82016-12-20 12:44:35 -08005074 if (op == spv::OpSubgroupReadInvocationKHR) {
5075 spvGroupOperands.push_back(scalar);
5076 spvGroupOperands.push_back(operands[1]);
5077 } else if (op == spv::OpGroupBroadcast) {
5078 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xub7072052016-09-26 15:53:40 +08005079 spvGroupOperands.push_back(scalar);
5080 spvGroupOperands.push_back(operands[1]);
5081 } else {
chaocf200da82016-12-20 12:44:35 -08005082 spvGroupOperands.push_back(builder.makeUintConstant(spv::ScopeSubgroup));
Rex Xu430ef402016-10-14 17:22:23 +08005083 spvGroupOperands.push_back(groupOperation);
Rex Xub7072052016-09-26 15:53:40 +08005084 spvGroupOperands.push_back(scalar);
5085 }
Rex Xu2bbbe062016-08-23 15:41:05 +08005086
Rex Xub7072052016-09-26 15:53:40 +08005087 results.push_back(builder.createOp(op, scalarType, spvGroupOperands));
Rex Xu2bbbe062016-08-23 15:41:05 +08005088 }
5089
5090 // put the pieces together
5091 return builder.createCompositeConstruct(typeId, results);
5092}
Rex Xu2bbbe062016-08-23 15:41:05 +08005093
John Kessenich5e4b1242015-08-06 22:53:06 -06005094spv::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 -06005095{
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005096#ifdef AMD_EXTENSIONS
Rex Xucabbb782017-03-24 13:41:14 +08005097 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64 || typeProxy == glslang::EbtUint16;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005098 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble || typeProxy == glslang::EbtFloat16;
5099#else
Rex Xucabbb782017-03-24 13:41:14 +08005100 bool isUnsigned = typeProxy == glslang::EbtUint || typeProxy == glslang::EbtUint64;
John Kessenich5e4b1242015-08-06 22:53:06 -06005101 bool isFloat = typeProxy == glslang::EbtFloat || typeProxy == glslang::EbtDouble;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005102#endif
John Kessenich5e4b1242015-08-06 22:53:06 -06005103
John Kessenich140f3df2015-06-26 16:58:36 -06005104 spv::Op opCode = spv::OpNop;
Rex Xu9d93a232016-05-05 12:30:44 +08005105 int extBuiltins = -1;
John Kessenich140f3df2015-06-26 16:58:36 -06005106 int libCall = -1;
Mark Adams364c21c2016-01-06 13:41:02 -05005107 size_t consumedOperands = operands.size();
John Kessenich55e7d112015-11-15 21:33:39 -07005108 spv::Id typeId0 = 0;
5109 if (consumedOperands > 0)
5110 typeId0 = builder.getTypeId(operands[0]);
Rex Xu470026f2017-03-29 17:12:40 +08005111 spv::Id typeId1 = 0;
5112 if (consumedOperands > 1)
5113 typeId1 = builder.getTypeId(operands[1]);
John Kessenich55e7d112015-11-15 21:33:39 -07005114 spv::Id frexpIntType = 0;
John Kessenich140f3df2015-06-26 16:58:36 -06005115
5116 switch (op) {
5117 case glslang::EOpMin:
John Kessenich5e4b1242015-08-06 22:53:06 -06005118 if (isFloat)
5119 libCall = spv::GLSLstd450FMin;
5120 else if (isUnsigned)
5121 libCall = spv::GLSLstd450UMin;
5122 else
5123 libCall = spv::GLSLstd450SMin;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005124 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005125 break;
5126 case glslang::EOpModf:
John Kessenich5e4b1242015-08-06 22:53:06 -06005127 libCall = spv::GLSLstd450Modf;
John Kessenich140f3df2015-06-26 16:58:36 -06005128 break;
5129 case glslang::EOpMax:
John Kessenich5e4b1242015-08-06 22:53:06 -06005130 if (isFloat)
5131 libCall = spv::GLSLstd450FMax;
5132 else if (isUnsigned)
5133 libCall = spv::GLSLstd450UMax;
5134 else
5135 libCall = spv::GLSLstd450SMax;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005136 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005137 break;
5138 case glslang::EOpPow:
John Kessenich5e4b1242015-08-06 22:53:06 -06005139 libCall = spv::GLSLstd450Pow;
John Kessenich140f3df2015-06-26 16:58:36 -06005140 break;
5141 case glslang::EOpDot:
5142 opCode = spv::OpDot;
5143 break;
5144 case glslang::EOpAtan:
John Kessenich5e4b1242015-08-06 22:53:06 -06005145 libCall = spv::GLSLstd450Atan2;
John Kessenich140f3df2015-06-26 16:58:36 -06005146 break;
5147
5148 case glslang::EOpClamp:
John Kessenich5e4b1242015-08-06 22:53:06 -06005149 if (isFloat)
5150 libCall = spv::GLSLstd450FClamp;
5151 else if (isUnsigned)
5152 libCall = spv::GLSLstd450UClamp;
5153 else
5154 libCall = spv::GLSLstd450SClamp;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005155 builder.promoteScalar(precision, operands.front(), operands[1]);
5156 builder.promoteScalar(precision, operands.front(), operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005157 break;
5158 case glslang::EOpMix:
Rex Xud715adc2016-03-15 12:08:31 +08005159 if (! builder.isBoolType(builder.getScalarTypeId(builder.getTypeId(operands.back())))) {
5160 assert(isFloat);
John Kessenich55e7d112015-11-15 21:33:39 -07005161 libCall = spv::GLSLstd450FMix;
Rex Xud715adc2016-03-15 12:08:31 +08005162 } else {
John Kessenich6c292d32016-02-15 20:58:50 -07005163 opCode = spv::OpSelect;
Rex Xud715adc2016-03-15 12:08:31 +08005164 std::swap(operands.front(), operands.back());
John Kessenich6c292d32016-02-15 20:58:50 -07005165 }
John Kesseniche7c83cf2015-12-13 13:34:37 -07005166 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005167 break;
5168 case glslang::EOpStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005169 libCall = spv::GLSLstd450Step;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005170 builder.promoteScalar(precision, operands.front(), operands.back());
John Kessenich140f3df2015-06-26 16:58:36 -06005171 break;
5172 case glslang::EOpSmoothStep:
John Kessenich5e4b1242015-08-06 22:53:06 -06005173 libCall = spv::GLSLstd450SmoothStep;
John Kesseniche7c83cf2015-12-13 13:34:37 -07005174 builder.promoteScalar(precision, operands[0], operands[2]);
5175 builder.promoteScalar(precision, operands[1], operands[2]);
John Kessenich140f3df2015-06-26 16:58:36 -06005176 break;
5177
5178 case glslang::EOpDistance:
John Kessenich5e4b1242015-08-06 22:53:06 -06005179 libCall = spv::GLSLstd450Distance;
John Kessenich140f3df2015-06-26 16:58:36 -06005180 break;
5181 case glslang::EOpCross:
John Kessenich5e4b1242015-08-06 22:53:06 -06005182 libCall = spv::GLSLstd450Cross;
John Kessenich140f3df2015-06-26 16:58:36 -06005183 break;
5184 case glslang::EOpFaceForward:
John Kessenich5e4b1242015-08-06 22:53:06 -06005185 libCall = spv::GLSLstd450FaceForward;
John Kessenich140f3df2015-06-26 16:58:36 -06005186 break;
5187 case glslang::EOpReflect:
John Kessenich5e4b1242015-08-06 22:53:06 -06005188 libCall = spv::GLSLstd450Reflect;
John Kessenich140f3df2015-06-26 16:58:36 -06005189 break;
5190 case glslang::EOpRefract:
John Kessenich5e4b1242015-08-06 22:53:06 -06005191 libCall = spv::GLSLstd450Refract;
John Kessenich140f3df2015-06-26 16:58:36 -06005192 break;
Rex Xu7a26c172015-12-08 17:12:09 +08005193 case glslang::EOpInterpolateAtSample:
John Kessenich92187592016-02-01 13:45:25 -07005194 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005195 libCall = spv::GLSLstd450InterpolateAtSample;
5196 break;
5197 case glslang::EOpInterpolateAtOffset:
John Kessenich92187592016-02-01 13:45:25 -07005198 builder.addCapability(spv::CapabilityInterpolationFunction);
Rex Xu7a26c172015-12-08 17:12:09 +08005199 libCall = spv::GLSLstd450InterpolateAtOffset;
5200 break;
John Kessenich55e7d112015-11-15 21:33:39 -07005201 case glslang::EOpAddCarry:
5202 opCode = spv::OpIAddCarry;
5203 typeId = builder.makeStructResultType(typeId0, typeId0);
5204 consumedOperands = 2;
5205 break;
5206 case glslang::EOpSubBorrow:
5207 opCode = spv::OpISubBorrow;
5208 typeId = builder.makeStructResultType(typeId0, typeId0);
5209 consumedOperands = 2;
5210 break;
5211 case glslang::EOpUMulExtended:
5212 opCode = spv::OpUMulExtended;
5213 typeId = builder.makeStructResultType(typeId0, typeId0);
5214 consumedOperands = 2;
5215 break;
5216 case glslang::EOpIMulExtended:
5217 opCode = spv::OpSMulExtended;
5218 typeId = builder.makeStructResultType(typeId0, typeId0);
5219 consumedOperands = 2;
5220 break;
5221 case glslang::EOpBitfieldExtract:
5222 if (isUnsigned)
5223 opCode = spv::OpBitFieldUExtract;
5224 else
5225 opCode = spv::OpBitFieldSExtract;
5226 break;
5227 case glslang::EOpBitfieldInsert:
5228 opCode = spv::OpBitFieldInsert;
5229 break;
5230
5231 case glslang::EOpFma:
5232 libCall = spv::GLSLstd450Fma;
5233 break;
5234 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005235 {
5236 libCall = spv::GLSLstd450FrexpStruct;
5237 assert(builder.isPointerType(typeId1));
5238 typeId1 = builder.getContainedTypeId(typeId1);
5239#ifdef AMD_EXTENSIONS
5240 int width = builder.getScalarTypeWidth(typeId1);
5241#else
5242 int width = 32;
5243#endif
5244 if (builder.getNumComponents(operands[0]) == 1)
5245 frexpIntType = builder.makeIntegerType(width, true);
5246 else
5247 frexpIntType = builder.makeVectorType(builder.makeIntegerType(width, true), builder.getNumComponents(operands[0]));
5248 typeId = builder.makeStructResultType(typeId0, frexpIntType);
5249 consumedOperands = 1;
5250 }
John Kessenich55e7d112015-11-15 21:33:39 -07005251 break;
5252 case glslang::EOpLdexp:
5253 libCall = spv::GLSLstd450Ldexp;
5254 break;
5255
Rex Xu574ab042016-04-14 16:53:07 +08005256 case glslang::EOpReadInvocation:
Rex Xu51596642016-09-21 18:56:12 +08005257 return createInvocationsOperation(op, typeId, operands, typeProxy);
Rex Xu574ab042016-04-14 16:53:07 +08005258
Rex Xu9d93a232016-05-05 12:30:44 +08005259#ifdef AMD_EXTENSIONS
5260 case glslang::EOpSwizzleInvocations:
5261 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5262 libCall = spv::SwizzleInvocationsAMD;
5263 break;
5264 case glslang::EOpSwizzleInvocationsMasked:
5265 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5266 libCall = spv::SwizzleInvocationsMaskedAMD;
5267 break;
5268 case glslang::EOpWriteInvocation:
5269 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_ballot);
5270 libCall = spv::WriteInvocationAMD;
5271 break;
5272
5273 case glslang::EOpMin3:
5274 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5275 if (isFloat)
5276 libCall = spv::FMin3AMD;
5277 else {
5278 if (isUnsigned)
5279 libCall = spv::UMin3AMD;
5280 else
5281 libCall = spv::SMin3AMD;
5282 }
5283 break;
5284 case glslang::EOpMax3:
5285 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5286 if (isFloat)
5287 libCall = spv::FMax3AMD;
5288 else {
5289 if (isUnsigned)
5290 libCall = spv::UMax3AMD;
5291 else
5292 libCall = spv::SMax3AMD;
5293 }
5294 break;
5295 case glslang::EOpMid3:
5296 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_trinary_minmax);
5297 if (isFloat)
5298 libCall = spv::FMid3AMD;
5299 else {
5300 if (isUnsigned)
5301 libCall = spv::UMid3AMD;
5302 else
5303 libCall = spv::SMid3AMD;
5304 }
5305 break;
5306
5307 case glslang::EOpInterpolateAtVertex:
5308 extBuiltins = getExtBuiltins(spv::E_SPV_AMD_shader_explicit_vertex_parameter);
5309 libCall = spv::InterpolateAtVertexAMD;
5310 break;
5311#endif
5312
John Kessenich140f3df2015-06-26 16:58:36 -06005313 default:
5314 return 0;
5315 }
5316
5317 spv::Id id = 0;
John Kessenich2359bd02015-12-06 19:29:11 -07005318 if (libCall >= 0) {
David Neto8d63a3d2015-12-07 16:17:06 -05005319 // Use an extended instruction from the standard library.
5320 // Construct the call arguments, without modifying the original operands vector.
5321 // We might need the remaining arguments, e.g. in the EOpFrexp case.
5322 std::vector<spv::Id> callArguments(operands.begin(), operands.begin() + consumedOperands);
Rex Xu9d93a232016-05-05 12:30:44 +08005323 id = builder.createBuiltinCall(typeId, extBuiltins >= 0 ? extBuiltins : stdBuiltins, libCall, callArguments);
John Kessenich2359bd02015-12-06 19:29:11 -07005324 } else {
John Kessenich55e7d112015-11-15 21:33:39 -07005325 switch (consumedOperands) {
John Kessenich140f3df2015-06-26 16:58:36 -06005326 case 0:
5327 // should all be handled by visitAggregate and createNoArgOperation
5328 assert(0);
5329 return 0;
5330 case 1:
5331 // should all be handled by createUnaryOperation
5332 assert(0);
5333 return 0;
5334 case 2:
5335 id = builder.createBinOp(opCode, typeId, operands[0], operands[1]);
5336 break;
John Kessenich140f3df2015-06-26 16:58:36 -06005337 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005338 // anything 3 or over doesn't have l-value operands, so all should be consumed
5339 assert(consumedOperands == operands.size());
5340 id = builder.createOp(opCode, typeId, operands);
John Kessenich140f3df2015-06-26 16:58:36 -06005341 break;
5342 }
5343 }
5344
John Kessenich55e7d112015-11-15 21:33:39 -07005345 // Decode the return types that were structures
5346 switch (op) {
5347 case glslang::EOpAddCarry:
5348 case glslang::EOpSubBorrow:
5349 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5350 id = builder.createCompositeExtract(id, typeId0, 0);
5351 break;
5352 case glslang::EOpUMulExtended:
5353 case glslang::EOpIMulExtended:
5354 builder.createStore(builder.createCompositeExtract(id, typeId0, 0), operands[3]);
5355 builder.createStore(builder.createCompositeExtract(id, typeId0, 1), operands[2]);
5356 break;
5357 case glslang::EOpFrexp:
Rex Xu470026f2017-03-29 17:12:40 +08005358 {
5359 assert(operands.size() == 2);
5360 if (builder.isFloatType(builder.getScalarTypeId(typeId1))) {
5361 // "exp" is floating-point type (from HLSL intrinsic)
5362 spv::Id member1 = builder.createCompositeExtract(id, frexpIntType, 1);
5363 member1 = builder.createUnaryOp(spv::OpConvertSToF, typeId1, member1);
5364 builder.createStore(member1, operands[1]);
5365 } else
5366 // "exp" is integer type (from GLSL built-in function)
5367 builder.createStore(builder.createCompositeExtract(id, frexpIntType, 1), operands[1]);
5368 id = builder.createCompositeExtract(id, typeId0, 0);
5369 }
John Kessenich55e7d112015-11-15 21:33:39 -07005370 break;
5371 default:
5372 break;
5373 }
5374
John Kessenich32cfd492016-02-02 12:37:46 -07005375 return builder.setPrecision(id, precision);
John Kessenich140f3df2015-06-26 16:58:36 -06005376}
5377
Rex Xu9d93a232016-05-05 12:30:44 +08005378// Intrinsics with no arguments (or no return value, and no precision).
5379spv::Id TGlslangToSpvTraverser::createNoArgOperation(glslang::TOperator op, spv::Decoration precision, spv::Id typeId)
John Kessenich140f3df2015-06-26 16:58:36 -06005380{
5381 // TODO: get the barrier operands correct
5382
5383 switch (op) {
5384 case glslang::EOpEmitVertex:
5385 builder.createNoResultOp(spv::OpEmitVertex);
5386 return 0;
5387 case glslang::EOpEndPrimitive:
5388 builder.createNoResultOp(spv::OpEndPrimitive);
5389 return 0;
5390 case glslang::EOpBarrier:
chrgau01@arm.comc3f1cdf2016-11-14 10:10:05 +01005391 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeDevice, spv::MemorySemanticsMaskNone);
John Kessenich140f3df2015-06-26 16:58:36 -06005392 return 0;
5393 case glslang::EOpMemoryBarrier:
John Kessenich5e4b1242015-08-06 22:53:06 -06005394 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAllMemory);
John Kessenich140f3df2015-06-26 16:58:36 -06005395 return 0;
5396 case glslang::EOpMemoryBarrierAtomicCounter:
John Kessenich5e4b1242015-08-06 22:53:06 -06005397 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsAtomicCounterMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005398 return 0;
5399 case glslang::EOpMemoryBarrierBuffer:
John Kessenich5e4b1242015-08-06 22:53:06 -06005400 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsUniformMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005401 return 0;
5402 case glslang::EOpMemoryBarrierImage:
John Kessenich5e4b1242015-08-06 22:53:06 -06005403 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsImageMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005404 return 0;
5405 case glslang::EOpMemoryBarrierShared:
John Kessenich55e7d112015-11-15 21:33:39 -07005406 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005407 return 0;
5408 case glslang::EOpGroupMemoryBarrier:
John Kessenich55e7d112015-11-15 21:33:39 -07005409 builder.createMemoryBarrier(spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
John Kessenich140f3df2015-06-26 16:58:36 -06005410 return 0;
LoopDawg6e72fdd2016-06-15 09:50:24 -06005411 case glslang::EOpAllMemoryBarrierWithGroupSync:
5412 // Control barrier with non-"None" semantic is also a memory barrier.
5413 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsAllMemory);
5414 return 0;
5415 case glslang::EOpGroupMemoryBarrierWithGroupSync:
5416 // Control barrier with non-"None" semantic is also a memory barrier.
5417 builder.createControlBarrier(spv::ScopeDevice, spv::ScopeDevice, spv::MemorySemanticsCrossWorkgroupMemoryMask);
5418 return 0;
5419 case glslang::EOpWorkgroupMemoryBarrier:
5420 builder.createMemoryBarrier(spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5421 return 0;
5422 case glslang::EOpWorkgroupMemoryBarrierWithGroupSync:
5423 // Control barrier with non-"None" semantic is also a memory barrier.
5424 builder.createControlBarrier(spv::ScopeWorkgroup, spv::ScopeWorkgroup, spv::MemorySemanticsWorkgroupMemoryMask);
5425 return 0;
Rex Xu9d93a232016-05-05 12:30:44 +08005426#ifdef AMD_EXTENSIONS
5427 case glslang::EOpTime:
5428 {
5429 std::vector<spv::Id> args; // Dummy arguments
5430 spv::Id id = builder.createBuiltinCall(typeId, getExtBuiltins(spv::E_SPV_AMD_gcn_shader), spv::TimeAMD, args);
5431 return builder.setPrecision(id, precision);
5432 }
5433#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005434 default:
Lei Zhang17535f72016-05-04 15:55:59 -04005435 logger->missingFunctionality("unknown operation with no arguments");
John Kessenich140f3df2015-06-26 16:58:36 -06005436 return 0;
5437 }
5438}
5439
5440spv::Id TGlslangToSpvTraverser::getSymbolId(const glslang::TIntermSymbol* symbol)
5441{
John Kessenich2f273362015-07-18 22:34:27 -06005442 auto iter = symbolValues.find(symbol->getId());
John Kessenich140f3df2015-06-26 16:58:36 -06005443 spv::Id id;
5444 if (symbolValues.end() != iter) {
5445 id = iter->second;
5446 return id;
5447 }
5448
5449 // it was not found, create it
5450 id = createSpvVariable(symbol);
5451 symbolValues[symbol->getId()] = id;
5452
Rex Xuc884b4a2016-06-29 15:03:44 +08005453 if (symbol->getBasicType() != glslang::EbtBlock) {
John Kessenich140f3df2015-06-26 16:58:36 -06005454 addDecoration(id, TranslatePrecisionDecoration(symbol->getType()));
John Kesseniche0b6cad2015-12-24 10:30:13 -07005455 addDecoration(id, TranslateInterpolationDecoration(symbol->getType().getQualifier()));
Rex Xubbceed72016-05-21 09:40:44 +08005456 addDecoration(id, TranslateAuxiliaryStorageDecoration(symbol->getType().getQualifier()));
John Kessenich6c292d32016-02-15 20:58:50 -07005457 if (symbol->getType().getQualifier().hasSpecConstantId())
5458 addDecoration(id, spv::DecorationSpecId, symbol->getType().getQualifier().layoutSpecConstantId);
John Kessenich140f3df2015-06-26 16:58:36 -06005459 if (symbol->getQualifier().hasIndex())
5460 builder.addDecoration(id, spv::DecorationIndex, symbol->getQualifier().layoutIndex);
5461 if (symbol->getQualifier().hasComponent())
5462 builder.addDecoration(id, spv::DecorationComponent, symbol->getQualifier().layoutComponent);
5463 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005464 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005465 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005466 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005467 if (symbol->getQualifier().hasXfbBuffer())
5468 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5469 if (symbol->getQualifier().hasXfbOffset())
5470 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutXfbOffset);
5471 }
John Kessenich91e4aa52016-07-07 17:46:42 -06005472 // atomic counters use this:
5473 if (symbol->getQualifier().hasOffset())
5474 builder.addDecoration(id, spv::DecorationOffset, symbol->getQualifier().layoutOffset);
John Kessenich140f3df2015-06-26 16:58:36 -06005475 }
5476
scygan2c864272016-05-18 18:09:17 +02005477 if (symbol->getQualifier().hasLocation())
5478 builder.addDecoration(id, spv::DecorationLocation, symbol->getQualifier().layoutLocation);
John Kesseniche0b6cad2015-12-24 10:30:13 -07005479 addDecoration(id, TranslateInvariantDecoration(symbol->getType().getQualifier()));
John Kessenichf2d8a5c2016-03-03 22:29:11 -07005480 if (symbol->getQualifier().hasStream() && glslangIntermediate->isMultiStream()) {
John Kessenich92187592016-02-01 13:45:25 -07005481 builder.addCapability(spv::CapabilityGeometryStreams);
John Kessenich140f3df2015-06-26 16:58:36 -06005482 builder.addDecoration(id, spv::DecorationStream, symbol->getQualifier().layoutStream);
John Kessenich92187592016-02-01 13:45:25 -07005483 }
John Kessenich140f3df2015-06-26 16:58:36 -06005484 if (symbol->getQualifier().hasSet())
5485 builder.addDecoration(id, spv::DecorationDescriptorSet, symbol->getQualifier().layoutSet);
John Kessenich6c292d32016-02-15 20:58:50 -07005486 else if (IsDescriptorResource(symbol->getType())) {
5487 // default to 0
5488 builder.addDecoration(id, spv::DecorationDescriptorSet, 0);
5489 }
John Kessenich140f3df2015-06-26 16:58:36 -06005490 if (symbol->getQualifier().hasBinding())
5491 builder.addDecoration(id, spv::DecorationBinding, symbol->getQualifier().layoutBinding);
John Kessenich6c292d32016-02-15 20:58:50 -07005492 if (symbol->getQualifier().hasAttachment())
5493 builder.addDecoration(id, spv::DecorationInputAttachmentIndex, symbol->getQualifier().layoutAttachment);
John Kessenich140f3df2015-06-26 16:58:36 -06005494 if (glslangIntermediate->getXfbMode()) {
John Kessenich92187592016-02-01 13:45:25 -07005495 builder.addCapability(spv::CapabilityTransformFeedback);
John Kessenich140f3df2015-06-26 16:58:36 -06005496 if (symbol->getQualifier().hasXfbStride())
John Kessenich5e4b1242015-08-06 22:53:06 -06005497 builder.addDecoration(id, spv::DecorationXfbStride, symbol->getQualifier().layoutXfbStride);
John Kessenich140f3df2015-06-26 16:58:36 -06005498 if (symbol->getQualifier().hasXfbBuffer())
5499 builder.addDecoration(id, spv::DecorationXfbBuffer, symbol->getQualifier().layoutXfbBuffer);
5500 }
5501
Rex Xu1da878f2016-02-21 20:59:01 +08005502 if (symbol->getType().isImage()) {
5503 std::vector<spv::Decoration> memory;
5504 TranslateMemoryDecoration(symbol->getType().getQualifier(), memory);
5505 for (unsigned int i = 0; i < memory.size(); ++i)
5506 addDecoration(id, memory[i]);
5507 }
5508
John Kessenich140f3df2015-06-26 16:58:36 -06005509 // built-in variable decorations
John Kessenichebb50532016-05-16 19:22:05 -06005510 spv::BuiltIn builtIn = TranslateBuiltInDecoration(symbol->getQualifier().builtIn, false);
John Kessenich4016e382016-07-15 11:53:56 -06005511 if (builtIn != spv::BuiltInMax)
John Kessenich92187592016-02-01 13:45:25 -07005512 addDecoration(id, spv::DecorationBuiltIn, (int)builtIn);
John Kessenich140f3df2015-06-26 16:58:36 -06005513
John Kessenichecba76f2017-01-06 00:34:48 -07005514#ifdef NV_EXTENSIONS
chaoc0ad6a4e2016-12-19 16:29:34 -08005515 if (builtIn == spv::BuiltInSampleMask) {
5516 spv::Decoration decoration;
5517 // GL_NV_sample_mask_override_coverage extension
5518 if (glslangIntermediate->getLayoutOverrideCoverage())
chaoc771d89f2017-01-13 01:10:53 -08005519 decoration = (spv::Decoration)spv::DecorationOverrideCoverageNV;
chaoc0ad6a4e2016-12-19 16:29:34 -08005520 else
5521 decoration = (spv::Decoration)spv::DecorationMax;
5522 addDecoration(id, decoration);
5523 if (decoration != spv::DecorationMax) {
5524 builder.addExtension(spv::E_SPV_NV_sample_mask_override_coverage);
5525 }
5526 }
chaoc771d89f2017-01-13 01:10:53 -08005527 else if (builtIn == spv::BuiltInLayer) {
5528 // SPV_NV_viewport_array2 extension
John Kessenichb41bff62017-08-11 13:07:17 -06005529 if (symbol->getQualifier().layoutViewportRelative) {
chaoc771d89f2017-01-13 01:10:53 -08005530 addDecoration(id, (spv::Decoration)spv::DecorationViewportRelativeNV);
5531 builder.addCapability(spv::CapabilityShaderViewportMaskNV);
5532 builder.addExtension(spv::E_SPV_NV_viewport_array2);
5533 }
John Kessenichb41bff62017-08-11 13:07:17 -06005534 if (symbol->getQualifier().layoutSecondaryViewportRelativeOffset != -2048) {
chaoc771d89f2017-01-13 01:10:53 -08005535 addDecoration(id, (spv::Decoration)spv::DecorationSecondaryViewportRelativeNV, symbol->getQualifier().layoutSecondaryViewportRelativeOffset);
5536 builder.addCapability(spv::CapabilityShaderStereoViewNV);
5537 builder.addExtension(spv::E_SPV_NV_stereo_view_rendering);
5538 }
5539 }
5540
chaoc6e5acae2016-12-20 13:28:52 -08005541 if (symbol->getQualifier().layoutPassthrough) {
chaoc771d89f2017-01-13 01:10:53 -08005542 addDecoration(id, spv::DecorationPassthroughNV);
5543 builder.addCapability(spv::CapabilityGeometryShaderPassthroughNV);
chaoc6e5acae2016-12-20 13:28:52 -08005544 builder.addExtension(spv::E_SPV_NV_geometry_shader_passthrough);
5545 }
chaoc0ad6a4e2016-12-19 16:29:34 -08005546#endif
5547
John Kessenich140f3df2015-06-26 16:58:36 -06005548 return id;
5549}
5550
John Kessenich55e7d112015-11-15 21:33:39 -07005551// If 'dec' is valid, add no-operand decoration to an object
John Kessenich140f3df2015-06-26 16:58:36 -06005552void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec)
5553{
John Kessenich4016e382016-07-15 11:53:56 -06005554 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005555 builder.addDecoration(id, dec);
5556}
5557
John Kessenich55e7d112015-11-15 21:33:39 -07005558// If 'dec' is valid, add a one-operand decoration to an object
5559void TGlslangToSpvTraverser::addDecoration(spv::Id id, spv::Decoration dec, unsigned value)
5560{
John Kessenich4016e382016-07-15 11:53:56 -06005561 if (dec != spv::DecorationMax)
John Kessenich55e7d112015-11-15 21:33:39 -07005562 builder.addDecoration(id, dec, value);
5563}
5564
5565// If 'dec' is valid, add a no-operand decoration to a struct member
John Kessenich140f3df2015-06-26 16:58:36 -06005566void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec)
5567{
John Kessenich4016e382016-07-15 11:53:56 -06005568 if (dec != spv::DecorationMax)
John Kessenich140f3df2015-06-26 16:58:36 -06005569 builder.addMemberDecoration(id, (unsigned)member, dec);
5570}
5571
John Kessenich92187592016-02-01 13:45:25 -07005572// If 'dec' is valid, add a one-operand decoration to a struct member
5573void TGlslangToSpvTraverser::addMemberDecoration(spv::Id id, int member, spv::Decoration dec, unsigned value)
5574{
John Kessenich4016e382016-07-15 11:53:56 -06005575 if (dec != spv::DecorationMax)
John Kessenich92187592016-02-01 13:45:25 -07005576 builder.addMemberDecoration(id, (unsigned)member, dec, value);
5577}
5578
John Kessenich55e7d112015-11-15 21:33:39 -07005579// Make a full tree of instructions to build a SPIR-V specialization constant,
John Kessenich6c292d32016-02-15 20:58:50 -07005580// or regular constant if possible.
John Kessenich55e7d112015-11-15 21:33:39 -07005581//
5582// TBD: this is not yet done, nor verified to be the best design, it does do the leaf symbols though
5583//
5584// Recursively walk the nodes. The nodes form a tree whose leaves are
5585// regular constants, which themselves are trees that createSpvConstant()
5586// recursively walks. So, this function walks the "top" of the tree:
5587// - emit specialization constant-building instructions for specConstant
5588// - when running into a non-spec-constant, switch to createSpvConstant()
qining08408382016-03-21 09:51:37 -04005589spv::Id TGlslangToSpvTraverser::createSpvConstant(const glslang::TIntermTyped& node)
John Kessenich55e7d112015-11-15 21:33:39 -07005590{
John Kessenich7cc0e282016-03-20 00:46:02 -06005591 assert(node.getQualifier().isConstant());
John Kessenich55e7d112015-11-15 21:33:39 -07005592
qining4f4bb812016-04-03 23:55:17 -04005593 // Handle front-end constants first (non-specialization constants).
John Kessenich6c292d32016-02-15 20:58:50 -07005594 if (! node.getQualifier().specConstant) {
5595 // hand off to the non-spec-constant path
5596 assert(node.getAsConstantUnion() != nullptr || node.getAsSymbolNode() != nullptr);
5597 int nextConst = 0;
qining08408382016-03-21 09:51:37 -04005598 return createSpvConstantFromConstUnionArray(node.getType(), node.getAsConstantUnion() ? node.getAsConstantUnion()->getConstArray() : node.getAsSymbolNode()->getConstArray(),
John Kessenich6c292d32016-02-15 20:58:50 -07005599 nextConst, false);
5600 }
5601
5602 // We now know we have a specialization constant to build
5603
John Kessenichd94c0032016-05-30 19:29:40 -06005604 // gl_WorkGroupSize is a special case until the front-end handles hierarchical specialization constants,
qining4f4bb812016-04-03 23:55:17 -04005605 // even then, it's specialization ids are handled by special case syntax in GLSL: layout(local_size_x = ...
5606 if (node.getType().getQualifier().builtIn == glslang::EbvWorkGroupSize) {
5607 std::vector<spv::Id> dimConstId;
5608 for (int dim = 0; dim < 3; ++dim) {
5609 bool specConst = (glslangIntermediate->getLocalSizeSpecId(dim) != glslang::TQualifier::layoutNotSet);
5610 dimConstId.push_back(builder.makeUintConstant(glslangIntermediate->getLocalSize(dim), specConst));
5611 if (specConst)
5612 addDecoration(dimConstId.back(), spv::DecorationSpecId, glslangIntermediate->getLocalSizeSpecId(dim));
5613 }
5614 return builder.makeCompositeConstant(builder.makeVectorType(builder.makeUintType(32), 3), dimConstId, true);
5615 }
5616
5617 // An AST node labelled as specialization constant should be a symbol node.
5618 // Its initializer should either be a sub tree with constant nodes, or a constant union array.
5619 if (auto* sn = node.getAsSymbolNode()) {
5620 if (auto* sub_tree = sn->getConstSubtree()) {
qining27e04a02016-04-14 16:40:20 -04005621 // Traverse the constant constructor sub tree like generating normal run-time instructions.
5622 // During the AST traversal, if the node is marked as 'specConstant', SpecConstantOpModeGuard
5623 // will set the builder into spec constant op instruction generating mode.
5624 sub_tree->traverse(this);
5625 return accessChainLoad(sub_tree->getType());
qining4f4bb812016-04-03 23:55:17 -04005626 } else if (auto* const_union_array = &sn->getConstArray()){
5627 int nextConst = 0;
Endre Omaad58d452017-01-31 21:08:19 +01005628 spv::Id id = createSpvConstantFromConstUnionArray(sn->getType(), *const_union_array, nextConst, true);
5629 builder.addName(id, sn->getName().c_str());
5630 return id;
John Kessenich6c292d32016-02-15 20:58:50 -07005631 }
5632 }
qining4f4bb812016-04-03 23:55:17 -04005633
5634 // Neither a front-end constant node, nor a specialization constant node with constant union array or
5635 // constant sub tree as initializer.
Lei Zhang17535f72016-05-04 15:55:59 -04005636 logger->missingFunctionality("Neither a front-end constant nor a spec constant.");
qining4f4bb812016-04-03 23:55:17 -04005637 exit(1);
5638 return spv::NoResult;
John Kessenich55e7d112015-11-15 21:33:39 -07005639}
5640
John Kessenich140f3df2015-06-26 16:58:36 -06005641// Use 'consts' as the flattened glslang source of scalar constants to recursively
5642// build the aggregate SPIR-V constant.
5643//
5644// If there are not enough elements present in 'consts', 0 will be substituted;
5645// an empty 'consts' can be used to create a fully zeroed SPIR-V constant.
5646//
qining08408382016-03-21 09:51:37 -04005647spv::Id TGlslangToSpvTraverser::createSpvConstantFromConstUnionArray(const glslang::TType& glslangType, const glslang::TConstUnionArray& consts, int& nextConst, bool specConstant)
John Kessenich140f3df2015-06-26 16:58:36 -06005648{
5649 // vector of constants for SPIR-V
5650 std::vector<spv::Id> spvConsts;
5651
5652 // Type is used for struct and array constants
5653 spv::Id typeId = convertGlslangToSpvType(glslangType);
5654
5655 if (glslangType.isArray()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005656 glslang::TType elementType(glslangType, 0);
5657 for (int i = 0; i < glslangType.getOuterArraySize(); ++i)
qining08408382016-03-21 09:51:37 -04005658 spvConsts.push_back(createSpvConstantFromConstUnionArray(elementType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005659 } else if (glslangType.isMatrix()) {
John Kessenich65c78a02015-08-10 17:08:55 -06005660 glslang::TType vectorType(glslangType, 0);
John Kessenich140f3df2015-06-26 16:58:36 -06005661 for (int col = 0; col < glslangType.getMatrixCols(); ++col)
qining08408382016-03-21 09:51:37 -04005662 spvConsts.push_back(createSpvConstantFromConstUnionArray(vectorType, consts, nextConst, false));
John Kessenich140f3df2015-06-26 16:58:36 -06005663 } else if (glslangType.getStruct()) {
5664 glslang::TVector<glslang::TTypeLoc>::const_iterator iter;
5665 for (iter = glslangType.getStruct()->begin(); iter != glslangType.getStruct()->end(); ++iter)
qining08408382016-03-21 09:51:37 -04005666 spvConsts.push_back(createSpvConstantFromConstUnionArray(*iter->type, consts, nextConst, false));
John Kessenich8d72f1a2016-05-20 12:06:03 -06005667 } else if (glslangType.getVectorSize() > 1) {
John Kessenich140f3df2015-06-26 16:58:36 -06005668 for (unsigned int i = 0; i < (unsigned int)glslangType.getVectorSize(); ++i) {
5669 bool zero = nextConst >= consts.size();
5670 switch (glslangType.getBasicType()) {
5671 case glslang::EbtInt:
5672 spvConsts.push_back(builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst()));
5673 break;
5674 case glslang::EbtUint:
5675 spvConsts.push_back(builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst()));
5676 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005677 case glslang::EbtInt64:
5678 spvConsts.push_back(builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const()));
5679 break;
5680 case glslang::EbtUint64:
5681 spvConsts.push_back(builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const()));
5682 break;
Rex Xucabbb782017-03-24 13:41:14 +08005683#ifdef AMD_EXTENSIONS
5684 case glslang::EbtInt16:
5685 spvConsts.push_back(builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst()));
5686 break;
5687 case glslang::EbtUint16:
5688 spvConsts.push_back(builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst()));
5689 break;
5690#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005691 case glslang::EbtFloat:
5692 spvConsts.push_back(builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5693 break;
5694 case glslang::EbtDouble:
5695 spvConsts.push_back(builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst()));
5696 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005697#ifdef AMD_EXTENSIONS
5698 case glslang::EbtFloat16:
5699 spvConsts.push_back(builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst()));
5700 break;
5701#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005702 case glslang::EbtBool:
5703 spvConsts.push_back(builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst()));
5704 break;
5705 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005706 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005707 break;
5708 }
5709 ++nextConst;
5710 }
5711 } else {
5712 // we have a non-aggregate (scalar) constant
5713 bool zero = nextConst >= consts.size();
5714 spv::Id scalar = 0;
5715 switch (glslangType.getBasicType()) {
5716 case glslang::EbtInt:
John Kessenich55e7d112015-11-15 21:33:39 -07005717 scalar = builder.makeIntConstant(zero ? 0 : consts[nextConst].getIConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005718 break;
5719 case glslang::EbtUint:
John Kessenich55e7d112015-11-15 21:33:39 -07005720 scalar = builder.makeUintConstant(zero ? 0 : consts[nextConst].getUConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005721 break;
Rex Xu8ff43de2016-04-22 16:51:45 +08005722 case glslang::EbtInt64:
5723 scalar = builder.makeInt64Constant(zero ? 0 : consts[nextConst].getI64Const(), specConstant);
5724 break;
5725 case glslang::EbtUint64:
5726 scalar = builder.makeUint64Constant(zero ? 0 : consts[nextConst].getU64Const(), specConstant);
5727 break;
Rex Xucabbb782017-03-24 13:41:14 +08005728#ifdef AMD_EXTENSIONS
5729 case glslang::EbtInt16:
5730 scalar = builder.makeInt16Constant(zero ? 0 : (short)consts[nextConst].getIConst(), specConstant);
5731 break;
5732 case glslang::EbtUint16:
5733 scalar = builder.makeUint16Constant(zero ? 0 : (unsigned short)consts[nextConst].getUConst(), specConstant);
5734 break;
5735#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005736 case glslang::EbtFloat:
John Kessenich55e7d112015-11-15 21:33:39 -07005737 scalar = builder.makeFloatConstant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005738 break;
5739 case glslang::EbtDouble:
John Kessenich55e7d112015-11-15 21:33:39 -07005740 scalar = builder.makeDoubleConstant(zero ? 0.0 : consts[nextConst].getDConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005741 break;
Rex Xuc9e3c3c2016-07-29 16:00:05 +08005742#ifdef AMD_EXTENSIONS
5743 case glslang::EbtFloat16:
5744 scalar = builder.makeFloat16Constant(zero ? 0.0F : (float)consts[nextConst].getDConst(), specConstant);
5745 break;
5746#endif
John Kessenich140f3df2015-06-26 16:58:36 -06005747 case glslang::EbtBool:
John Kessenich55e7d112015-11-15 21:33:39 -07005748 scalar = builder.makeBoolConstant(zero ? false : consts[nextConst].getBConst(), specConstant);
John Kessenich140f3df2015-06-26 16:58:36 -06005749 break;
5750 default:
John Kessenich55e7d112015-11-15 21:33:39 -07005751 assert(0);
John Kessenich140f3df2015-06-26 16:58:36 -06005752 break;
5753 }
5754 ++nextConst;
5755 return scalar;
5756 }
5757
5758 return builder.makeCompositeConstant(typeId, spvConsts);
5759}
5760
John Kessenich7c1aa102015-10-15 13:29:11 -06005761// Return true if the node is a constant or symbol whose reading has no
5762// non-trivial observable cost or effect.
5763bool TGlslangToSpvTraverser::isTrivialLeaf(const glslang::TIntermTyped* node)
5764{
5765 // don't know what this is
5766 if (node == nullptr)
5767 return false;
5768
5769 // a constant is safe
5770 if (node->getAsConstantUnion() != nullptr)
5771 return true;
5772
5773 // not a symbol means non-trivial
5774 if (node->getAsSymbolNode() == nullptr)
5775 return false;
5776
5777 // a symbol, depends on what's being read
5778 switch (node->getType().getQualifier().storage) {
5779 case glslang::EvqTemporary:
5780 case glslang::EvqGlobal:
5781 case glslang::EvqIn:
5782 case glslang::EvqInOut:
5783 case glslang::EvqConst:
5784 case glslang::EvqConstReadOnly:
5785 case glslang::EvqUniform:
5786 return true;
5787 default:
5788 return false;
5789 }
qining25262b32016-05-06 17:25:16 -04005790}
John Kessenich7c1aa102015-10-15 13:29:11 -06005791
5792// A node is trivial if it is a single operation with no side effects.
John Kessenich84cc15f2017-05-24 16:44:47 -06005793// HLSL (and/or vectors) are always trivial, as it does not short circuit.
John Kessenich0d2b4712017-05-19 20:19:00 -06005794// Otherwise, error on the side of saying non-trivial.
John Kessenich7c1aa102015-10-15 13:29:11 -06005795// Return true if trivial.
5796bool TGlslangToSpvTraverser::isTrivial(const glslang::TIntermTyped* node)
5797{
5798 if (node == nullptr)
5799 return false;
5800
John Kessenich84cc15f2017-05-24 16:44:47 -06005801 // count non scalars as trivial, as well as anything coming from HLSL
5802 if (! node->getType().isScalarOrVec1() || glslangIntermediate->getSource() == glslang::EShSourceHlsl)
John Kessenich0d2b4712017-05-19 20:19:00 -06005803 return true;
5804
John Kessenich7c1aa102015-10-15 13:29:11 -06005805 // symbols and constants are trivial
5806 if (isTrivialLeaf(node))
5807 return true;
5808
5809 // otherwise, it needs to be a simple operation or one or two leaf nodes
5810
5811 // not a simple operation
5812 const glslang::TIntermBinary* binaryNode = node->getAsBinaryNode();
5813 const glslang::TIntermUnary* unaryNode = node->getAsUnaryNode();
5814 if (binaryNode == nullptr && unaryNode == nullptr)
5815 return false;
5816
5817 // not on leaf nodes
5818 if (binaryNode && (! isTrivialLeaf(binaryNode->getLeft()) || ! isTrivialLeaf(binaryNode->getRight())))
5819 return false;
5820
5821 if (unaryNode && ! isTrivialLeaf(unaryNode->getOperand())) {
5822 return false;
5823 }
5824
5825 switch (node->getAsOperator()->getOp()) {
5826 case glslang::EOpLogicalNot:
5827 case glslang::EOpConvIntToBool:
5828 case glslang::EOpConvUintToBool:
5829 case glslang::EOpConvFloatToBool:
5830 case glslang::EOpConvDoubleToBool:
5831 case glslang::EOpEqual:
5832 case glslang::EOpNotEqual:
5833 case glslang::EOpLessThan:
5834 case glslang::EOpGreaterThan:
5835 case glslang::EOpLessThanEqual:
5836 case glslang::EOpGreaterThanEqual:
5837 case glslang::EOpIndexDirect:
5838 case glslang::EOpIndexDirectStruct:
5839 case glslang::EOpLogicalXor:
5840 case glslang::EOpAny:
5841 case glslang::EOpAll:
5842 return true;
5843 default:
5844 return false;
5845 }
5846}
5847
5848// Emit short-circuiting code, where 'right' is never evaluated unless
5849// the left side is true (for &&) or false (for ||).
5850spv::Id TGlslangToSpvTraverser::createShortCircuit(glslang::TOperator op, glslang::TIntermTyped& left, glslang::TIntermTyped& right)
5851{
5852 spv::Id boolTypeId = builder.makeBoolType();
5853
5854 // emit left operand
5855 builder.clearAccessChain();
5856 left.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005857 spv::Id leftId = accessChainLoad(left.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005858
5859 // Operands to accumulate OpPhi operands
5860 std::vector<spv::Id> phiOperands;
5861 // accumulate left operand's phi information
5862 phiOperands.push_back(leftId);
5863 phiOperands.push_back(builder.getBuildPoint()->getId());
5864
5865 // Make the two kinds of operation symmetric with a "!"
5866 // || => emit "if (! left) result = right"
5867 // && => emit "if ( left) result = right"
5868 //
5869 // TODO: this runtime "not" for || could be avoided by adding functionality
5870 // to 'builder' to have an "else" without an "then"
5871 if (op == glslang::EOpLogicalOr)
5872 leftId = builder.createUnaryOp(spv::OpLogicalNot, boolTypeId, leftId);
5873
5874 // make an "if" based on the left value
Rex Xu57e65922017-07-04 23:23:40 +08005875 spv::Builder::If ifBuilder(leftId, spv::SelectionControlMaskNone, builder);
John Kessenich7c1aa102015-10-15 13:29:11 -06005876
5877 // emit right operand as the "then" part of the "if"
5878 builder.clearAccessChain();
5879 right.traverse(this);
Rex Xub4fd8d12016-03-03 14:38:51 +08005880 spv::Id rightId = accessChainLoad(right.getType());
John Kessenich7c1aa102015-10-15 13:29:11 -06005881
5882 // accumulate left operand's phi information
5883 phiOperands.push_back(rightId);
5884 phiOperands.push_back(builder.getBuildPoint()->getId());
5885
5886 // finish the "if"
5887 ifBuilder.makeEndIf();
5888
5889 // phi together the two results
5890 return builder.createOp(spv::OpPhi, boolTypeId, phiOperands);
5891}
5892
Rex Xu9d93a232016-05-05 12:30:44 +08005893// Return type Id of the imported set of extended instructions corresponds to the name.
5894// Import this set if it has not been imported yet.
5895spv::Id TGlslangToSpvTraverser::getExtBuiltins(const char* name)
5896{
5897 if (extBuiltinMap.find(name) != extBuiltinMap.end())
5898 return extBuiltinMap[name];
5899 else {
Rex Xu51596642016-09-21 18:56:12 +08005900 builder.addExtension(name);
Rex Xu9d93a232016-05-05 12:30:44 +08005901 spv::Id extBuiltins = builder.import(name);
5902 extBuiltinMap[name] = extBuiltins;
5903 return extBuiltins;
5904 }
5905}
5906
John Kessenich140f3df2015-06-26 16:58:36 -06005907}; // end anonymous namespace
5908
5909namespace glslang {
5910
John Kessenich68d78fd2015-07-12 19:28:10 -06005911void GetSpirvVersion(std::string& version)
5912{
John Kessenich9e55f632015-07-15 10:03:39 -06005913 const int bufSize = 100;
John Kessenichf98ee232015-07-12 19:39:51 -06005914 char buf[bufSize];
John Kessenich55e7d112015-11-15 21:33:39 -07005915 snprintf(buf, bufSize, "0x%08x, Revision %d", spv::Version, spv::Revision);
John Kessenich68d78fd2015-07-12 19:28:10 -06005916 version = buf;
5917}
5918
John Kessenich140f3df2015-06-26 16:58:36 -06005919// Write SPIR-V out to a binary file
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005920void OutputSpvBin(const std::vector<unsigned int>& spirv, const char* baseName)
John Kessenich140f3df2015-06-26 16:58:36 -06005921{
5922 std::ofstream out;
John Kessenich68d78fd2015-07-12 19:28:10 -06005923 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005924 if (out.fail())
5925 printf("ERROR: Failed to open file: %s\n", baseName);
John Kessenich140f3df2015-06-26 16:58:36 -06005926 for (int i = 0; i < (int)spirv.size(); ++i) {
5927 unsigned int word = spirv[i];
5928 out.write((const char*)&word, 4);
5929 }
5930 out.close();
5931}
5932
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005933// Write SPIR-V out to a text file with 32-bit hexadecimal words
Flavioaea3c892017-02-06 11:46:35 -08005934void OutputSpvHex(const std::vector<unsigned int>& spirv, const char* baseName, const char* varName)
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005935{
5936 std::ofstream out;
5937 out.open(baseName, std::ios::binary | std::ios::out);
John Kessenich8f674e82017-02-18 09:45:40 -07005938 if (out.fail())
5939 printf("ERROR: Failed to open file: %s\n", baseName);
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005940 out << "\t// " GLSLANG_REVISION " " GLSLANG_DATE << std::endl;
Flavio15017db2017-02-15 14:29:33 -08005941 if (varName != nullptr) {
5942 out << "\t #pragma once" << std::endl;
5943 out << "const uint32_t " << varName << "[] = {" << std::endl;
5944 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005945 const int WORDS_PER_LINE = 8;
5946 for (int i = 0; i < (int)spirv.size(); i += WORDS_PER_LINE) {
5947 out << "\t";
5948 for (int j = 0; j < WORDS_PER_LINE && i + j < (int)spirv.size(); ++j) {
5949 const unsigned int word = spirv[i + j];
5950 out << "0x" << std::hex << std::setw(8) << std::setfill('0') << word;
5951 if (i + j + 1 < (int)spirv.size()) {
5952 out << ",";
5953 }
5954 }
5955 out << std::endl;
5956 }
Flavio15017db2017-02-15 14:29:33 -08005957 if (varName != nullptr) {
5958 out << "};";
5959 }
Johannes van Waverenecb0f3b2016-05-27 12:55:53 -05005960 out.close();
5961}
5962
John Kessenich140f3df2015-06-26 16:58:36 -06005963//
5964// Set up the glslang traversal
5965//
John Kessenich121853f2017-05-31 17:11:16 -06005966void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv, SpvOptions* options)
John Kessenich140f3df2015-06-26 16:58:36 -06005967{
Lei Zhang17535f72016-05-04 15:55:59 -04005968 spv::SpvBuildLogger logger;
John Kessenich121853f2017-05-31 17:11:16 -06005969 GlslangToSpv(intermediate, spirv, &logger, options);
Lei Zhang09caf122016-05-02 18:11:54 -04005970}
5971
John Kessenich121853f2017-05-31 17:11:16 -06005972void GlslangToSpv(const glslang::TIntermediate& intermediate, std::vector<unsigned int>& spirv,
5973 spv::SpvBuildLogger* logger, SpvOptions* options)
Lei Zhang09caf122016-05-02 18:11:54 -04005974{
John Kessenich140f3df2015-06-26 16:58:36 -06005975 TIntermNode* root = intermediate.getTreeRoot();
5976
5977 if (root == 0)
5978 return;
5979
John Kessenich121853f2017-05-31 17:11:16 -06005980 glslang::SpvOptions defaultOptions;
5981 if (options == nullptr)
5982 options = &defaultOptions;
5983
John Kessenich140f3df2015-06-26 16:58:36 -06005984 glslang::GetThreadPoolAllocator().push();
5985
John Kessenich121853f2017-05-31 17:11:16 -06005986 TGlslangToSpvTraverser it(&intermediate, logger, *options);
John Kessenich140f3df2015-06-26 16:58:36 -06005987 root->traverse(&it);
John Kessenichfca82622016-11-26 13:23:20 -07005988 it.finishSpv();
John Kessenich140f3df2015-06-26 16:58:36 -06005989 it.dumpSpv(spirv);
5990
5991 glslang::GetThreadPoolAllocator().pop();
5992}
5993
5994}; // end namespace glslang